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()
206 _nextGCKey = 0; // Any value will do
209 _log = new simgear::BufferedLogCallback(SG_NASAL, SG_INFO);
210 _log->truncateAt(255);
211 sglog().addCallback(_log);
214 // Utility. Sets a named key in a hash by C string, rather than nasal
216 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
218 naRef s = naNewString(_context);
219 naStr_fromdata(s, (char*)key, strlen(key));
220 naHash_set(hash, s, val);
223 void FGNasalSys::globalsSet(const char* key, naRef val)
225 hashset(_globals, key, val);
228 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
230 return callMethod(code, naNil(), argc, args, locals);
233 // Does a naCall() in a new context. Wrapped here to make lock
234 // tracking easier. Extension functions are called with the lock, but
235 // we have to release it before making a new naCall(). So rather than
236 // drop the lock in every extension function that might call back into
237 // Nasal, we keep a stack depth counter here and only unlock/lock
238 // around the naCall if it isn't the first one.
240 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
242 naContext ctx = naNewContext();
243 if(_callCount) naModUnlock();
245 naRef result = naCall(ctx, code, argc, args, self, locals);
249 if(_callCount) naModLock();
254 FGNasalSys::~FGNasalSys()
257 map<int, FGNasalListener *>::iterator it, end = _listener.end();
258 for(it = _listener.begin(); it != end; ++it)
261 naFreeContext(_context);
266 bool FGNasalSys::parseAndRun(const char* sourceCode)
268 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
272 call(code, 0, 0, naNil());
277 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
279 FGNasalScript* script = new FGNasalScript();
280 script->_gcKey = -1; // important, if we delete it on a parse
281 script->_nas = this; // error, don't clobber a real handle!
285 sprintf(buf, "FGNasalScript@%p", (void *)script);
289 script->_code = parse(name, src, strlen(src));
290 if(naIsNil(script->_code)) {
295 script->_gcKey = gcSave(script->_code);
300 // The get/setprop functions accept a *list* of strings and walk
301 // through the property tree with them to find the appropriate node.
302 // This allows a Nasal object to hold onto a property path and use it
303 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
304 // is the utility function that walks the property tree.
305 // Future enhancement: support integer arguments to specify array
307 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
309 SGPropertyNode* p = globals->get_props();
311 for(int i=0; i<len; i++) {
313 if(!naIsString(a)) return 0;
314 p = p->getNode(naStr_data(a));
317 } catch (const string& err) {
318 naRuntimeError(c, (char *)err.c_str());
324 // getprop() extension function. Concatenates its string arguments as
325 // property names and returns the value of the specified property. Or
326 // nil if it doesn't exist.
327 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
329 using namespace simgear;
330 const SGPropertyNode* p = findnode(c, args, argc);
331 if(!p) return naNil();
333 switch(p->getType()) {
334 case props::BOOL: case props::INT:
335 case props::LONG: case props::FLOAT:
338 double dv = p->getDoubleValue();
339 if (SGMisc<double>::isNaN(dv)) {
340 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
348 case props::UNSPECIFIED:
350 naRef nastr = naNewString(c);
351 const char* val = p->getStringValue();
352 naStr_fromdata(nastr, (char*)val, strlen(val));
355 case props::ALIAS: // <--- FIXME, recurse?
361 // setprop() extension function. Concatenates its string arguments as
362 // property names and sets the value of the specified property to the
364 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
367 char buf[BUFLEN + 1];
371 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
372 for(int i=0; i<argc-1; i++) {
373 naRef s = naStringValue(c, args[i]);
374 if(naIsNil(s)) return naNil();
375 strncpy(p, naStr_data(s), buflen);
377 buflen = BUFLEN - (p - buf);
378 if(i < (argc-2) && buflen > 0) {
384 SGPropertyNode* props = globals->get_props();
385 naRef val = args[argc-1];
388 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
390 naRef n = naNumValue(val);
392 naRuntimeError(c, "setprop() value is not string or number");
394 if (SGMisc<double>::isNaN(n.num)) {
395 naRuntimeError(c, "setprop() passed a NaN");
398 result = props->setDoubleValue(buf, n.num);
400 } catch (const string& err) {
401 naRuntimeError(c, (char *)err.c_str());
403 return naNum(result);
407 // print() extension function. Concatenates and prints its arguments
408 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
409 // make sure it appears. Is there better way to do this?
410 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
414 for(int i=0; i<n; i++) {
415 naRef s = naStringValue(c, args[i]);
416 if(naIsNil(s)) continue;
417 buf += naStr_data(s);
419 SG_LOG(SG_NASAL, SG_ALERT, buf);
420 return naNum(buf.length());
423 // logprint() extension function. Same as above, all arguments after the
424 // first argument are concatenated. Argument 0 is the log-level, matching
426 static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
429 naRuntimeError(c, "no prioirty argument to logprint()");
431 naRef priority = args[0];
434 for(int i=1; i<n; i++) {
435 naRef s = naStringValue(c, args[i]);
436 if(naIsNil(s)) continue;
437 buf += naStr_data(s);
439 // use the nasal source file and line for the message location, since
440 // that's more useful than the location here!
441 sglog().log(SG_NASAL, (sgDebugPriority)(int) priority.num,
442 naStr_data(naGetSourceFile(c, 0)),
443 naGetLine(c, 0), buf);
444 return naNum(buf.length());
448 // fgcommand() extension function. Executes a named command via the
449 // FlightGear command manager. Takes a single property node name as
451 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
453 naRef cmd = argc > 0 ? args[0] : naNil();
454 naRef props = argc > 1 ? args[1] : naNil();
455 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
456 naRuntimeError(c, "bad arguments to fgcommand()");
457 SGPropertyNode_ptr tmp, *node;
459 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
461 tmp = new SGPropertyNode();
464 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
467 // settimer(func, dt, simtime) extension function. Falls through to
468 // FGNasalSys::setTimer(). See there for docs.
469 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
471 nasalSys->setTimer(c, argc, args);
475 static naRef f_makeTimer(naContext c, naRef me, int argc, naRef* args)
477 if (!naIsNum(args[0])) {
478 naRuntimeError(c, "bad interval argument to maketimer");
481 naRef func, self = naNil();
482 if (naIsFunc(args[1])) {
484 } else if ((argc == 3) && naIsFunc(args[2])) {
489 TimerObj* timerObj = new TimerObj(nasalSys, func, self, args[0].num);
490 return NasalTimerObj::create(c, timerObj);
493 // setlistener(func, property, bool) extension function. Falls through to
494 // FGNasalSys::setListener(). See there for docs.
495 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
497 return nasalSys->setListener(c, argc, args);
500 // removelistener(int) extension function. Falls through to
501 // FGNasalSys::removeListener(). See there for docs.
502 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
504 return nasalSys->removeListener(c, argc, args);
507 // Returns a ghost handle to the argument to the currently executing
509 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
511 return nasalSys->cmdArgGhost();
514 // Sets up a property interpolation. The first argument is either a
515 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
516 // interpolate. The second argument is a vector of pairs of
517 // value/delta numbers.
518 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
520 SGPropertyNode* node;
521 naRef prop = argc > 0 ? args[0] : naNil();
522 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
523 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
526 naRef curve = argc > 1 ? args[1] : naNil();
527 if(!naIsVector(curve)) return naNil();
528 int nPoints = naVec_size(curve) / 2;
530 simgear::PropertyList value_nodes;
531 value_nodes.reserve(nPoints);
533 deltas.reserve(nPoints);
535 for( int i = 0; i < nPoints; ++i )
537 SGPropertyNode* val = new SGPropertyNode;
538 val->setDoubleValue(naNumValue(naVec_get(curve, 2*i)).num);
539 value_nodes.push_back(val);
540 deltas.push_back(naNumValue(naVec_get(curve, 2*i+1)).num);
543 node->interpolate("numeric", value_nodes, deltas, "linear");
547 // This is a better RNG than the one in the default Nasal distribution
548 // (which is based on the C library rand() implementation). It will
550 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
552 return naNum(sg_random());
555 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
561 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
567 // Return an array listing of all files in a directory
568 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
570 if(argc != 1 || !naIsString(args[0]))
571 naRuntimeError(c, "bad arguments to directory()");
573 simgear::Dir d(SGPath(naStr_data(args[0])));
574 if(!d.exists()) return naNil();
575 naRef result = naNewVector(c);
577 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
578 for (unsigned int i=0; i<paths.size(); ++i) {
579 std::string p = paths[i].file();
580 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
587 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
589 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
591 if(argc != 1 || !naIsString(args[0]))
592 naRuntimeError(c, "bad arguments to resolveDataPath()");
594 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
595 const char* pdata = p.c_str();
596 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
599 static naRef f_findDataDir(naContext c, naRef me, int argc, naRef* args)
601 if(argc != 1 || !naIsString(args[0]))
602 naRuntimeError(c, "bad arguments to findDataDir()");
604 SGPath p = globals->find_data_dir(naStr_data(args[0]));
605 const char* pdata = p.c_str();
606 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
609 class NasalCommand : public SGCommandMgr::Command
612 NasalCommand(FGNasalSys* sys, naRef f) :
616 _gcRoot = sys->gcSave(f);
619 virtual ~NasalCommand()
621 _sys->gcRelease(_gcRoot);
624 virtual bool operator()(const SGPropertyNode* aNode)
626 _sys->setCmdArg(const_cast<SGPropertyNode*>(aNode));
628 args[0] = _sys->wrappedPropsNode(const_cast<SGPropertyNode*>(aNode));
630 _sys->callMethod(_func, naNil(), 1, args, naNil() /* locals */);
641 static naRef f_addCommand(naContext c, naRef me, int argc, naRef* args)
643 if(argc != 2 || !naIsString(args[0]) || !naIsFunc(args[1]))
644 naRuntimeError(c, "bad arguments to addcommand()");
646 naRef func = args[1];
647 NasalCommand* cmd = new NasalCommand(nasalSys, func);
648 globals->get_commands()->addCommandObject(naStr_data(args[0]), cmd);
652 static naRef f_removeCommand(naContext c, naRef me, int argc, naRef* args)
654 SGCommandMgr::Command* cmd = globals->get_commands()->getCommand(naStr_data(args[0]));
656 // SGCommandMgr::Command* cmd = globals->get_commands()->removeCommand(naStr_data(args[0]))
664 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
666 // <path> ... absolute path to an XML file
667 // <start-tag> ... callback function with two args: tag name, attribute hash
668 // <end-tag> ... callback function with one arg: tag name
669 // <data> ... callback function with one arg: data
670 // <pi> ... callback function with two args: target, data
671 // (pi = "processing instruction")
672 // All four callback functions are optional and default to nil.
673 // The function returns nil on error, or the validated file name otherwise.
674 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
676 if(argc < 1 || !naIsString(args[0]))
677 naRuntimeError(c, "parsexml(): path argument missing or not a string");
678 if(argc > 5) argc = 5;
679 for(int i=1; i<argc; i++)
680 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
681 naRuntimeError(c, "parsexml(): callback argument not a function");
683 const char* file = fgValidatePath(naStr_data(args[0]), false);
685 naRuntimeError(c, "parsexml(): reading '%s' denied "
686 "(unauthorized access)", naStr_data(args[0]));
689 std::ifstream input(file);
690 NasalXMLVisitor visitor(c, argc, args);
692 readXML(input, visitor);
693 } catch (const sg_exception& e) {
694 naRuntimeError(c, "parsexml(): file '%s' %s",
695 file, e.getFormattedMessage().c_str());
698 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
701 // Return UNIX epoch time in seconds.
702 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
706 GetSystemTimeAsFileTime(&ft);
707 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
708 // Converts from 100ns units in 1601 epoch to unix epoch in sec
709 return naNum((t * 1e-7) - 11644473600.0);
712 gettimeofday(&td, 0);
713 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
717 // Table of extension functions. Terminate with zeros.
718 static struct { const char* name; naCFunction func; } funcs[] = {
719 { "getprop", f_getprop },
720 { "setprop", f_setprop },
721 { "print", f_print },
722 { "logprint", f_logprint },
723 { "_fgcommand", f_fgcommand },
724 { "settimer", f_settimer },
725 { "maketimer", f_makeTimer },
726 { "_setlistener", f_setlistener },
727 { "removelistener", f_removelistener },
728 { "addcommand", f_addCommand },
729 { "removecommand", f_removeCommand },
730 { "_cmdarg", f_cmdarg },
731 { "_interpolate", f_interpolate },
733 { "srand", f_srand },
734 { "abort", f_abort },
735 { "directory", f_directory },
736 { "resolvepath", f_resolveDataPath },
737 { "finddata", f_findDataDir },
738 { "parsexml", f_parsexml },
739 { "systime", f_systime },
743 naRef FGNasalSys::cmdArgGhost()
745 return propNodeGhost(_cmdArg);
748 void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
753 void FGNasalSys::init()
757 _context = naNewContext();
759 // Start with globals. Add it to itself as a recursive
760 // sub-reference under the name "globals". This gives client-code
761 // write access to the namespace if someone wants to do something
763 _globals = naInit_std(_context);
764 naSave(_context, _globals);
765 hashset(_globals, "globals", _globals);
767 hashset(_globals, "math", naInit_math(_context));
768 hashset(_globals, "bits", naInit_bits(_context));
769 hashset(_globals, "io", naInit_io(_context));
770 hashset(_globals, "thread", naInit_thread(_context));
771 hashset(_globals, "utf8", naInit_utf8(_context));
773 // Add our custom extension functions:
774 for(i=0; funcs[i].name; i++)
775 hashset(_globals, funcs[i].name,
776 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
778 // And our SGPropertyNode wrapper
779 hashset(_globals, "props", genPropsModule());
781 // Make a "__gcsave" hash to hold the naRef objects which get
782 // passed to handles outside the interpreter (to protect them from
783 // begin garbage-collected).
784 _gcHash = naNewHash(_context);
785 hashset(_globals, "__gcsave", _gcHash);
787 // Add string methods
788 _string = naInit_string(_context);
789 naSave(_context, _string);
790 initNasalString(_globals, _string, _context, _gcHash);
792 initNasalPositioned(_globals, _context, _gcHash);
793 initNasalPositioned_cppbind(_globals, _context, _gcHash);
794 NasalClipboard::init(this);
795 initNasalCanvas(_globals, _context, _gcHash);
796 initNasalCondition(_globals, _context, _gcHash);
798 NasalTimerObj::init("Timer")
799 .method("start", &TimerObj::start)
800 .method("stop", &TimerObj::stop)
801 .method("restart", &TimerObj::restart)
802 .member("singleShot", &TimerObj::isSingleShot, &TimerObj::setSingleShot)
803 .member("isRunning", &TimerObj::isRunning);
805 // Now load the various source files in the Nasal directory
806 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
807 loadScriptDirectory(nasalDir);
809 // Add modules in Nasal subdirectories to property tree
810 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
811 simgear::Dir::NO_DOT_OR_DOTDOT, "");
812 for (unsigned int i=0; i<directories.size(); ++i) {
813 simgear::Dir dir(directories[i]);
814 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
815 addModule(directories[i].file(), scripts);
818 // set signal and remove node to avoid restoring at reinit
819 const char *s = "nasal-dir-initialized";
820 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
821 signal->setBoolValue(s, true);
822 signal->removeChildren(s, false);
824 // Pull scripts out of the property tree, too
825 loadPropertyScripts();
827 // now Nasal modules are loaded, we can do some delayed work
828 postinitNasalPositioned(_globals, _context);
829 postinitNasalGUI(_globals, _context);
832 naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps)
834 static naRef wrapNodeFunc = naNil();
835 if (naIsNil(wrapNodeFunc)) {
836 nasal::Hash props = getGlobals().get<nasal::Hash>("props");
837 wrapNodeFunc = props.get("wrapNode");
841 args[0] = propNodeGhost(aProps);
842 return naCall(_context, wrapNodeFunc, 1, args, naNil(), naNil());
845 void FGNasalSys::update(double)
847 if( NasalClipboard::getInstance() )
848 NasalClipboard::getInstance()->update();
850 if(!_dead_listener.empty()) {
851 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
852 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
853 _dead_listener.clear();
856 if (!_loadList.empty())
861 // process Nasal load hook (only one per update loop to avoid excessive lags)
862 _loadList.pop()->load();
865 if (!_unloadList.empty())
867 // process pending Nasal unload hooks after _all_ load hooks were processed
868 // (only unload one per update loop to avoid excessive lags)
869 _unloadList.pop()->unload();
872 // The global context is a legacy thing. We use dynamically
873 // created contexts for naCall() now, so that we can call them
874 // recursively. But there are still spots that want to use it for
875 // naNew*() calls, which end up leaking memory because the context
876 // only clears out its temporary vector when it's *used*. So just
877 // junk it and fetch a new/reinitialized one every frame. This is
878 // clumsy: the right solution would use the dynamic context in all
879 // cases and eliminate _context entirely. But that's more work,
880 // and this works fine (yes, they say "New" and "Free", but
881 // they're very fast, just trust me). -Andy
882 naFreeContext(_context);
883 _context = naNewContext();
886 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
888 return p1.file() < p2.file();
891 // Loads all scripts in given directory
892 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
894 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
895 // Note: simgear::Dir already reports file entries in a deterministic order,
896 // so a fixed loading sequence is guaranteed (same for every user)
897 for (unsigned int i=0; i<scripts.size(); ++i) {
898 SGPath fullpath(scripts[i]);
899 SGPath file = fullpath.file();
900 loadModule(fullpath, file.base().c_str());
904 // Create module with list of scripts
905 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
907 if (! scripts.empty())
909 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
910 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
911 for (unsigned int i=0; i<scripts.size(); ++i) {
912 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
913 pFileNode->setStringValue(scripts[i].c_str());
915 if (!module_node->hasChild("enabled",0))
917 SGPropertyNode* node = module_node->getChild("enabled",0,true);
918 node->setBoolValue(true);
919 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
924 // Loads the scripts found under /nasal in the global tree
925 void FGNasalSys::loadPropertyScripts()
927 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
930 for(int i=0; i<nasal->nChildren(); i++)
932 SGPropertyNode* n = nasal->getChild(i);
933 loadPropertyScripts(n);
937 // Loads the scripts found under /nasal in the global tree
938 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
940 bool is_loaded = false;
942 const char* module = n->getName();
943 if(n->hasChild("module"))
944 module = n->getStringValue("module");
945 if (n->getBoolValue("enabled",true))
947 // allow multiple files to be specified within a single
951 bool file_specified = false;
953 while((fn = n->getChild("file", j)) != NULL) {
954 file_specified = true;
955 const char* file = fn->getStringValue();
957 if (!p.isAbsolute() || !p.exists())
959 p = globals->resolve_maybe_aircraft_path(file);
962 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
963 file << "' for module '" << module << "'.");
966 ok &= p.isNull() ? false : loadModule(p, module);
970 const char* src = n->getStringValue("script");
971 if(!n->hasChild("script")) src = 0; // Hrm...
973 createModule(module, n->getPath().c_str(), src, strlen(src));
975 if(!file_specified && !src)
977 // module no longer exists - clear the archived "enable" flag
978 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
979 SGPropertyNode* node = n->getChild("enabled",0,false);
981 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
983 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
984 "no <file> or <script> defined in " <<
985 "/nasal/" << module);
992 SGPropertyNode* enable = n->getChild("enabled");
995 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
996 enable->addChangeListener(listener, false);
999 SGPropertyNode* loaded = n->getChild("loaded",0,true);
1000 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
1001 loaded->setBoolValue(is_loaded);
1004 // Logs a runtime error, with stack trace, to the FlightGear log stream
1005 void FGNasalSys::logError(naContext context)
1007 SG_LOG(SG_NASAL, SG_ALERT,
1008 "Nasal runtime error: " << naGetError(context));
1009 SG_LOG(SG_NASAL, SG_ALERT,
1010 " at " << naStr_data(naGetSourceFile(context, 0)) <<
1011 ", line " << naGetLine(context, 0));
1012 for(int i=1; i<naStackDepth(context); i++)
1013 SG_LOG(SG_NASAL, SG_ALERT,
1014 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
1015 ", line " << naGetLine(context, i));
1018 // Reads a script file, executes it, and places the resulting
1019 // namespace into the global namespace under the specified module
1021 bool FGNasalSys::loadModule(SGPath file, const char* module)
1024 char* buf = readfile(file.c_str(), &len);
1026 SG_LOG(SG_NASAL, SG_ALERT,
1027 "Nasal error: could not read script file " << file.c_str()
1028 << " into module " << module);
1032 bool ok = createModule(module, file.c_str(), buf, len);
1037 // Parse and run. Save the local variables namespace, as it will
1038 // become a sub-object of globals. The optional "arg" argument can be
1039 // used to pass an associated property node to the module, which can then
1040 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
1041 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1042 const char* src, int len,
1043 const SGPropertyNode* cmdarg,
1044 int argc, naRef* args)
1046 naRef code = parse(fileName, src, len);
1050 // See if we already have a module hash to use. This allows the
1051 // user to, for example, add functions to the built-in math
1052 // module. Make a new one if necessary.
1054 naRef modname = naNewString(_context);
1055 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1056 if(!naHash_get(_globals, modname, &locals))
1057 locals = naNewHash(_context);
1059 _cmdArg = (SGPropertyNode*)cmdarg;
1061 call(code, argc, args, locals);
1062 hashset(_globals, moduleName, locals);
1066 void FGNasalSys::deleteModule(const char* moduleName)
1068 naRef modname = naNewString(_context);
1069 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1070 naHash_delete(_globals, modname);
1073 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
1076 naRef srcfile = naNewString(_context);
1077 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1078 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
1080 SG_LOG(SG_NASAL, SG_ALERT,
1081 "Nasal parse error: " << naGetError(_context) <<
1082 " in "<< filename <<", line " << errLine);
1086 // Bind to the global namespace before returning
1087 return naBindFunction(_context, code, _globals);
1090 bool FGNasalSys::handleCommand( const char* moduleName,
1091 const char* fileName,
1093 const SGPropertyNode* arg )
1095 naRef code = parse(fileName, src, strlen(src));
1096 if(naIsNil(code)) return false;
1098 // Commands can be run "in" a module. Make sure that module
1099 // exists, and set it up as the local variables hash for the
1101 naRef locals = naNil();
1103 naRef modname = naNewString(_context);
1104 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1105 if(!naHash_get(_globals, modname, &locals)) {
1106 locals = naNewHash(_context);
1107 naHash_set(_globals, modname, locals);
1111 // Cache this command's argument for inspection via cmdarg(). For
1112 // performance reasons, we won't bother with it if the invoked
1113 // code doesn't need it.
1114 _cmdArg = (SGPropertyNode*)arg;
1116 call(code, 0, 0, locals);
1120 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1122 const char* src = arg->getStringValue("script");
1123 const char* moduleName = arg->getStringValue("module");
1125 return handleCommand( moduleName,
1126 arg ? arg->getPath(true).c_str() : moduleName,
1131 // settimer(func, dt, simtime) extension function. The first argument
1132 // is a Nasal function to call, the second is a delta time (from now),
1133 // in seconds. The third, if present, is a boolean value indicating
1134 // that "real world" time (rather than simulator time) is to be used.
1136 // Implementation note: the FGTimer objects don't live inside the
1137 // garbage collector, so the Nasal handler functions have to be
1138 // "saved" somehow lest they be inadvertently cleaned. In this case,
1139 // they are inserted into a globals.__gcsave hash and removed on
1141 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1143 // Extract the handler, delta, and simtime arguments:
1144 naRef handler = argc > 0 ? args[0] : naNil();
1145 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1146 naRuntimeError(c, "settimer() with invalid function argument");
1150 naRef delta = argc > 1 ? args[1] : naNil();
1151 if(naIsNil(delta)) {
1152 naRuntimeError(c, "settimer() with invalid time argument");
1156 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1158 // Generate and register a C++ timer handler
1159 NasalTimer* t = new NasalTimer;
1160 t->handler = handler;
1161 t->gcKey = gcSave(handler);
1164 globals->get_event_mgr()->addEvent("NasalTimer",
1165 t, &NasalTimer::timerExpired,
1166 delta.num, simtime);
1169 void FGNasalSys::handleTimer(NasalTimer* t)
1171 call(t->handler, 0, 0, naNil());
1172 gcRelease(t->gcKey);
1175 int FGNasalSys::gcSave(naRef r)
1177 int key = _nextGCKey++;
1178 naHash_set(_gcHash, naNum(key), r);
1182 void FGNasalSys::gcRelease(int key)
1184 naHash_delete(_gcHash, naNum(key));
1187 void FGNasalSys::NasalTimer::timerExpired()
1189 nasal->handleTimer(this);
1193 int FGNasalSys::_listenerId = 0;
1195 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1196 // Attaches a callback function to a property (specified as a global
1197 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1198 // optional argument (default=0) is set to 1, then the function is also
1199 // called initially. If the fourth, optional argument is set to 0, then the
1200 // function is only called when the property node value actually changes.
1201 // Otherwise it's called independent of the value whenever the node is
1202 // written to (default). The setlistener() function returns a unique
1203 // id number, which is to be used as argument to the removelistener()
1205 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1207 SGPropertyNode_ptr node;
1208 naRef prop = argc > 0 ? args[0] : naNil();
1209 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1210 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1212 naRuntimeError(c, "setlistener() with invalid property argument");
1217 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1220 naRef code = argc > 1 ? args[1] : naNil();
1221 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1222 naRuntimeError(c, "setlistener() with invalid function argument");
1226 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1227 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1228 FGNasalListener *nl = new FGNasalListener(node, code, this,
1229 gcSave(code), _listenerId, init, type);
1231 node->addChangeListener(nl, init != 0);
1233 _listener[_listenerId] = nl;
1234 return naNum(_listenerId++);
1237 // removelistener(int) extension function. The argument is the id of
1238 // a listener as returned by the setlistener() function.
1239 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1241 naRef id = argc > 0 ? args[0] : naNil();
1242 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1244 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1245 naRuntimeError(c, "removelistener() with invalid listener id");
1249 it->second->_dead = true;
1250 _dead_listener.push_back(it->second);
1251 _listener.erase(it);
1252 return naNum(_listener.size());
1255 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1257 if( _loadList.empty() )
1259 _loadList.push(data);
1262 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1264 _unloadList.push(data);
1267 //////////////////////////////////////////////////////////////////////////
1268 // FGNasalListener class.
1270 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1271 FGNasalSys* nasal, int key, int id,
1272 int init, int type) :
1285 if(_type == 0 && !_init)
1289 FGNasalListener::~FGNasalListener()
1291 _node->removeChangeListener(this);
1292 _nas->gcRelease(_gcKey);
1295 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1297 if(_active || _dead) return;
1300 arg[0] = _nas->propNodeGhost(which);
1301 arg[1] = _nas->propNodeGhost(_node);
1302 arg[2] = mode; // value changed, child added/removed
1303 arg[3] = naNum(_node != which); // child event?
1304 _nas->call(_code, 4, arg, naNil());
1308 void FGNasalListener::valueChanged(SGPropertyNode* node)
1310 if(_type < 2 && node != _node) return; // skip child events
1311 if(_type > 0 || changed(_node) || _init)
1312 call(node, naNum(0));
1317 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1319 if(_type == 2) call(child, naNum(1));
1322 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1324 if(_type == 2) call(child, naNum(-1));
1327 bool FGNasalListener::changed(SGPropertyNode* node)
1329 using namespace simgear;
1330 props::Type type = node->getType();
1331 if(type == props::NONE) return false;
1332 if(type == props::UNSPECIFIED) return true;
1340 long l = node->getLongValue();
1341 result = l != _last_int;
1348 double d = node->getDoubleValue();
1349 result = d != _last_float;
1355 string s = node->getStringValue();
1356 result = s != _last_string;
1363 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1365 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1366 _c(naSubContext(c)),
1367 _start_element(argc > 1 ? args[1] : naNil()),
1368 _end_element(argc > 2 ? args[2] : naNil()),
1369 _data(argc > 3 ? args[3] : naNil()),
1370 _pi(argc > 4 ? args[4] : naNil())
1374 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1376 if(naIsNil(_start_element)) return;
1377 naRef attr = naNewHash(_c);
1378 for(int i=0; i<a.size(); i++) {
1379 naRef name = make_string(a.getName(i));
1380 naRef value = make_string(a.getValue(i));
1381 naHash_set(attr, name, value);
1383 call(_start_element, 2, make_string(tag), attr);
1386 void NasalXMLVisitor::endElement(const char* tag)
1388 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1391 void NasalXMLVisitor::data(const char* str, int len)
1393 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1396 void NasalXMLVisitor::pi(const char* target, const char* data)
1398 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1401 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1406 naCall(_c, func, num, args, naNil(), naNil());
1411 naRef NasalXMLVisitor::make_string(const char* s, int n)
1413 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1414 n < 0 ? strlen(s) : n);