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()
209 _wrappedNodeFunc = naNil();
211 _log = new simgear::BufferedLogCallback(SG_NASAL, SG_INFO);
212 _log->truncateAt(255);
213 sglog().addCallback(_log);
215 naSetErrorHandler(&logError);
218 // Utility. Sets a named key in a hash by C string, rather than nasal
220 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
222 naRef s = naNewString(_context);
223 naStr_fromdata(s, (char*)key, strlen(key));
224 naHash_set(hash, s, val);
227 void FGNasalSys::globalsSet(const char* key, naRef val)
229 hashset(_globals, key, val);
232 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
234 return callMethod(code, naNil(), argc, args, locals);
237 // Does a naCall() in a new context. Wrapped here to make lock
238 // tracking easier. Extension functions are called with the lock, but
239 // we have to release it before making a new naCall(). So rather than
240 // drop the lock in every extension function that might call back into
241 // Nasal, we keep a stack depth counter here and only unlock/lock
242 // around the naCall if it isn't the first one.
244 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
246 return naCallMethod(code, self, argc, args, locals);
249 FGNasalSys::~FGNasalSys()
254 bool FGNasalSys::parseAndRun(const char* sourceCode)
256 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
260 call(code, 0, 0, naNil());
265 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
267 FGNasalScript* script = new FGNasalScript();
268 script->_gcKey = -1; // important, if we delete it on a parse
269 script->_nas = this; // error, don't clobber a real handle!
273 sprintf(buf, "FGNasalScript@%p", (void *)script);
277 script->_code = parse(name, src, strlen(src));
278 if(naIsNil(script->_code)) {
283 script->_gcKey = gcSave(script->_code);
288 // The get/setprop functions accept a *list* of strings and walk
289 // through the property tree with them to find the appropriate node.
290 // This allows a Nasal object to hold onto a property path and use it
291 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
292 // is the utility function that walks the property tree.
293 // Future enhancement: support integer arguments to specify array
295 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
297 SGPropertyNode* p = globals->get_props();
299 for(int i=0; i<len; i++) {
301 if(!naIsString(a)) return 0;
302 p = p->getNode(naStr_data(a));
305 } catch (const string& err) {
306 naRuntimeError(c, (char *)err.c_str());
312 // getprop() extension function. Concatenates its string arguments as
313 // property names and returns the value of the specified property. Or
314 // nil if it doesn't exist.
315 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
317 using namespace simgear;
318 const SGPropertyNode* p = findnode(c, args, argc);
319 if(!p) return naNil();
321 switch(p->getType()) {
322 case props::BOOL: case props::INT:
323 case props::LONG: case props::FLOAT:
326 double dv = p->getDoubleValue();
327 if (SGMisc<double>::isNaN(dv)) {
328 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
336 case props::UNSPECIFIED:
338 naRef nastr = naNewString(c);
339 const char* val = p->getStringValue();
340 naStr_fromdata(nastr, (char*)val, strlen(val));
343 case props::ALIAS: // <--- FIXME, recurse?
349 // setprop() extension function. Concatenates its string arguments as
350 // property names and sets the value of the specified property to the
352 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
355 char buf[BUFLEN + 1];
359 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
360 for(int i=0; i<argc-1; i++) {
361 naRef s = naStringValue(c, args[i]);
362 if(naIsNil(s)) return naNil();
363 strncpy(p, naStr_data(s), buflen);
365 buflen = BUFLEN - (p - buf);
366 if(i < (argc-2) && buflen > 0) {
372 SGPropertyNode* props = globals->get_props();
373 naRef val = args[argc-1];
376 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
378 naRef n = naNumValue(val);
380 naRuntimeError(c, "setprop() value is not string or number");
382 if (SGMisc<double>::isNaN(n.num)) {
383 naRuntimeError(c, "setprop() passed a NaN");
386 result = props->setDoubleValue(buf, n.num);
388 } catch (const string& err) {
389 naRuntimeError(c, (char *)err.c_str());
391 return naNum(result);
395 // print() extension function. Concatenates and prints its arguments
396 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
397 // make sure it appears. Is there better way to do this?
398 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
402 for(int i=0; i<n; i++) {
403 naRef s = naStringValue(c, args[i]);
404 if(naIsNil(s)) continue;
405 buf += naStr_data(s);
407 SG_LOG(SG_NASAL, SG_ALERT, buf);
408 return naNum(buf.length());
411 // logprint() extension function. Same as above, all arguments after the
412 // first argument are concatenated. Argument 0 is the log-level, matching
414 static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
417 naRuntimeError(c, "no prioirty argument to logprint()");
419 naRef priority = args[0];
422 for(int i=1; i<n; i++) {
423 naRef s = naStringValue(c, args[i]);
424 if(naIsNil(s)) continue;
425 buf += naStr_data(s);
427 // use the nasal source file and line for the message location, since
428 // that's more useful than the location here!
429 sglog().log(SG_NASAL, (sgDebugPriority)(int) priority.num,
430 naStr_data(naGetSourceFile(c, 0)),
431 naGetLine(c, 0), buf);
432 return naNum(buf.length());
436 // fgcommand() extension function. Executes a named command via the
437 // FlightGear command manager. Takes a single property node name as
439 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
441 naRef cmd = argc > 0 ? args[0] : naNil();
442 naRef props = argc > 1 ? args[1] : naNil();
443 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
444 naRuntimeError(c, "bad arguments to fgcommand()");
445 SGPropertyNode_ptr tmp, *node;
447 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
449 tmp = new SGPropertyNode();
452 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
455 // settimer(func, dt, simtime) extension function. Falls through to
456 // FGNasalSys::setTimer(). See there for docs.
457 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
459 nasalSys->setTimer(c, argc, args);
463 static naRef f_makeTimer(naContext c, naRef me, int argc, naRef* args)
465 if (!naIsNum(args[0])) {
466 naRuntimeError(c, "bad interval argument to maketimer");
469 naRef func, self = naNil();
470 if (naIsFunc(args[1])) {
472 } else if ((argc == 3) && naIsFunc(args[2])) {
477 TimerObj* timerObj = new TimerObj(nasalSys, func, self, args[0].num);
478 return NasalTimerObj::create(c, timerObj);
481 // setlistener(func, property, bool) extension function. Falls through to
482 // FGNasalSys::setListener(). See there for docs.
483 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
485 return nasalSys->setListener(c, argc, args);
488 // removelistener(int) extension function. Falls through to
489 // FGNasalSys::removeListener(). See there for docs.
490 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
492 return nasalSys->removeListener(c, argc, args);
495 // Returns a ghost handle to the argument to the currently executing
497 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
499 return nasalSys->cmdArgGhost();
502 // Sets up a property interpolation. The first argument is either a
503 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
504 // interpolate. The second argument is a vector of pairs of
505 // value/delta numbers.
506 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
508 SGPropertyNode* node;
509 naRef prop = argc > 0 ? args[0] : naNil();
510 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
511 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
514 naRef curve = argc > 1 ? args[1] : naNil();
515 if(!naIsVector(curve)) return naNil();
516 int nPoints = naVec_size(curve) / 2;
518 simgear::PropertyList value_nodes;
519 value_nodes.reserve(nPoints);
521 deltas.reserve(nPoints);
523 for( int i = 0; i < nPoints; ++i )
525 SGPropertyNode* val = new SGPropertyNode;
526 val->setDoubleValue(naNumValue(naVec_get(curve, 2*i)).num);
527 value_nodes.push_back(val);
528 deltas.push_back(naNumValue(naVec_get(curve, 2*i+1)).num);
531 node->interpolate("numeric", value_nodes, deltas, "linear");
535 // This is a better RNG than the one in the default Nasal distribution
536 // (which is based on the C library rand() implementation). It will
538 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
540 return naNum(sg_random());
543 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
549 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
555 // Return an array listing of all files in a directory
556 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
558 if(argc != 1 || !naIsString(args[0]))
559 naRuntimeError(c, "bad arguments to directory()");
561 simgear::Dir d(SGPath(naStr_data(args[0])));
562 if(!d.exists()) return naNil();
563 naRef result = naNewVector(c);
565 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
566 for (unsigned int i=0; i<paths.size(); ++i) {
567 std::string p = paths[i].file();
568 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
575 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
577 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
579 if(argc != 1 || !naIsString(args[0]))
580 naRuntimeError(c, "bad arguments to resolveDataPath()");
582 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
583 const char* pdata = p.c_str();
584 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
587 static naRef f_findDataDir(naContext c, naRef me, int argc, naRef* args)
589 if(argc != 1 || !naIsString(args[0]))
590 naRuntimeError(c, "bad arguments to findDataDir()");
592 SGPath p = globals->find_data_dir(naStr_data(args[0]));
593 const char* pdata = p.c_str();
594 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
597 class NasalCommand : public SGCommandMgr::Command
600 NasalCommand(FGNasalSys* sys, naRef f, const std::string& name) :
605 globals->get_commands()->addCommandObject(_name, this);
606 _gcRoot = sys->gcSave(f);
609 virtual ~NasalCommand()
611 _sys->gcRelease(_gcRoot);
614 virtual bool operator()(const SGPropertyNode* aNode)
616 _sys->setCmdArg(const_cast<SGPropertyNode*>(aNode));
618 args[0] = _sys->wrappedPropsNode(const_cast<SGPropertyNode*>(aNode));
620 _sys->callMethod(_func, naNil(), 1, args, naNil() /* locals */);
632 static naRef f_addCommand(naContext c, naRef me, int argc, naRef* args)
634 if(argc != 2 || !naIsString(args[0]) || !naIsFunc(args[1]))
635 naRuntimeError(c, "bad arguments to addcommand()");
637 nasalSys->addCommand(args[1], naStr_data(args[0]));
641 static naRef f_removeCommand(naContext c, naRef me, int argc, naRef* args)
643 if ((argc < 1) || !naIsString(args[0]))
644 naRuntimeError(c, "bad argument to removecommand()");
646 globals->get_commands()->removeCommand(naStr_data(args[0]));
651 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
653 // <path> ... absolute path to an XML file
654 // <start-tag> ... callback function with two args: tag name, attribute hash
655 // <end-tag> ... callback function with one arg: tag name
656 // <data> ... callback function with one arg: data
657 // <pi> ... callback function with two args: target, data
658 // (pi = "processing instruction")
659 // All four callback functions are optional and default to nil.
660 // The function returns nil on error, or the validated file name otherwise.
661 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
663 if(argc < 1 || !naIsString(args[0]))
664 naRuntimeError(c, "parsexml(): path argument missing or not a string");
665 if(argc > 5) argc = 5;
666 for(int i=1; i<argc; i++)
667 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
668 naRuntimeError(c, "parsexml(): callback argument not a function");
670 const char* file = fgValidatePath(naStr_data(args[0]), false);
672 naRuntimeError(c, "parsexml(): reading '%s' denied "
673 "(unauthorized access)", naStr_data(args[0]));
676 std::ifstream input(file);
677 NasalXMLVisitor visitor(c, argc, args);
679 readXML(input, visitor);
680 } catch (const sg_exception& e) {
681 naRuntimeError(c, "parsexml(): file '%s' %s",
682 file, e.getFormattedMessage().c_str());
685 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
688 // Return UNIX epoch time in seconds.
689 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
693 GetSystemTimeAsFileTime(&ft);
694 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
695 // Converts from 100ns units in 1601 epoch to unix epoch in sec
696 return naNum((t * 1e-7) - 11644473600.0);
699 gettimeofday(&td, 0);
700 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
704 // Table of extension functions. Terminate with zeros.
705 static struct { const char* name; naCFunction func; } funcs[] = {
706 { "getprop", f_getprop },
707 { "setprop", f_setprop },
708 { "print", f_print },
709 { "logprint", f_logprint },
710 { "_fgcommand", f_fgcommand },
711 { "settimer", f_settimer },
712 { "maketimer", f_makeTimer },
713 { "_setlistener", f_setlistener },
714 { "removelistener", f_removelistener },
715 { "addcommand", f_addCommand },
716 { "removecommand", f_removeCommand },
717 { "_cmdarg", f_cmdarg },
718 { "_interpolate", f_interpolate },
720 { "srand", f_srand },
721 { "abort", f_abort },
722 { "directory", f_directory },
723 { "resolvepath", f_resolveDataPath },
724 { "finddata", f_findDataDir },
725 { "parsexml", f_parsexml },
726 { "systime", f_systime },
730 naRef FGNasalSys::cmdArgGhost()
732 return propNodeGhost(_cmdArg);
735 void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
740 void FGNasalSys::init()
744 _context = naNewContext();
746 // Start with globals. Add it to itself as a recursive
747 // sub-reference under the name "globals". This gives client-code
748 // write access to the namespace if someone wants to do something
750 _globals = naInit_std(_context);
751 naSave(_context, _globals);
752 hashset(_globals, "globals", _globals);
754 hashset(_globals, "math", naInit_math(_context));
755 hashset(_globals, "bits", naInit_bits(_context));
756 hashset(_globals, "io", naInit_io(_context));
757 hashset(_globals, "thread", naInit_thread(_context));
758 hashset(_globals, "utf8", naInit_utf8(_context));
760 // Add our custom extension functions:
761 for(i=0; funcs[i].name; i++)
762 hashset(_globals, funcs[i].name,
763 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
765 // And our SGPropertyNode wrapper
766 hashset(_globals, "props", genPropsModule());
768 // Add string methods
769 _string = naInit_string(_context);
770 naSave(_context, _string);
771 initNasalString(_globals, _string, _context);
773 initNasalPositioned(_globals, _context);
774 initNasalPositioned_cppbind(_globals, _context);
775 NasalClipboard::init(this);
776 initNasalCanvas(_globals, _context);
777 initNasalCondition(_globals, _context);
778 initNasalHTTP(_globals, _context);
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);
787 // Now load the various source files in the Nasal directory
788 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
789 loadScriptDirectory(nasalDir);
791 // Add modules in Nasal subdirectories to property tree
792 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
793 simgear::Dir::NO_DOT_OR_DOTDOT, "");
794 for (unsigned int i=0; i<directories.size(); ++i) {
795 simgear::Dir dir(directories[i]);
796 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
797 addModule(directories[i].file(), scripts);
800 // set signal and remove node to avoid restoring at reinit
801 const char *s = "nasal-dir-initialized";
802 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
803 signal->setBoolValue(s, true);
804 signal->removeChildren(s, false);
806 // Pull scripts out of the property tree, too
807 loadPropertyScripts();
809 // now Nasal modules are loaded, we can do some delayed work
810 postinitNasalPositioned(_globals, _context);
811 postinitNasalGUI(_globals, _context);
814 void FGNasalSys::shutdown()
816 shutdownNasalPositioned();
818 map<int, FGNasalListener *>::iterator it, end = _listener.end();
819 for(it = _listener.begin(); it != end; ++it)
823 NasalCommandDict::iterator j = _commands.begin();
824 for (; j != _commands.end(); ++j) {
825 globals->get_commands()->removeCommand(j->first);
829 std::vector<FGNasalModuleListener*>::iterator k = _moduleListeners.begin();
830 for(; k!= _moduleListeners.end(); ++k)
832 _moduleListeners.clear();
836 _string = naNil(); // will be freed by _context
837 naFreeContext(_context);
839 //setWatchedRef(_globals);
841 // remove the recursive reference in globals
842 hashset(_globals, "globals", naNil());
849 naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps)
851 if (naIsNil(_wrappedNodeFunc)) {
852 nasal::Hash props = getGlobals().get<nasal::Hash>("props");
853 _wrappedNodeFunc = props.get("wrapNode");
857 args[0] = propNodeGhost(aProps);
858 naContext ctx = naNewContext();
859 naRef wrapped = naCall(ctx, _wrappedNodeFunc, 1, args, naNil(), naNil());
864 void FGNasalSys::update(double)
866 if( NasalClipboard::getInstance() )
867 NasalClipboard::getInstance()->update();
869 if(!_dead_listener.empty()) {
870 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
871 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
872 _dead_listener.clear();
875 if (!_loadList.empty())
880 // process Nasal load hook (only one per update loop to avoid excessive lags)
881 _loadList.pop()->load();
884 if (!_unloadList.empty())
886 // process pending Nasal unload hooks after _all_ load hooks were processed
887 // (only unload one per update loop to avoid excessive lags)
888 _unloadList.pop()->unload();
891 // The global context is a legacy thing. We use dynamically
892 // created contexts for naCall() now, so that we can call them
893 // recursively. But there are still spots that want to use it for
894 // naNew*() calls, which end up leaking memory because the context
895 // only clears out its temporary vector when it's *used*. So just
896 // junk it and fetch a new/reinitialized one every frame. This is
897 // clumsy: the right solution would use the dynamic context in all
898 // cases and eliminate _context entirely. But that's more work,
899 // and this works fine (yes, they say "New" and "Free", but
900 // they're very fast, just trust me). -Andy
901 naFreeContext(_context);
902 _context = naNewContext();
905 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
907 return p1.file() < p2.file();
910 // Loads all scripts in given directory
911 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
913 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
914 // Note: simgear::Dir already reports file entries in a deterministic order,
915 // so a fixed loading sequence is guaranteed (same for every user)
916 for (unsigned int i=0; i<scripts.size(); ++i) {
917 SGPath fullpath(scripts[i]);
918 SGPath file = fullpath.file();
919 loadModule(fullpath, file.base().c_str());
923 // Create module with list of scripts
924 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
926 if (! scripts.empty())
928 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
929 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
930 for (unsigned int i=0; i<scripts.size(); ++i) {
931 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
932 pFileNode->setStringValue(scripts[i].c_str());
934 if (!module_node->hasChild("enabled",0))
936 SGPropertyNode* node = module_node->getChild("enabled",0,true);
937 node->setBoolValue(true);
938 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
943 // Loads the scripts found under /nasal in the global tree
944 void FGNasalSys::loadPropertyScripts()
946 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
949 for(int i=0; i<nasal->nChildren(); i++)
951 SGPropertyNode* n = nasal->getChild(i);
952 loadPropertyScripts(n);
956 // Loads the scripts found under /nasal in the global tree
957 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
959 bool is_loaded = false;
961 const char* module = n->getName();
962 if(n->hasChild("module"))
963 module = n->getStringValue("module");
964 if (n->getBoolValue("enabled",true))
966 // allow multiple files to be specified within a single
970 bool file_specified = false;
972 while((fn = n->getChild("file", j)) != NULL) {
973 file_specified = true;
974 const char* file = fn->getStringValue();
976 if (!p.isAbsolute() || !p.exists())
978 p = globals->resolve_maybe_aircraft_path(file);
981 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
982 file << "' for module '" << module << "'.");
985 ok &= p.isNull() ? false : loadModule(p, module);
989 const char* src = n->getStringValue("script");
990 if(!n->hasChild("script")) src = 0; // Hrm...
992 createModule(module, n->getPath().c_str(), src, strlen(src));
994 if(!file_specified && !src)
996 // module no longer exists - clear the archived "enable" flag
997 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
998 SGPropertyNode* node = n->getChild("enabled",0,false);
1000 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
1002 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
1003 "no <file> or <script> defined in " <<
1004 "/nasal/" << module);
1011 SGPropertyNode* enable = n->getChild("enabled");
1014 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
1015 _moduleListeners.push_back(listener);
1016 enable->addChangeListener(listener, false);
1019 SGPropertyNode* loaded = n->getChild("loaded",0,true);
1020 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
1021 loaded->setBoolValue(is_loaded);
1024 // Logs a runtime error, with stack trace, to the FlightGear log stream
1025 void FGNasalSys::logError(naContext context)
1027 SG_LOG(SG_NASAL, SG_ALERT, "Nasal runtime error: " << naGetError(context));
1028 int stack_depth = naStackDepth(context);
1029 if( stack_depth < 1 )
1031 SG_LOG(SG_NASAL, SG_ALERT,
1032 " at " << naStr_data(naGetSourceFile(context, 0)) <<
1033 ", line " << naGetLine(context, 0));
1034 for(int i=1; i<stack_depth; i++)
1035 SG_LOG(SG_NASAL, SG_ALERT,
1036 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
1037 ", line " << naGetLine(context, i));
1040 // Reads a script file, executes it, and places the resulting
1041 // namespace into the global namespace under the specified module
1043 bool FGNasalSys::loadModule(SGPath file, const char* module)
1046 char* buf = readfile(file.c_str(), &len);
1048 SG_LOG(SG_NASAL, SG_ALERT,
1049 "Nasal error: could not read script file " << file.c_str()
1050 << " into module " << module);
1054 bool ok = createModule(module, file.c_str(), buf, len);
1059 // Parse and run. Save the local variables namespace, as it will
1060 // become a sub-object of globals. The optional "arg" argument can be
1061 // used to pass an associated property node to the module, which can then
1062 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
1063 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1064 const char* src, int len,
1065 const SGPropertyNode* cmdarg,
1066 int argc, naRef* args)
1068 naRef code = parse(fileName, src, len);
1072 naContext ctx = naNewContext();
1074 // See if we already have a module hash to use. This allows the
1075 // user to, for example, add functions to the built-in math
1076 // module. Make a new one if necessary.
1078 naRef modname = naNewString(ctx);
1079 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1080 if(!naHash_get(_globals, modname, &locals))
1081 locals = naNewHash(ctx);
1083 _cmdArg = (SGPropertyNode*)cmdarg;
1085 call(code, argc, args, locals);
1086 hashset(_globals, moduleName, locals);
1092 void FGNasalSys::deleteModule(const char* moduleName)
1094 naContext ctx = naNewContext();
1095 naRef modname = naNewString(ctx);
1096 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1097 naHash_delete(_globals, modname);
1101 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
1104 naContext ctx = naNewContext();
1105 naRef srcfile = naNewString(ctx);
1106 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1107 naRef code = naParseCode(ctx, srcfile, 1, (char*)buf, len, &errLine);
1109 SG_LOG(SG_NASAL, SG_ALERT,
1110 "Nasal parse error: " << naGetError(ctx) <<
1111 " in "<< filename <<", line " << errLine);
1116 // Bind to the global namespace before returning
1117 naRef bound = naBindFunction(ctx, code, _globals);
1122 bool FGNasalSys::handleCommand( const char* moduleName,
1123 const char* fileName,
1125 const SGPropertyNode* arg )
1127 naRef code = parse(fileName, src, strlen(src));
1128 if(naIsNil(code)) return false;
1130 // Commands can be run "in" a module. Make sure that module
1131 // exists, and set it up as the local variables hash for the
1133 naRef locals = naNil();
1135 naContext ctx = naNewContext();
1136 naRef modname = naNewString(ctx);
1137 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1138 if(!naHash_get(_globals, modname, &locals)) {
1139 locals = naNewHash(ctx);
1140 naHash_set(_globals, modname, locals);
1145 // Cache this command's argument for inspection via cmdarg(). For
1146 // performance reasons, we won't bother with it if the invoked
1147 // code doesn't need it.
1148 _cmdArg = (SGPropertyNode*)arg;
1150 call(code, 0, 0, locals);
1154 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1156 const char* src = arg->getStringValue("script");
1157 const char* moduleName = arg->getStringValue("module");
1159 return handleCommand( moduleName,
1160 arg ? arg->getPath(true).c_str() : moduleName,
1165 // settimer(func, dt, simtime) extension function. The first argument
1166 // is a Nasal function to call, the second is a delta time (from now),
1167 // in seconds. The third, if present, is a boolean value indicating
1168 // that "real world" time (rather than simulator time) is to be used.
1170 // Implementation note: the FGTimer objects don't live inside the
1171 // garbage collector, so the Nasal handler functions have to be
1172 // "saved" somehow lest they be inadvertently cleaned. In this case,
1173 // they are inserted into a globals.__gcsave hash and removed on
1175 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1177 // Extract the handler, delta, and simtime arguments:
1178 naRef handler = argc > 0 ? args[0] : naNil();
1179 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1180 naRuntimeError(c, "settimer() with invalid function argument");
1184 naRef delta = argc > 1 ? args[1] : naNil();
1185 if(naIsNil(delta)) {
1186 naRuntimeError(c, "settimer() with invalid time argument");
1190 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1192 // Generate and register a C++ timer handler
1193 NasalTimer* t = new NasalTimer;
1194 t->handler = handler;
1195 t->gcKey = gcSave(handler);
1198 globals->get_event_mgr()->addEvent("NasalTimer",
1199 t, &NasalTimer::timerExpired,
1200 delta.num, simtime);
1203 void FGNasalSys::handleTimer(NasalTimer* t)
1205 call(t->handler, 0, 0, naNil());
1206 gcRelease(t->gcKey);
1209 int FGNasalSys::gcSave(naRef r)
1214 void FGNasalSys::gcRelease(int key)
1219 void FGNasalSys::NasalTimer::timerExpired()
1221 nasal->handleTimer(this);
1225 int FGNasalSys::_listenerId = 0;
1227 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1228 // Attaches a callback function to a property (specified as a global
1229 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1230 // optional argument (default=0) is set to 1, then the function is also
1231 // called initially. If the fourth, optional argument is set to 0, then the
1232 // function is only called when the property node value actually changes.
1233 // Otherwise it's called independent of the value whenever the node is
1234 // written to (default). The setlistener() function returns a unique
1235 // id number, which is to be used as argument to the removelistener()
1237 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1239 SGPropertyNode_ptr node;
1240 naRef prop = argc > 0 ? args[0] : naNil();
1241 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1242 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1244 naRuntimeError(c, "setlistener() with invalid property argument");
1249 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1252 naRef code = argc > 1 ? args[1] : naNil();
1253 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1254 naRuntimeError(c, "setlistener() with invalid function argument");
1258 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1259 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1260 FGNasalListener *nl = new FGNasalListener(node, code, this,
1261 gcSave(code), _listenerId, init, type);
1263 node->addChangeListener(nl, init != 0);
1265 _listener[_listenerId] = nl;
1266 return naNum(_listenerId++);
1269 // removelistener(int) extension function. The argument is the id of
1270 // a listener as returned by the setlistener() function.
1271 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1273 naRef id = argc > 0 ? args[0] : naNil();
1274 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1276 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1277 naRuntimeError(c, "removelistener() with invalid listener id");
1281 it->second->_dead = true;
1282 _dead_listener.push_back(it->second);
1283 _listener.erase(it);
1284 return naNum(_listener.size());
1287 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1289 if( _loadList.empty() )
1291 _loadList.push(data);
1294 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1296 _unloadList.push(data);
1299 void FGNasalSys::addCommand(naRef func, const std::string& name)
1301 if (_commands.find(name) != _commands.end()) {
1302 SG_LOG(SG_NASAL, SG_WARN, "duplicate add of command:" << name);
1306 NasalCommand* cmd = new NasalCommand(this, func, name);
1307 _commands[name] = cmd;
1310 void FGNasalSys::removeCommand(const std::string& name)
1312 NasalCommandDict::iterator it = _commands.find(name);
1313 if (it == _commands.end()) {
1314 SG_LOG(SG_NASAL, SG_WARN, "remove of unknwon command:" << name);
1318 // will delete the NasalCommand instance
1319 globals->get_commands()->removeCommand(name);
1320 _commands.erase(it);
1323 //////////////////////////////////////////////////////////////////////////
1324 // FGNasalListener class.
1326 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1327 FGNasalSys* nasal, int key, int id,
1328 int init, int type) :
1341 if(_type == 0 && !_init)
1345 FGNasalListener::~FGNasalListener()
1347 _node->removeChangeListener(this);
1348 _nas->gcRelease(_gcKey);
1351 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1353 if(_active || _dead) return;
1356 arg[0] = _nas->propNodeGhost(which);
1357 arg[1] = _nas->propNodeGhost(_node);
1358 arg[2] = mode; // value changed, child added/removed
1359 arg[3] = naNum(_node != which); // child event?
1360 _nas->call(_code, 4, arg, naNil());
1364 void FGNasalListener::valueChanged(SGPropertyNode* node)
1366 if(_type < 2 && node != _node) return; // skip child events
1367 if(_type > 0 || changed(_node) || _init)
1368 call(node, naNum(0));
1373 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1375 if(_type == 2) call(child, naNum(1));
1378 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1380 if(_type == 2) call(child, naNum(-1));
1383 bool FGNasalListener::changed(SGPropertyNode* node)
1385 using namespace simgear;
1386 props::Type type = node->getType();
1387 if(type == props::NONE) return false;
1388 if(type == props::UNSPECIFIED) return true;
1396 long l = node->getLongValue();
1397 result = l != _last_int;
1404 double d = node->getDoubleValue();
1405 result = d != _last_float;
1411 string s = node->getStringValue();
1412 result = s != _last_string;
1419 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1421 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1422 _c(naSubContext(c)),
1423 _start_element(argc > 1 ? args[1] : naNil()),
1424 _end_element(argc > 2 ? args[2] : naNil()),
1425 _data(argc > 3 ? args[3] : naNil()),
1426 _pi(argc > 4 ? args[4] : naNil())
1430 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1432 if(naIsNil(_start_element)) return;
1433 naRef attr = naNewHash(_c);
1434 for(int i=0; i<a.size(); i++) {
1435 naRef name = make_string(a.getName(i));
1436 naRef value = make_string(a.getValue(i));
1437 naHash_set(attr, name, value);
1439 call(_start_element, 2, make_string(tag), attr);
1442 void NasalXMLVisitor::endElement(const char* tag)
1444 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1447 void NasalXMLVisitor::data(const char* str, int len)
1449 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1452 void NasalXMLVisitor::pi(const char* target, const char* data)
1454 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1457 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1462 naCall(_c, func, num, args, naNil(), naNil());
1467 naRef NasalXMLVisitor::make_string(const char* s, int n)
1469 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1470 n < 0 ? strlen(s) : n);