10 #ifdef HAVE_SYS_TIME_H
11 # include <sys/time.h> // gettimeofday
16 #include <sys/types.h>
21 #include <simgear/nasal/nasal.h>
22 #include <simgear/props/props.hxx>
23 #include <simgear/math/sg_random.h>
24 #include <simgear/misc/sg_path.hxx>
25 #include <simgear/misc/sg_dir.hxx>
26 #include <simgear/structure/commands.hxx>
27 #include <simgear/math/sg_geodesy.hxx>
28 #include <simgear/structure/event_mgr.hxx>
29 #include <simgear/debug/BufferedLogCallback.hxx>
31 #include <simgear/nasal/cppbind/from_nasal.hxx>
32 #include <simgear/nasal/cppbind/to_nasal.hxx>
33 #include <simgear/nasal/cppbind/Ghost.hxx>
34 #include <simgear/nasal/cppbind/NasalHash.hxx>
36 #include "NasalSys.hxx"
37 #include "NasalSys_private.hxx"
38 #include "NasalModelData.hxx"
39 #include "NasalPositioned.hxx"
40 #include "NasalCanvas.hxx"
41 #include "NasalClipboard.hxx"
42 #include "NasalCondition.hxx"
43 #include "NasalString.hxx"
45 #include <Main/globals.hxx>
46 #include <Main/util.hxx>
47 #include <Main/fg_props.hxx>
51 void postinitNasalGUI(naRef globals, naContext c);
53 static FGNasalSys* nasalSys = 0;
55 // Listener class for loading Nasal modules on demand
56 class FGNasalModuleListener : public SGPropertyChangeListener
59 FGNasalModuleListener(SGPropertyNode* node);
61 virtual void valueChanged(SGPropertyNode* node);
64 SGPropertyNode_ptr _node;
67 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
71 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
73 if (_node->getBoolValue("enabled",false)&&
74 !_node->getBoolValue("loaded",true))
76 nasalSys->loadPropertyScripts(_node);
80 //////////////////////////////////////////////////////////////////////////
83 class TimerObj : public SGReferenced
86 TimerObj(FGNasalSys* sys, naRef f, naRef self, double interval) :
95 snprintf(nm, 128, "nasal-timer-%p", this);
97 _gcRoot = sys->gcSave(f);
98 _gcSelf = sys->gcSave(self);
104 _sys->gcRelease(_gcRoot);
105 _sys->gcRelease(_gcSelf);
108 bool isRunning() const { return _isRunning; }
113 globals->get_event_mgr()->removeTask(_name);
126 globals->get_event_mgr()->addEvent(_name, this, &TimerObj::invoke, _interval);
128 globals->get_event_mgr()->addTask(_name, this, &TimerObj::invoke, _interval);
132 // stop and then start -
133 void restart(double newInterval)
135 _interval = newInterval;
143 _sys->callMethod(_func, _self, 0, args, naNil() /* locals */);
149 void setSingleShot(bool aSingleShot)
151 _singleShot = aSingleShot;
154 bool isSingleShot() const
155 { return _singleShot; }
160 int _gcRoot, _gcSelf;
166 typedef SGSharedPtr<TimerObj> TimerObjRef;
167 typedef nasal::Ghost<TimerObjRef> NasalTimerObj;
169 ///////////////////////////////////////////////////////////////////////////
171 // Read and return file contents in a single buffer. Note use of
172 // stat() to get the file size. This is a win32 function, believe it
173 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
174 // Text mode brain damage will kill us if we're trying to do bytewise
176 static char* readfile(const char* file, int* lenOut)
179 if(stat(file, &data) != 0) return 0;
180 FILE* f = fopen(file, "rb");
182 char* buf = new char[data.st_size];
183 *lenOut = fread(buf, 1, data.st_size, f);
185 if(*lenOut != data.st_size) {
186 // Shouldn't happen, but warn anyway since it represents a
187 // platform bug and not a typical runtime error (missing file,
189 SG_LOG(SG_NASAL, SG_ALERT,
190 "ERROR in Nasal initialization: " <<
191 "short count returned from fread() of " << file <<
192 ". Check your C library!");
199 FGNasalSys::FGNasalSys()
207 _log = new simgear::BufferedLogCallback(SG_NASAL, SG_INFO);
208 _log->truncateAt(255);
209 sglog().addCallback(_log);
212 // Utility. Sets a named key in a hash by C string, rather than nasal
214 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
216 naRef s = naNewString(_context);
217 naStr_fromdata(s, (char*)key, strlen(key));
218 naHash_set(hash, s, val);
221 void FGNasalSys::globalsSet(const char* key, naRef val)
223 hashset(_globals, key, val);
226 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
228 return callMethod(code, naNil(), argc, args, locals);
231 // Does a naCall() in a new context. Wrapped here to make lock
232 // tracking easier. Extension functions are called with the lock, but
233 // we have to release it before making a new naCall(). So rather than
234 // drop the lock in every extension function that might call back into
235 // Nasal, we keep a stack depth counter here and only unlock/lock
236 // around the naCall if it isn't the first one.
238 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
240 naContext ctx = naNewContext();
241 if(_callCount) naModUnlock();
243 naRef result = naCall(ctx, code, argc, args, self, locals);
247 if(_callCount) naModLock();
252 FGNasalSys::~FGNasalSys()
255 map<int, FGNasalListener *>::iterator it, end = _listener.end();
256 for(it = _listener.begin(); it != end; ++it)
259 naFreeContext(_context);
264 bool FGNasalSys::parseAndRun(const char* sourceCode)
266 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
270 call(code, 0, 0, naNil());
275 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
277 FGNasalScript* script = new FGNasalScript();
278 script->_gcKey = -1; // important, if we delete it on a parse
279 script->_nas = this; // error, don't clobber a real handle!
283 sprintf(buf, "FGNasalScript@%p", (void *)script);
287 script->_code = parse(name, src, strlen(src));
288 if(naIsNil(script->_code)) {
293 script->_gcKey = gcSave(script->_code);
298 // The get/setprop functions accept a *list* of strings and walk
299 // through the property tree with them to find the appropriate node.
300 // This allows a Nasal object to hold onto a property path and use it
301 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
302 // is the utility function that walks the property tree.
303 // Future enhancement: support integer arguments to specify array
305 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
307 SGPropertyNode* p = globals->get_props();
309 for(int i=0; i<len; i++) {
311 if(!naIsString(a)) return 0;
312 p = p->getNode(naStr_data(a));
315 } catch (const string& err) {
316 naRuntimeError(c, (char *)err.c_str());
322 // getprop() extension function. Concatenates its string arguments as
323 // property names and returns the value of the specified property. Or
324 // nil if it doesn't exist.
325 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
327 using namespace simgear;
328 const SGPropertyNode* p = findnode(c, args, argc);
329 if(!p) return naNil();
331 switch(p->getType()) {
332 case props::BOOL: case props::INT:
333 case props::LONG: case props::FLOAT:
336 double dv = p->getDoubleValue();
337 if (SGMisc<double>::isNaN(dv)) {
338 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
346 case props::UNSPECIFIED:
348 naRef nastr = naNewString(c);
349 const char* val = p->getStringValue();
350 naStr_fromdata(nastr, (char*)val, strlen(val));
353 case props::ALIAS: // <--- FIXME, recurse?
359 // setprop() extension function. Concatenates its string arguments as
360 // property names and sets the value of the specified property to the
362 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
365 char buf[BUFLEN + 1];
369 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
370 for(int i=0; i<argc-1; i++) {
371 naRef s = naStringValue(c, args[i]);
372 if(naIsNil(s)) return naNil();
373 strncpy(p, naStr_data(s), buflen);
375 buflen = BUFLEN - (p - buf);
376 if(i < (argc-2) && buflen > 0) {
382 SGPropertyNode* props = globals->get_props();
383 naRef val = args[argc-1];
386 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
388 naRef n = naNumValue(val);
390 naRuntimeError(c, "setprop() value is not string or number");
392 if (SGMisc<double>::isNaN(n.num)) {
393 naRuntimeError(c, "setprop() passed a NaN");
396 result = props->setDoubleValue(buf, n.num);
398 } catch (const string& err) {
399 naRuntimeError(c, (char *)err.c_str());
401 return naNum(result);
405 // print() extension function. Concatenates and prints its arguments
406 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
407 // make sure it appears. Is there better way to do this?
408 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
412 for(int i=0; i<n; i++) {
413 naRef s = naStringValue(c, args[i]);
414 if(naIsNil(s)) continue;
415 buf += naStr_data(s);
417 SG_LOG(SG_NASAL, SG_ALERT, buf);
418 return naNum(buf.length());
421 // logprint() extension function. Same as above, all arguments after the
422 // first argument are concatenated. Argument 0 is the log-level, matching
424 static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
427 naRuntimeError(c, "no prioirty argument to logprint()");
429 naRef priority = args[0];
432 for(int i=1; i<n; i++) {
433 naRef s = naStringValue(c, args[i]);
434 if(naIsNil(s)) continue;
435 buf += naStr_data(s);
437 // use the nasal source file and line for the message location, since
438 // that's more useful than the location here!
439 sglog().log(SG_NASAL, (sgDebugPriority)(int) priority.num,
440 naStr_data(naGetSourceFile(c, 0)),
441 naGetLine(c, 0), buf);
442 return naNum(buf.length());
446 // fgcommand() extension function. Executes a named command via the
447 // FlightGear command manager. Takes a single property node name as
449 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
451 naRef cmd = argc > 0 ? args[0] : naNil();
452 naRef props = argc > 1 ? args[1] : naNil();
453 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
454 naRuntimeError(c, "bad arguments to fgcommand()");
455 SGPropertyNode_ptr tmp, *node;
457 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
459 tmp = new SGPropertyNode();
462 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
465 // settimer(func, dt, simtime) extension function. Falls through to
466 // FGNasalSys::setTimer(). See there for docs.
467 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
469 nasalSys->setTimer(c, argc, args);
473 static naRef f_makeTimer(naContext c, naRef me, int argc, naRef* args)
475 if (!naIsNum(args[0])) {
476 naRuntimeError(c, "bad interval argument to maketimer");
479 naRef func, self = naNil();
480 if (naIsFunc(args[1])) {
482 } else if ((argc == 3) && naIsFunc(args[2])) {
487 TimerObj* timerObj = new TimerObj(nasalSys, func, self, args[0].num);
488 return NasalTimerObj::create(c, timerObj);
491 // setlistener(func, property, bool) extension function. Falls through to
492 // FGNasalSys::setListener(). See there for docs.
493 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
495 return nasalSys->setListener(c, argc, args);
498 // removelistener(int) extension function. Falls through to
499 // FGNasalSys::removeListener(). See there for docs.
500 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
502 return nasalSys->removeListener(c, argc, args);
505 // Returns a ghost handle to the argument to the currently executing
507 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
509 return nasalSys->cmdArgGhost();
512 // Sets up a property interpolation. The first argument is either a
513 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
514 // interpolate. The second argument is a vector of pairs of
515 // value/delta numbers.
516 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
518 SGPropertyNode* node;
519 naRef prop = argc > 0 ? args[0] : naNil();
520 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
521 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
524 naRef curve = argc > 1 ? args[1] : naNil();
525 if(!naIsVector(curve)) return naNil();
526 int nPoints = naVec_size(curve) / 2;
528 simgear::PropertyList value_nodes;
529 value_nodes.reserve(nPoints);
531 deltas.reserve(nPoints);
533 for( int i = 0; i < nPoints; ++i )
535 SGPropertyNode* val = new SGPropertyNode;
536 val->setDoubleValue(naNumValue(naVec_get(curve, 2*i)).num);
537 value_nodes.push_back(val);
538 deltas.push_back(naNumValue(naVec_get(curve, 2*i+1)).num);
541 node->interpolate("numeric", value_nodes, deltas, "linear");
545 // This is a better RNG than the one in the default Nasal distribution
546 // (which is based on the C library rand() implementation). It will
548 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
550 return naNum(sg_random());
553 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
559 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
565 // Return an array listing of all files in a directory
566 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
568 if(argc != 1 || !naIsString(args[0]))
569 naRuntimeError(c, "bad arguments to directory()");
571 simgear::Dir d(SGPath(naStr_data(args[0])));
572 if(!d.exists()) return naNil();
573 naRef result = naNewVector(c);
575 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
576 for (unsigned int i=0; i<paths.size(); ++i) {
577 std::string p = paths[i].file();
578 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
585 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
587 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
589 if(argc != 1 || !naIsString(args[0]))
590 naRuntimeError(c, "bad arguments to resolveDataPath()");
592 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
593 const char* pdata = p.c_str();
594 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
597 static naRef f_findDataDir(naContext c, naRef me, int argc, naRef* args)
599 if(argc != 1 || !naIsString(args[0]))
600 naRuntimeError(c, "bad arguments to findDataDir()");
602 SGPath p = globals->find_data_dir(naStr_data(args[0]));
603 const char* pdata = p.c_str();
604 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
607 class NasalCommand : public SGCommandMgr::Command
610 NasalCommand(FGNasalSys* sys, naRef f) :
614 _gcRoot = sys->gcSave(f);
617 virtual ~NasalCommand()
619 _sys->gcRelease(_gcRoot);
622 virtual bool operator()(const SGPropertyNode* aNode)
624 _sys->setCmdArg(const_cast<SGPropertyNode*>(aNode));
626 args[0] = _sys->wrappedPropsNode(const_cast<SGPropertyNode*>(aNode));
628 _sys->callMethod(_func, naNil(), 1, args, naNil() /* locals */);
639 static naRef f_addCommand(naContext c, naRef me, int argc, naRef* args)
641 if(argc != 2 || !naIsString(args[0]) || !naIsFunc(args[1]))
642 naRuntimeError(c, "bad arguments to addcommand()");
644 naRef func = args[1];
645 NasalCommand* cmd = new NasalCommand(nasalSys, func);
646 globals->get_commands()->addCommandObject(naStr_data(args[0]), cmd);
650 static naRef f_removeCommand(naContext c, naRef me, int argc, naRef* args)
652 SGCommandMgr::Command* cmd = globals->get_commands()->getCommand(naStr_data(args[0]));
654 // SGCommandMgr::Command* cmd = globals->get_commands()->removeCommand(naStr_data(args[0]))
662 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
664 // <path> ... absolute path to an XML file
665 // <start-tag> ... callback function with two args: tag name, attribute hash
666 // <end-tag> ... callback function with one arg: tag name
667 // <data> ... callback function with one arg: data
668 // <pi> ... callback function with two args: target, data
669 // (pi = "processing instruction")
670 // All four callback functions are optional and default to nil.
671 // The function returns nil on error, or the validated file name otherwise.
672 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
674 if(argc < 1 || !naIsString(args[0]))
675 naRuntimeError(c, "parsexml(): path argument missing or not a string");
676 if(argc > 5) argc = 5;
677 for(int i=1; i<argc; i++)
678 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
679 naRuntimeError(c, "parsexml(): callback argument not a function");
681 const char* file = fgValidatePath(naStr_data(args[0]), false);
683 naRuntimeError(c, "parsexml(): reading '%s' denied "
684 "(unauthorized access)", naStr_data(args[0]));
687 std::ifstream input(file);
688 NasalXMLVisitor visitor(c, argc, args);
690 readXML(input, visitor);
691 } catch (const sg_exception& e) {
692 naRuntimeError(c, "parsexml(): file '%s' %s",
693 file, e.getFormattedMessage().c_str());
696 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
699 // Return UNIX epoch time in seconds.
700 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
704 GetSystemTimeAsFileTime(&ft);
705 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
706 // Converts from 100ns units in 1601 epoch to unix epoch in sec
707 return naNum((t * 1e-7) - 11644473600.0);
710 gettimeofday(&td, 0);
711 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
715 // Table of extension functions. Terminate with zeros.
716 static struct { const char* name; naCFunction func; } funcs[] = {
717 { "getprop", f_getprop },
718 { "setprop", f_setprop },
719 { "print", f_print },
720 { "logprint", f_logprint },
721 { "_fgcommand", f_fgcommand },
722 { "settimer", f_settimer },
723 { "maketimer", f_makeTimer },
724 { "_setlistener", f_setlistener },
725 { "removelistener", f_removelistener },
726 { "addcommand", f_addCommand },
727 { "removecommand", f_removeCommand },
728 { "_cmdarg", f_cmdarg },
729 { "_interpolate", f_interpolate },
731 { "srand", f_srand },
732 { "abort", f_abort },
733 { "directory", f_directory },
734 { "resolvepath", f_resolveDataPath },
735 { "finddata", f_findDataDir },
736 { "parsexml", f_parsexml },
737 { "systime", f_systime },
741 naRef FGNasalSys::cmdArgGhost()
743 return propNodeGhost(_cmdArg);
746 void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
751 void FGNasalSys::init()
755 _context = naNewContext();
757 // Start with globals. Add it to itself as a recursive
758 // sub-reference under the name "globals". This gives client-code
759 // write access to the namespace if someone wants to do something
761 _globals = naInit_std(_context);
762 naSave(_context, _globals);
763 hashset(_globals, "globals", _globals);
765 hashset(_globals, "math", naInit_math(_context));
766 hashset(_globals, "bits", naInit_bits(_context));
767 hashset(_globals, "io", naInit_io(_context));
768 hashset(_globals, "thread", naInit_thread(_context));
769 hashset(_globals, "utf8", naInit_utf8(_context));
771 // Add our custom extension functions:
772 for(i=0; funcs[i].name; i++)
773 hashset(_globals, funcs[i].name,
774 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
776 // And our SGPropertyNode wrapper
777 hashset(_globals, "props", genPropsModule());
779 // Add string methods
780 _string = naInit_string(_context);
781 naSave(_context, _string);
782 initNasalString(_globals, _string, _context);
784 initNasalPositioned(_globals, _context);
785 initNasalPositioned_cppbind(_globals, _context);
786 NasalClipboard::init(this);
787 initNasalCanvas(_globals, _context);
788 initNasalCondition(_globals, _context);
790 NasalTimerObj::init("Timer")
791 .method("start", &TimerObj::start)
792 .method("stop", &TimerObj::stop)
793 .method("restart", &TimerObj::restart)
794 .member("singleShot", &TimerObj::isSingleShot, &TimerObj::setSingleShot)
795 .member("isRunning", &TimerObj::isRunning);
797 // Now load the various source files in the Nasal directory
798 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
799 loadScriptDirectory(nasalDir);
801 // Add modules in Nasal subdirectories to property tree
802 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
803 simgear::Dir::NO_DOT_OR_DOTDOT, "");
804 for (unsigned int i=0; i<directories.size(); ++i) {
805 simgear::Dir dir(directories[i]);
806 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
807 addModule(directories[i].file(), scripts);
810 // set signal and remove node to avoid restoring at reinit
811 const char *s = "nasal-dir-initialized";
812 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
813 signal->setBoolValue(s, true);
814 signal->removeChildren(s, false);
816 // Pull scripts out of the property tree, too
817 loadPropertyScripts();
819 // now Nasal modules are loaded, we can do some delayed work
820 postinitNasalPositioned(_globals, _context);
821 postinitNasalGUI(_globals, _context);
824 naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps)
826 static naRef wrapNodeFunc = naNil();
827 if (naIsNil(wrapNodeFunc)) {
828 nasal::Hash props = getGlobals().get<nasal::Hash>("props");
829 wrapNodeFunc = props.get("wrapNode");
833 args[0] = propNodeGhost(aProps);
834 return naCall(_context, wrapNodeFunc, 1, args, naNil(), naNil());
837 void FGNasalSys::update(double)
839 if( NasalClipboard::getInstance() )
840 NasalClipboard::getInstance()->update();
842 if(!_dead_listener.empty()) {
843 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
844 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
845 _dead_listener.clear();
848 if (!_loadList.empty())
853 // process Nasal load hook (only one per update loop to avoid excessive lags)
854 _loadList.pop()->load();
857 if (!_unloadList.empty())
859 // process pending Nasal unload hooks after _all_ load hooks were processed
860 // (only unload one per update loop to avoid excessive lags)
861 _unloadList.pop()->unload();
864 // The global context is a legacy thing. We use dynamically
865 // created contexts for naCall() now, so that we can call them
866 // recursively. But there are still spots that want to use it for
867 // naNew*() calls, which end up leaking memory because the context
868 // only clears out its temporary vector when it's *used*. So just
869 // junk it and fetch a new/reinitialized one every frame. This is
870 // clumsy: the right solution would use the dynamic context in all
871 // cases and eliminate _context entirely. But that's more work,
872 // and this works fine (yes, they say "New" and "Free", but
873 // they're very fast, just trust me). -Andy
874 naFreeContext(_context);
875 _context = naNewContext();
878 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
880 return p1.file() < p2.file();
883 // Loads all scripts in given directory
884 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
886 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
887 // Note: simgear::Dir already reports file entries in a deterministic order,
888 // so a fixed loading sequence is guaranteed (same for every user)
889 for (unsigned int i=0; i<scripts.size(); ++i) {
890 SGPath fullpath(scripts[i]);
891 SGPath file = fullpath.file();
892 loadModule(fullpath, file.base().c_str());
896 // Create module with list of scripts
897 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
899 if (! scripts.empty())
901 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
902 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
903 for (unsigned int i=0; i<scripts.size(); ++i) {
904 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
905 pFileNode->setStringValue(scripts[i].c_str());
907 if (!module_node->hasChild("enabled",0))
909 SGPropertyNode* node = module_node->getChild("enabled",0,true);
910 node->setBoolValue(true);
911 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
916 // Loads the scripts found under /nasal in the global tree
917 void FGNasalSys::loadPropertyScripts()
919 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
922 for(int i=0; i<nasal->nChildren(); i++)
924 SGPropertyNode* n = nasal->getChild(i);
925 loadPropertyScripts(n);
929 // Loads the scripts found under /nasal in the global tree
930 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
932 bool is_loaded = false;
934 const char* module = n->getName();
935 if(n->hasChild("module"))
936 module = n->getStringValue("module");
937 if (n->getBoolValue("enabled",true))
939 // allow multiple files to be specified within a single
943 bool file_specified = false;
945 while((fn = n->getChild("file", j)) != NULL) {
946 file_specified = true;
947 const char* file = fn->getStringValue();
949 if (!p.isAbsolute() || !p.exists())
951 p = globals->resolve_maybe_aircraft_path(file);
954 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
955 file << "' for module '" << module << "'.");
958 ok &= p.isNull() ? false : loadModule(p, module);
962 const char* src = n->getStringValue("script");
963 if(!n->hasChild("script")) src = 0; // Hrm...
965 createModule(module, n->getPath().c_str(), src, strlen(src));
967 if(!file_specified && !src)
969 // module no longer exists - clear the archived "enable" flag
970 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
971 SGPropertyNode* node = n->getChild("enabled",0,false);
973 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
975 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
976 "no <file> or <script> defined in " <<
977 "/nasal/" << module);
984 SGPropertyNode* enable = n->getChild("enabled");
987 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
988 enable->addChangeListener(listener, false);
991 SGPropertyNode* loaded = n->getChild("loaded",0,true);
992 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
993 loaded->setBoolValue(is_loaded);
996 // Logs a runtime error, with stack trace, to the FlightGear log stream
997 void FGNasalSys::logError(naContext context)
999 SG_LOG(SG_NASAL, SG_ALERT,
1000 "Nasal runtime error: " << naGetError(context));
1001 SG_LOG(SG_NASAL, SG_ALERT,
1002 " at " << naStr_data(naGetSourceFile(context, 0)) <<
1003 ", line " << naGetLine(context, 0));
1004 for(int i=1; i<naStackDepth(context); i++)
1005 SG_LOG(SG_NASAL, SG_ALERT,
1006 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
1007 ", line " << naGetLine(context, i));
1010 // Reads a script file, executes it, and places the resulting
1011 // namespace into the global namespace under the specified module
1013 bool FGNasalSys::loadModule(SGPath file, const char* module)
1016 char* buf = readfile(file.c_str(), &len);
1018 SG_LOG(SG_NASAL, SG_ALERT,
1019 "Nasal error: could not read script file " << file.c_str()
1020 << " into module " << module);
1024 bool ok = createModule(module, file.c_str(), buf, len);
1029 // Parse and run. Save the local variables namespace, as it will
1030 // become a sub-object of globals. The optional "arg" argument can be
1031 // used to pass an associated property node to the module, which can then
1032 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
1033 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1034 const char* src, int len,
1035 const SGPropertyNode* cmdarg,
1036 int argc, naRef* args)
1038 naRef code = parse(fileName, src, len);
1042 // See if we already have a module hash to use. This allows the
1043 // user to, for example, add functions to the built-in math
1044 // module. Make a new one if necessary.
1046 naRef modname = naNewString(_context);
1047 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1048 if(!naHash_get(_globals, modname, &locals))
1049 locals = naNewHash(_context);
1051 _cmdArg = (SGPropertyNode*)cmdarg;
1053 call(code, argc, args, locals);
1054 hashset(_globals, moduleName, locals);
1058 void FGNasalSys::deleteModule(const char* moduleName)
1060 naRef modname = naNewString(_context);
1061 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1062 naHash_delete(_globals, modname);
1065 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
1068 naRef srcfile = naNewString(_context);
1069 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1070 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
1072 SG_LOG(SG_NASAL, SG_ALERT,
1073 "Nasal parse error: " << naGetError(_context) <<
1074 " in "<< filename <<", line " << errLine);
1078 // Bind to the global namespace before returning
1079 return naBindFunction(_context, code, _globals);
1082 bool FGNasalSys::handleCommand( const char* moduleName,
1083 const char* fileName,
1085 const SGPropertyNode* arg )
1087 naRef code = parse(fileName, src, strlen(src));
1088 if(naIsNil(code)) return false;
1090 // Commands can be run "in" a module. Make sure that module
1091 // exists, and set it up as the local variables hash for the
1093 naRef locals = naNil();
1095 naRef modname = naNewString(_context);
1096 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1097 if(!naHash_get(_globals, modname, &locals)) {
1098 locals = naNewHash(_context);
1099 naHash_set(_globals, modname, locals);
1103 // Cache this command's argument for inspection via cmdarg(). For
1104 // performance reasons, we won't bother with it if the invoked
1105 // code doesn't need it.
1106 _cmdArg = (SGPropertyNode*)arg;
1108 call(code, 0, 0, locals);
1112 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1114 const char* src = arg->getStringValue("script");
1115 const char* moduleName = arg->getStringValue("module");
1117 return handleCommand( moduleName,
1118 arg ? arg->getPath(true).c_str() : moduleName,
1123 // settimer(func, dt, simtime) extension function. The first argument
1124 // is a Nasal function to call, the second is a delta time (from now),
1125 // in seconds. The third, if present, is a boolean value indicating
1126 // that "real world" time (rather than simulator time) is to be used.
1128 // Implementation note: the FGTimer objects don't live inside the
1129 // garbage collector, so the Nasal handler functions have to be
1130 // "saved" somehow lest they be inadvertently cleaned. In this case,
1131 // they are inserted into a globals.__gcsave hash and removed on
1133 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1135 // Extract the handler, delta, and simtime arguments:
1136 naRef handler = argc > 0 ? args[0] : naNil();
1137 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1138 naRuntimeError(c, "settimer() with invalid function argument");
1142 naRef delta = argc > 1 ? args[1] : naNil();
1143 if(naIsNil(delta)) {
1144 naRuntimeError(c, "settimer() with invalid time argument");
1148 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1150 // Generate and register a C++ timer handler
1151 NasalTimer* t = new NasalTimer;
1152 t->handler = handler;
1153 t->gcKey = gcSave(handler);
1156 globals->get_event_mgr()->addEvent("NasalTimer",
1157 t, &NasalTimer::timerExpired,
1158 delta.num, simtime);
1161 void FGNasalSys::handleTimer(NasalTimer* t)
1163 call(t->handler, 0, 0, naNil());
1164 gcRelease(t->gcKey);
1167 int FGNasalSys::gcSave(naRef r)
1172 void FGNasalSys::gcRelease(int key)
1177 void FGNasalSys::NasalTimer::timerExpired()
1179 nasal->handleTimer(this);
1183 int FGNasalSys::_listenerId = 0;
1185 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1186 // Attaches a callback function to a property (specified as a global
1187 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1188 // optional argument (default=0) is set to 1, then the function is also
1189 // called initially. If the fourth, optional argument is set to 0, then the
1190 // function is only called when the property node value actually changes.
1191 // Otherwise it's called independent of the value whenever the node is
1192 // written to (default). The setlistener() function returns a unique
1193 // id number, which is to be used as argument to the removelistener()
1195 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1197 SGPropertyNode_ptr node;
1198 naRef prop = argc > 0 ? args[0] : naNil();
1199 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1200 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1202 naRuntimeError(c, "setlistener() with invalid property argument");
1207 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1210 naRef code = argc > 1 ? args[1] : naNil();
1211 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1212 naRuntimeError(c, "setlistener() with invalid function argument");
1216 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1217 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1218 FGNasalListener *nl = new FGNasalListener(node, code, this,
1219 gcSave(code), _listenerId, init, type);
1221 node->addChangeListener(nl, init != 0);
1223 _listener[_listenerId] = nl;
1224 return naNum(_listenerId++);
1227 // removelistener(int) extension function. The argument is the id of
1228 // a listener as returned by the setlistener() function.
1229 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1231 naRef id = argc > 0 ? args[0] : naNil();
1232 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1234 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1235 naRuntimeError(c, "removelistener() with invalid listener id");
1239 it->second->_dead = true;
1240 _dead_listener.push_back(it->second);
1241 _listener.erase(it);
1242 return naNum(_listener.size());
1245 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1247 if( _loadList.empty() )
1249 _loadList.push(data);
1252 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1254 _unloadList.push(data);
1257 //////////////////////////////////////////////////////////////////////////
1258 // FGNasalListener class.
1260 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1261 FGNasalSys* nasal, int key, int id,
1262 int init, int type) :
1275 if(_type == 0 && !_init)
1279 FGNasalListener::~FGNasalListener()
1281 _node->removeChangeListener(this);
1282 _nas->gcRelease(_gcKey);
1285 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1287 if(_active || _dead) return;
1290 arg[0] = _nas->propNodeGhost(which);
1291 arg[1] = _nas->propNodeGhost(_node);
1292 arg[2] = mode; // value changed, child added/removed
1293 arg[3] = naNum(_node != which); // child event?
1294 _nas->call(_code, 4, arg, naNil());
1298 void FGNasalListener::valueChanged(SGPropertyNode* node)
1300 if(_type < 2 && node != _node) return; // skip child events
1301 if(_type > 0 || changed(_node) || _init)
1302 call(node, naNum(0));
1307 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1309 if(_type == 2) call(child, naNum(1));
1312 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1314 if(_type == 2) call(child, naNum(-1));
1317 bool FGNasalListener::changed(SGPropertyNode* node)
1319 using namespace simgear;
1320 props::Type type = node->getType();
1321 if(type == props::NONE) return false;
1322 if(type == props::UNSPECIFIED) return true;
1330 long l = node->getLongValue();
1331 result = l != _last_int;
1338 double d = node->getDoubleValue();
1339 result = d != _last_float;
1345 string s = node->getStringValue();
1346 result = s != _last_string;
1353 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1355 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1356 _c(naSubContext(c)),
1357 _start_element(argc > 1 ? args[1] : naNil()),
1358 _end_element(argc > 2 ? args[2] : naNil()),
1359 _data(argc > 3 ? args[3] : naNil()),
1360 _pi(argc > 4 ? args[4] : naNil())
1364 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1366 if(naIsNil(_start_element)) return;
1367 naRef attr = naNewHash(_c);
1368 for(int i=0; i<a.size(); i++) {
1369 naRef name = make_string(a.getName(i));
1370 naRef value = make_string(a.getValue(i));
1371 naHash_set(attr, name, value);
1373 call(_start_element, 2, make_string(tag), attr);
1376 void NasalXMLVisitor::endElement(const char* tag)
1378 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1381 void NasalXMLVisitor::data(const char* str, int len)
1383 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1386 void NasalXMLVisitor::pi(const char* target, const char* data)
1388 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1391 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1396 naCall(_c, func, num, args, naNil(), naNil());
1401 naRef NasalXMLVisitor::make_string(const char* s, int n)
1403 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1404 n < 0 ? strlen(s) : n);