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 "NasalHTTP.hxx"
44 #include "NasalString.hxx"
46 #include <Main/globals.hxx>
47 #include <Main/util.hxx>
48 #include <Main/fg_props.hxx>
54 void postinitNasalGUI(naRef globals, naContext c);
56 static FGNasalSys* nasalSys = 0;
58 // Listener class for loading Nasal modules on demand
59 class FGNasalModuleListener : public SGPropertyChangeListener
62 FGNasalModuleListener(SGPropertyNode* node);
64 virtual void valueChanged(SGPropertyNode* node);
67 SGPropertyNode_ptr _node;
70 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
74 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
76 if (_node->getBoolValue("enabled",false)&&
77 !_node->getBoolValue("loaded",true))
79 nasalSys->loadPropertyScripts(_node);
83 //////////////////////////////////////////////////////////////////////////
86 class TimerObj : public SGReferenced
89 TimerObj(FGNasalSys* sys, naRef f, naRef self, double interval) :
98 snprintf(nm, 128, "nasal-timer-%p", this);
100 _gcRoot = sys->gcSave(f);
101 _gcSelf = sys->gcSave(self);
107 _sys->gcRelease(_gcRoot);
108 _sys->gcRelease(_gcSelf);
111 bool isRunning() const { return _isRunning; }
116 globals->get_event_mgr()->removeTask(_name);
129 globals->get_event_mgr()->addEvent(_name, this, &TimerObj::invoke, _interval);
131 globals->get_event_mgr()->addTask(_name, this, &TimerObj::invoke,
132 _interval, _interval /* delay */);
136 // stop and then start -
137 void restart(double newInterval)
139 _interval = newInterval;
147 _sys->callMethod(_func, _self, 0, args, naNil() /* locals */);
153 void setSingleShot(bool aSingleShot)
155 _singleShot = aSingleShot;
158 bool isSingleShot() const
159 { return _singleShot; }
164 int _gcRoot, _gcSelf;
170 typedef SGSharedPtr<TimerObj> TimerObjRef;
171 typedef nasal::Ghost<TimerObjRef> NasalTimerObj;
173 ///////////////////////////////////////////////////////////////////////////
175 // Read and return file contents in a single buffer. Note use of
176 // stat() to get the file size. This is a win32 function, believe it
177 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
178 // Text mode brain damage will kill us if we're trying to do bytewise
180 static char* readfile(const char* file, int* lenOut)
183 if(stat(file, &data) != 0) return 0;
184 FILE* f = fopen(file, "rb");
186 char* buf = new char[data.st_size];
187 *lenOut = fread(buf, 1, data.st_size, f);
189 if(*lenOut != data.st_size) {
190 // Shouldn't happen, but warn anyway since it represents a
191 // platform bug and not a typical runtime error (missing file,
193 SG_LOG(SG_NASAL, SG_ALERT,
194 "ERROR in Nasal initialization: " <<
195 "short count returned from fread() of " << file <<
196 ". Check your C library!");
203 FGNasalSys::FGNasalSys()
210 _log = new simgear::BufferedLogCallback(SG_NASAL, SG_INFO);
211 _log->truncateAt(255);
212 sglog().addCallback(_log);
214 naSetErrorHandler(&logError);
217 // Utility. Sets a named key in a hash by C string, rather than nasal
219 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
221 naRef s = naNewString(_context);
222 naStr_fromdata(s, (char*)key, strlen(key));
223 naHash_set(hash, s, val);
226 void FGNasalSys::globalsSet(const char* key, naRef val)
228 hashset(_globals, key, val);
231 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
233 return callMethod(code, naNil(), argc, args, locals);
236 // Does a naCall() in a new context. Wrapped here to make lock
237 // tracking easier. Extension functions are called with the lock, but
238 // we have to release it before making a new naCall(). So rather than
239 // drop the lock in every extension function that might call back into
240 // Nasal, we keep a stack depth counter here and only unlock/lock
241 // around the naCall if it isn't the first one.
243 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
245 return naCallMethod(code, self, argc, args, locals);
248 FGNasalSys::~FGNasalSys()
253 bool FGNasalSys::parseAndRun(const char* sourceCode)
255 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
259 call(code, 0, 0, naNil());
264 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
266 FGNasalScript* script = new FGNasalScript();
267 script->_gcKey = -1; // important, if we delete it on a parse
268 script->_nas = this; // error, don't clobber a real handle!
272 sprintf(buf, "FGNasalScript@%p", (void *)script);
276 script->_code = parse(name, src, strlen(src));
277 if(naIsNil(script->_code)) {
282 script->_gcKey = gcSave(script->_code);
287 // The get/setprop functions accept a *list* of strings and walk
288 // through the property tree with them to find the appropriate node.
289 // This allows a Nasal object to hold onto a property path and use it
290 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
291 // is the utility function that walks the property tree.
292 // Future enhancement: support integer arguments to specify array
294 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
296 SGPropertyNode* p = globals->get_props();
298 for(int i=0; i<len; i++) {
300 if(!naIsString(a)) return 0;
301 p = p->getNode(naStr_data(a));
304 } catch (const string& err) {
305 naRuntimeError(c, (char *)err.c_str());
311 // getprop() extension function. Concatenates its string arguments as
312 // property names and returns the value of the specified property. Or
313 // nil if it doesn't exist.
314 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
316 using namespace simgear;
317 const SGPropertyNode* p = findnode(c, args, argc);
318 if(!p) return naNil();
320 switch(p->getType()) {
321 case props::BOOL: case props::INT:
322 case props::LONG: case props::FLOAT:
325 double dv = p->getDoubleValue();
326 if (SGMisc<double>::isNaN(dv)) {
327 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
335 case props::UNSPECIFIED:
337 naRef nastr = naNewString(c);
338 const char* val = p->getStringValue();
339 naStr_fromdata(nastr, (char*)val, strlen(val));
342 case props::ALIAS: // <--- FIXME, recurse?
348 // setprop() extension function. Concatenates its string arguments as
349 // property names and sets the value of the specified property to the
351 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
354 char buf[BUFLEN + 1];
358 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
359 for(int i=0; i<argc-1; i++) {
360 naRef s = naStringValue(c, args[i]);
361 if(naIsNil(s)) return naNil();
362 strncpy(p, naStr_data(s), buflen);
364 buflen = BUFLEN - (p - buf);
365 if(i < (argc-2) && buflen > 0) {
371 SGPropertyNode* props = globals->get_props();
372 naRef val = args[argc-1];
375 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
377 naRef n = naNumValue(val);
379 naRuntimeError(c, "setprop() value is not string or number");
381 if (SGMisc<double>::isNaN(n.num)) {
382 naRuntimeError(c, "setprop() passed a NaN");
385 result = props->setDoubleValue(buf, n.num);
387 } catch (const string& err) {
388 naRuntimeError(c, (char *)err.c_str());
390 return naNum(result);
394 // print() extension function. Concatenates and prints its arguments
395 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
396 // make sure it appears. Is there better way to do this?
397 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
401 for(int i=0; i<n; i++) {
402 naRef s = naStringValue(c, args[i]);
403 if(naIsNil(s)) continue;
404 buf += naStr_data(s);
406 SG_LOG(SG_NASAL, SG_ALERT, buf);
407 return naNum(buf.length());
410 // logprint() extension function. Same as above, all arguments after the
411 // first argument are concatenated. Argument 0 is the log-level, matching
413 static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
416 naRuntimeError(c, "no prioirty argument to logprint()");
418 naRef priority = args[0];
421 for(int i=1; i<n; i++) {
422 naRef s = naStringValue(c, args[i]);
423 if(naIsNil(s)) continue;
424 buf += naStr_data(s);
426 // use the nasal source file and line for the message location, since
427 // that's more useful than the location here!
428 sglog().log(SG_NASAL, (sgDebugPriority)(int) priority.num,
429 naStr_data(naGetSourceFile(c, 0)),
430 naGetLine(c, 0), buf);
431 return naNum(buf.length());
435 // fgcommand() extension function. Executes a named command via the
436 // FlightGear command manager. Takes a single property node name as
438 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
440 naRef cmd = argc > 0 ? args[0] : naNil();
441 naRef props = argc > 1 ? args[1] : naNil();
442 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
443 naRuntimeError(c, "bad arguments to fgcommand()");
444 SGPropertyNode_ptr tmp, *node;
446 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
448 tmp = new SGPropertyNode();
451 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
454 // settimer(func, dt, simtime) extension function. Falls through to
455 // FGNasalSys::setTimer(). See there for docs.
456 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
458 nasalSys->setTimer(c, argc, args);
462 static naRef f_makeTimer(naContext c, naRef me, int argc, naRef* args)
464 if (!naIsNum(args[0])) {
465 naRuntimeError(c, "bad interval argument to maketimer");
468 naRef func, self = naNil();
469 if (naIsFunc(args[1])) {
471 } else if ((argc == 3) && naIsFunc(args[2])) {
476 TimerObj* timerObj = new TimerObj(nasalSys, func, self, args[0].num);
477 return NasalTimerObj::create(c, timerObj);
480 // setlistener(func, property, bool) extension function. Falls through to
481 // FGNasalSys::setListener(). See there for docs.
482 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
484 return nasalSys->setListener(c, argc, args);
487 // removelistener(int) extension function. Falls through to
488 // FGNasalSys::removeListener(). See there for docs.
489 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
491 return nasalSys->removeListener(c, argc, args);
494 // Returns a ghost handle to the argument to the currently executing
496 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
498 return nasalSys->cmdArgGhost();
501 // Sets up a property interpolation. The first argument is either a
502 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
503 // interpolate. The second argument is a vector of pairs of
504 // value/delta numbers.
505 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
507 SGPropertyNode* node;
508 naRef prop = argc > 0 ? args[0] : naNil();
509 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
510 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
513 naRef curve = argc > 1 ? args[1] : naNil();
514 if(!naIsVector(curve)) return naNil();
515 int nPoints = naVec_size(curve) / 2;
517 simgear::PropertyList value_nodes;
518 value_nodes.reserve(nPoints);
520 deltas.reserve(nPoints);
522 for( int i = 0; i < nPoints; ++i )
524 SGPropertyNode* val = new SGPropertyNode;
525 val->setDoubleValue(naNumValue(naVec_get(curve, 2*i)).num);
526 value_nodes.push_back(val);
527 deltas.push_back(naNumValue(naVec_get(curve, 2*i+1)).num);
530 node->interpolate("numeric", value_nodes, deltas, "linear");
534 // This is a better RNG than the one in the default Nasal distribution
535 // (which is based on the C library rand() implementation). It will
537 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
539 return naNum(sg_random());
542 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
548 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
554 // Return an array listing of all files in a directory
555 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
557 if(argc != 1 || !naIsString(args[0]))
558 naRuntimeError(c, "bad arguments to directory()");
560 simgear::Dir d(SGPath(naStr_data(args[0])));
561 if(!d.exists()) return naNil();
562 naRef result = naNewVector(c);
564 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
565 for (unsigned int i=0; i<paths.size(); ++i) {
566 std::string p = paths[i].file();
567 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
574 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
576 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
578 if(argc != 1 || !naIsString(args[0]))
579 naRuntimeError(c, "bad arguments to resolveDataPath()");
581 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
582 const char* pdata = p.c_str();
583 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
586 static naRef f_findDataDir(naContext c, naRef me, int argc, naRef* args)
588 if(argc != 1 || !naIsString(args[0]))
589 naRuntimeError(c, "bad arguments to findDataDir()");
591 SGPath p = globals->find_data_dir(naStr_data(args[0]));
592 const char* pdata = p.c_str();
593 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
596 class NasalCommand : public SGCommandMgr::Command
599 NasalCommand(FGNasalSys* sys, naRef f, const std::string& name) :
604 globals->get_commands()->addCommandObject(_name, this);
605 _gcRoot = sys->gcSave(f);
608 virtual ~NasalCommand()
610 _sys->gcRelease(_gcRoot);
613 virtual bool operator()(const SGPropertyNode* aNode)
615 _sys->setCmdArg(const_cast<SGPropertyNode*>(aNode));
617 args[0] = _sys->wrappedPropsNode(const_cast<SGPropertyNode*>(aNode));
619 _sys->callMethod(_func, naNil(), 1, args, naNil() /* locals */);
631 static naRef f_addCommand(naContext c, naRef me, int argc, naRef* args)
633 if(argc != 2 || !naIsString(args[0]) || !naIsFunc(args[1]))
634 naRuntimeError(c, "bad arguments to addcommand()");
636 nasalSys->addCommand(args[1], naStr_data(args[0]));
640 static naRef f_removeCommand(naContext c, naRef me, int argc, naRef* args)
642 if ((argc < 1) || !naIsString(args[0]))
643 naRuntimeError(c, "bad argument to removecommand()");
645 globals->get_commands()->removeCommand(naStr_data(args[0]));
650 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
652 // <path> ... absolute path to an XML file
653 // <start-tag> ... callback function with two args: tag name, attribute hash
654 // <end-tag> ... callback function with one arg: tag name
655 // <data> ... callback function with one arg: data
656 // <pi> ... callback function with two args: target, data
657 // (pi = "processing instruction")
658 // All four callback functions are optional and default to nil.
659 // The function returns nil on error, or the validated file name otherwise.
660 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
662 if(argc < 1 || !naIsString(args[0]))
663 naRuntimeError(c, "parsexml(): path argument missing or not a string");
664 if(argc > 5) argc = 5;
665 for(int i=1; i<argc; i++)
666 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
667 naRuntimeError(c, "parsexml(): callback argument not a function");
669 const char* file = fgValidatePath(naStr_data(args[0]), false);
671 naRuntimeError(c, "parsexml(): reading '%s' denied "
672 "(unauthorized access)", naStr_data(args[0]));
675 std::ifstream input(file);
676 NasalXMLVisitor visitor(c, argc, args);
678 readXML(input, visitor);
679 } catch (const sg_exception& e) {
680 naRuntimeError(c, "parsexml(): file '%s' %s",
681 file, e.getFormattedMessage().c_str());
684 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
687 // Return UNIX epoch time in seconds.
688 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
692 GetSystemTimeAsFileTime(&ft);
693 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
694 // Converts from 100ns units in 1601 epoch to unix epoch in sec
695 return naNum((t * 1e-7) - 11644473600.0);
698 gettimeofday(&td, 0);
699 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
703 // Table of extension functions. Terminate with zeros.
704 static struct { const char* name; naCFunction func; } funcs[] = {
705 { "getprop", f_getprop },
706 { "setprop", f_setprop },
707 { "print", f_print },
708 { "logprint", f_logprint },
709 { "_fgcommand", f_fgcommand },
710 { "settimer", f_settimer },
711 { "maketimer", f_makeTimer },
712 { "_setlistener", f_setlistener },
713 { "removelistener", f_removelistener },
714 { "addcommand", f_addCommand },
715 { "removecommand", f_removeCommand },
716 { "_cmdarg", f_cmdarg },
717 { "_interpolate", f_interpolate },
719 { "srand", f_srand },
720 { "abort", f_abort },
721 { "directory", f_directory },
722 { "resolvepath", f_resolveDataPath },
723 { "finddata", f_findDataDir },
724 { "parsexml", f_parsexml },
725 { "systime", f_systime },
729 naRef FGNasalSys::cmdArgGhost()
731 return propNodeGhost(_cmdArg);
734 void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
739 void FGNasalSys::init()
743 _context = naNewContext();
745 // Start with globals. Add it to itself as a recursive
746 // sub-reference under the name "globals". This gives client-code
747 // write access to the namespace if someone wants to do something
749 _globals = naInit_std(_context);
750 naSave(_context, _globals);
751 hashset(_globals, "globals", _globals);
753 hashset(_globals, "math", naInit_math(_context));
754 hashset(_globals, "bits", naInit_bits(_context));
755 hashset(_globals, "io", naInit_io(_context));
756 hashset(_globals, "thread", naInit_thread(_context));
757 hashset(_globals, "utf8", naInit_utf8(_context));
759 // Add our custom extension functions:
760 for(i=0; funcs[i].name; i++)
761 hashset(_globals, funcs[i].name,
762 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
764 // And our SGPropertyNode wrapper
765 hashset(_globals, "props", genPropsModule());
767 // Add string methods
768 _string = naInit_string(_context);
769 naSave(_context, _string);
770 initNasalString(_globals, _string, _context);
772 initNasalPositioned(_globals, _context);
773 initNasalPositioned_cppbind(_globals, _context);
774 NasalClipboard::init(this);
775 initNasalCanvas(_globals, _context);
776 initNasalCondition(_globals, _context);
777 initNasalHTTP(_globals, _context);
779 if (!NasalTimerObj::isInit()) {
780 NasalTimerObj::init("Timer")
781 .method("start", &TimerObj::start)
782 .method("stop", &TimerObj::stop)
783 .method("restart", &TimerObj::restart)
784 .member("singleShot", &TimerObj::isSingleShot, &TimerObj::setSingleShot)
785 .member("isRunning", &TimerObj::isRunning);
788 // Now load the various source files in the Nasal directory
789 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
790 loadScriptDirectory(nasalDir);
792 // Add modules in Nasal subdirectories to property tree
793 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
794 simgear::Dir::NO_DOT_OR_DOTDOT, "");
795 for (unsigned int i=0; i<directories.size(); ++i) {
796 simgear::Dir dir(directories[i]);
797 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
798 addModule(directories[i].file(), scripts);
801 // set signal and remove node to avoid restoring at reinit
802 const char *s = "nasal-dir-initialized";
803 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
804 signal->setBoolValue(s, true);
805 signal->removeChildren(s, false);
807 // Pull scripts out of the property tree, too
808 loadPropertyScripts();
810 // now Nasal modules are loaded, we can do some delayed work
811 postinitNasalPositioned(_globals, _context);
812 postinitNasalGUI(_globals, _context);
815 void FGNasalSys::shutdown()
817 shutdownNasalPositioned();
819 map<int, FGNasalListener *>::iterator it, end = _listener.end();
820 for(it = _listener.begin(); it != end; ++it)
824 NasalCommandDict::iterator j = _commands.begin();
825 for (; j != _commands.end(); ++j) {
826 globals->get_commands()->removeCommand(j->first);
832 _string = naNil(); // will be freed by _context
833 naFreeContext(_context);
835 //setWatchedRef(_globals);
837 // remove the recursive reference in globals
838 hashset(_globals, "globals", naNil());
845 naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps)
847 static naRef wrapNodeFunc = naNil();
848 if (naIsNil(wrapNodeFunc)) {
849 nasal::Hash props = getGlobals().get<nasal::Hash>("props");
850 wrapNodeFunc = props.get("wrapNode");
854 args[0] = propNodeGhost(aProps);
855 return naCall(_context, wrapNodeFunc, 1, args, naNil(), naNil());
858 void FGNasalSys::update(double)
860 if( NasalClipboard::getInstance() )
861 NasalClipboard::getInstance()->update();
863 if(!_dead_listener.empty()) {
864 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
865 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
866 _dead_listener.clear();
869 if (!_loadList.empty())
874 // process Nasal load hook (only one per update loop to avoid excessive lags)
875 _loadList.pop()->load();
878 if (!_unloadList.empty())
880 // process pending Nasal unload hooks after _all_ load hooks were processed
881 // (only unload one per update loop to avoid excessive lags)
882 _unloadList.pop()->unload();
885 // The global context is a legacy thing. We use dynamically
886 // created contexts for naCall() now, so that we can call them
887 // recursively. But there are still spots that want to use it for
888 // naNew*() calls, which end up leaking memory because the context
889 // only clears out its temporary vector when it's *used*. So just
890 // junk it and fetch a new/reinitialized one every frame. This is
891 // clumsy: the right solution would use the dynamic context in all
892 // cases and eliminate _context entirely. But that's more work,
893 // and this works fine (yes, they say "New" and "Free", but
894 // they're very fast, just trust me). -Andy
895 naFreeContext(_context);
896 _context = naNewContext();
899 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
901 return p1.file() < p2.file();
904 // Loads all scripts in given directory
905 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
907 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
908 // Note: simgear::Dir already reports file entries in a deterministic order,
909 // so a fixed loading sequence is guaranteed (same for every user)
910 for (unsigned int i=0; i<scripts.size(); ++i) {
911 SGPath fullpath(scripts[i]);
912 SGPath file = fullpath.file();
913 loadModule(fullpath, file.base().c_str());
917 // Create module with list of scripts
918 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
920 if (! scripts.empty())
922 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
923 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
924 for (unsigned int i=0; i<scripts.size(); ++i) {
925 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
926 pFileNode->setStringValue(scripts[i].c_str());
928 if (!module_node->hasChild("enabled",0))
930 SGPropertyNode* node = module_node->getChild("enabled",0,true);
931 node->setBoolValue(true);
932 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
937 // Loads the scripts found under /nasal in the global tree
938 void FGNasalSys::loadPropertyScripts()
940 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
943 for(int i=0; i<nasal->nChildren(); i++)
945 SGPropertyNode* n = nasal->getChild(i);
946 loadPropertyScripts(n);
950 // Loads the scripts found under /nasal in the global tree
951 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
953 bool is_loaded = false;
955 const char* module = n->getName();
956 if(n->hasChild("module"))
957 module = n->getStringValue("module");
958 if (n->getBoolValue("enabled",true))
960 // allow multiple files to be specified within a single
964 bool file_specified = false;
966 while((fn = n->getChild("file", j)) != NULL) {
967 file_specified = true;
968 const char* file = fn->getStringValue();
970 if (!p.isAbsolute() || !p.exists())
972 p = globals->resolve_maybe_aircraft_path(file);
975 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
976 file << "' for module '" << module << "'.");
979 ok &= p.isNull() ? false : loadModule(p, module);
983 const char* src = n->getStringValue("script");
984 if(!n->hasChild("script")) src = 0; // Hrm...
986 createModule(module, n->getPath().c_str(), src, strlen(src));
988 if(!file_specified && !src)
990 // module no longer exists - clear the archived "enable" flag
991 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
992 SGPropertyNode* node = n->getChild("enabled",0,false);
994 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
996 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
997 "no <file> or <script> defined in " <<
998 "/nasal/" << module);
1005 SGPropertyNode* enable = n->getChild("enabled");
1008 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
1009 enable->addChangeListener(listener, false);
1012 SGPropertyNode* loaded = n->getChild("loaded",0,true);
1013 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
1014 loaded->setBoolValue(is_loaded);
1017 // Logs a runtime error, with stack trace, to the FlightGear log stream
1018 void FGNasalSys::logError(naContext context)
1020 SG_LOG(SG_NASAL, SG_ALERT, "Nasal runtime error: " << naGetError(context));
1021 int stack_depth = naStackDepth(context);
1022 if( stack_depth < 1 )
1024 SG_LOG(SG_NASAL, SG_ALERT,
1025 " at " << naStr_data(naGetSourceFile(context, 0)) <<
1026 ", line " << naGetLine(context, 0));
1027 for(int i=1; i<stack_depth; i++)
1028 SG_LOG(SG_NASAL, SG_ALERT,
1029 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
1030 ", line " << naGetLine(context, i));
1033 // Reads a script file, executes it, and places the resulting
1034 // namespace into the global namespace under the specified module
1036 bool FGNasalSys::loadModule(SGPath file, const char* module)
1039 char* buf = readfile(file.c_str(), &len);
1041 SG_LOG(SG_NASAL, SG_ALERT,
1042 "Nasal error: could not read script file " << file.c_str()
1043 << " into module " << module);
1047 bool ok = createModule(module, file.c_str(), buf, len);
1052 // Parse and run. Save the local variables namespace, as it will
1053 // become a sub-object of globals. The optional "arg" argument can be
1054 // used to pass an associated property node to the module, which can then
1055 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
1056 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1057 const char* src, int len,
1058 const SGPropertyNode* cmdarg,
1059 int argc, naRef* args)
1061 naRef code = parse(fileName, src, len);
1065 // See if we already have a module hash to use. This allows the
1066 // user to, for example, add functions to the built-in math
1067 // module. Make a new one if necessary.
1069 naRef modname = naNewString(_context);
1070 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1071 if(!naHash_get(_globals, modname, &locals))
1072 locals = naNewHash(_context);
1074 _cmdArg = (SGPropertyNode*)cmdarg;
1076 call(code, argc, args, locals);
1077 hashset(_globals, moduleName, locals);
1081 void FGNasalSys::deleteModule(const char* moduleName)
1083 naRef modname = naNewString(_context);
1084 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1085 naHash_delete(_globals, modname);
1088 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
1091 naRef srcfile = naNewString(_context);
1092 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1093 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
1095 SG_LOG(SG_NASAL, SG_ALERT,
1096 "Nasal parse error: " << naGetError(_context) <<
1097 " in "<< filename <<", line " << errLine);
1101 // Bind to the global namespace before returning
1102 return naBindFunction(_context, code, _globals);
1105 bool FGNasalSys::handleCommand( const char* moduleName,
1106 const char* fileName,
1108 const SGPropertyNode* arg )
1110 naRef code = parse(fileName, src, strlen(src));
1111 if(naIsNil(code)) return false;
1113 // Commands can be run "in" a module. Make sure that module
1114 // exists, and set it up as the local variables hash for the
1116 naRef locals = naNil();
1118 naRef modname = naNewString(_context);
1119 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1120 if(!naHash_get(_globals, modname, &locals)) {
1121 locals = naNewHash(_context);
1122 naHash_set(_globals, modname, locals);
1126 // Cache this command's argument for inspection via cmdarg(). For
1127 // performance reasons, we won't bother with it if the invoked
1128 // code doesn't need it.
1129 _cmdArg = (SGPropertyNode*)arg;
1131 call(code, 0, 0, locals);
1135 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1137 const char* src = arg->getStringValue("script");
1138 const char* moduleName = arg->getStringValue("module");
1140 return handleCommand( moduleName,
1141 arg ? arg->getPath(true).c_str() : moduleName,
1146 // settimer(func, dt, simtime) extension function. The first argument
1147 // is a Nasal function to call, the second is a delta time (from now),
1148 // in seconds. The third, if present, is a boolean value indicating
1149 // that "real world" time (rather than simulator time) is to be used.
1151 // Implementation note: the FGTimer objects don't live inside the
1152 // garbage collector, so the Nasal handler functions have to be
1153 // "saved" somehow lest they be inadvertently cleaned. In this case,
1154 // they are inserted into a globals.__gcsave hash and removed on
1156 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1158 // Extract the handler, delta, and simtime arguments:
1159 naRef handler = argc > 0 ? args[0] : naNil();
1160 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1161 naRuntimeError(c, "settimer() with invalid function argument");
1165 naRef delta = argc > 1 ? args[1] : naNil();
1166 if(naIsNil(delta)) {
1167 naRuntimeError(c, "settimer() with invalid time argument");
1171 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1173 // Generate and register a C++ timer handler
1174 NasalTimer* t = new NasalTimer;
1175 t->handler = handler;
1176 t->gcKey = gcSave(handler);
1179 globals->get_event_mgr()->addEvent("NasalTimer",
1180 t, &NasalTimer::timerExpired,
1181 delta.num, simtime);
1184 void FGNasalSys::handleTimer(NasalTimer* t)
1186 call(t->handler, 0, 0, naNil());
1187 gcRelease(t->gcKey);
1190 int FGNasalSys::gcSave(naRef r)
1195 void FGNasalSys::gcRelease(int key)
1200 void FGNasalSys::NasalTimer::timerExpired()
1202 nasal->handleTimer(this);
1206 int FGNasalSys::_listenerId = 0;
1208 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1209 // Attaches a callback function to a property (specified as a global
1210 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1211 // optional argument (default=0) is set to 1, then the function is also
1212 // called initially. If the fourth, optional argument is set to 0, then the
1213 // function is only called when the property node value actually changes.
1214 // Otherwise it's called independent of the value whenever the node is
1215 // written to (default). The setlistener() function returns a unique
1216 // id number, which is to be used as argument to the removelistener()
1218 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1220 SGPropertyNode_ptr node;
1221 naRef prop = argc > 0 ? args[0] : naNil();
1222 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1223 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1225 naRuntimeError(c, "setlistener() with invalid property argument");
1230 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1233 naRef code = argc > 1 ? args[1] : naNil();
1234 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1235 naRuntimeError(c, "setlistener() with invalid function argument");
1239 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1240 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1241 FGNasalListener *nl = new FGNasalListener(node, code, this,
1242 gcSave(code), _listenerId, init, type);
1244 node->addChangeListener(nl, init != 0);
1246 _listener[_listenerId] = nl;
1247 return naNum(_listenerId++);
1250 // removelistener(int) extension function. The argument is the id of
1251 // a listener as returned by the setlistener() function.
1252 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1254 naRef id = argc > 0 ? args[0] : naNil();
1255 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1257 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1258 naRuntimeError(c, "removelistener() with invalid listener id");
1262 it->second->_dead = true;
1263 _dead_listener.push_back(it->second);
1264 _listener.erase(it);
1265 return naNum(_listener.size());
1268 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1270 if( _loadList.empty() )
1272 _loadList.push(data);
1275 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1277 _unloadList.push(data);
1280 void FGNasalSys::addCommand(naRef func, const std::string& name)
1282 if (_commands.find(name) != _commands.end()) {
1283 SG_LOG(SG_NASAL, SG_WARN, "duplicate add of command:" << name);
1287 NasalCommand* cmd = new NasalCommand(this, func, name);
1288 _commands[name] = cmd;
1291 void FGNasalSys::removeCommand(const std::string& name)
1293 NasalCommandDict::iterator it = _commands.find(name);
1294 if (it == _commands.end()) {
1295 SG_LOG(SG_NASAL, SG_WARN, "remove of unknwon command:" << name);
1299 // will delete the NasalCommand instance
1300 globals->get_commands()->removeCommand(name);
1301 _commands.erase(it);
1304 //////////////////////////////////////////////////////////////////////////
1305 // FGNasalListener class.
1307 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1308 FGNasalSys* nasal, int key, int id,
1309 int init, int type) :
1322 if(_type == 0 && !_init)
1326 FGNasalListener::~FGNasalListener()
1328 _node->removeChangeListener(this);
1329 _nas->gcRelease(_gcKey);
1332 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1334 if(_active || _dead) return;
1337 arg[0] = _nas->propNodeGhost(which);
1338 arg[1] = _nas->propNodeGhost(_node);
1339 arg[2] = mode; // value changed, child added/removed
1340 arg[3] = naNum(_node != which); // child event?
1341 _nas->call(_code, 4, arg, naNil());
1345 void FGNasalListener::valueChanged(SGPropertyNode* node)
1347 if(_type < 2 && node != _node) return; // skip child events
1348 if(_type > 0 || changed(_node) || _init)
1349 call(node, naNum(0));
1354 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1356 if(_type == 2) call(child, naNum(1));
1359 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1361 if(_type == 2) call(child, naNum(-1));
1364 bool FGNasalListener::changed(SGPropertyNode* node)
1366 using namespace simgear;
1367 props::Type type = node->getType();
1368 if(type == props::NONE) return false;
1369 if(type == props::UNSPECIFIED) return true;
1377 long l = node->getLongValue();
1378 result = l != _last_int;
1385 double d = node->getDoubleValue();
1386 result = d != _last_float;
1392 string s = node->getStringValue();
1393 result = s != _last_string;
1400 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1402 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1403 _c(naSubContext(c)),
1404 _start_element(argc > 1 ? args[1] : naNil()),
1405 _end_element(argc > 2 ? args[2] : naNil()),
1406 _data(argc > 3 ? args[3] : naNil()),
1407 _pi(argc > 4 ? args[4] : naNil())
1411 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1413 if(naIsNil(_start_element)) return;
1414 naRef attr = naNewHash(_c);
1415 for(int i=0; i<a.size(); i++) {
1416 naRef name = make_string(a.getName(i));
1417 naRef value = make_string(a.getValue(i));
1418 naHash_set(attr, name, value);
1420 call(_start_element, 2, make_string(tag), attr);
1423 void NasalXMLVisitor::endElement(const char* tag)
1425 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1428 void NasalXMLVisitor::data(const char* str, int len)
1430 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1433 void NasalXMLVisitor::pi(const char* target, const char* data)
1435 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1438 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1443 naCall(_c, func, num, args, naNil(), naNil());
1448 naRef NasalXMLVisitor::make_string(const char* s, int n)
1450 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1451 n < 0 ? strlen(s) : n);