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 _log = new simgear::BufferedLogCallback(SG_NASAL, SG_INFO);
207 _log->truncateAt(255);
208 sglog().addCallback(_log);
210 naSetErrorHandler(&logError);
213 // Utility. Sets a named key in a hash by C string, rather than nasal
215 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
217 naRef s = naNewString(_context);
218 naStr_fromdata(s, (char*)key, strlen(key));
219 naHash_set(hash, s, val);
222 void FGNasalSys::globalsSet(const char* key, naRef val)
224 hashset(_globals, key, val);
227 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
229 return callMethod(code, naNil(), argc, args, locals);
232 // Does a naCall() in a new context. Wrapped here to make lock
233 // tracking easier. Extension functions are called with the lock, but
234 // we have to release it before making a new naCall(). So rather than
235 // drop the lock in every extension function that might call back into
236 // Nasal, we keep a stack depth counter here and only unlock/lock
237 // around the naCall if it isn't the first one.
239 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
241 return naCallMethod(code, self, argc, args, locals);
244 FGNasalSys::~FGNasalSys()
247 map<int, FGNasalListener *>::iterator it, end = _listener.end();
248 for(it = _listener.begin(); it != end; ++it)
251 naFreeContext(_context);
256 bool FGNasalSys::parseAndRun(const char* sourceCode)
258 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
262 call(code, 0, 0, naNil());
267 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
269 FGNasalScript* script = new FGNasalScript();
270 script->_gcKey = -1; // important, if we delete it on a parse
271 script->_nas = this; // error, don't clobber a real handle!
275 sprintf(buf, "FGNasalScript@%p", (void *)script);
279 script->_code = parse(name, src, strlen(src));
280 if(naIsNil(script->_code)) {
285 script->_gcKey = gcSave(script->_code);
290 // The get/setprop functions accept a *list* of strings and walk
291 // through the property tree with them to find the appropriate node.
292 // This allows a Nasal object to hold onto a property path and use it
293 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
294 // is the utility function that walks the property tree.
295 // Future enhancement: support integer arguments to specify array
297 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
299 SGPropertyNode* p = globals->get_props();
301 for(int i=0; i<len; i++) {
303 if(!naIsString(a)) return 0;
304 p = p->getNode(naStr_data(a));
307 } catch (const string& err) {
308 naRuntimeError(c, (char *)err.c_str());
314 // getprop() extension function. Concatenates its string arguments as
315 // property names and returns the value of the specified property. Or
316 // nil if it doesn't exist.
317 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
319 using namespace simgear;
320 const SGPropertyNode* p = findnode(c, args, argc);
321 if(!p) return naNil();
323 switch(p->getType()) {
324 case props::BOOL: case props::INT:
325 case props::LONG: case props::FLOAT:
328 double dv = p->getDoubleValue();
329 if (SGMisc<double>::isNaN(dv)) {
330 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
338 case props::UNSPECIFIED:
340 naRef nastr = naNewString(c);
341 const char* val = p->getStringValue();
342 naStr_fromdata(nastr, (char*)val, strlen(val));
345 case props::ALIAS: // <--- FIXME, recurse?
351 // setprop() extension function. Concatenates its string arguments as
352 // property names and sets the value of the specified property to the
354 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
357 char buf[BUFLEN + 1];
361 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
362 for(int i=0; i<argc-1; i++) {
363 naRef s = naStringValue(c, args[i]);
364 if(naIsNil(s)) return naNil();
365 strncpy(p, naStr_data(s), buflen);
367 buflen = BUFLEN - (p - buf);
368 if(i < (argc-2) && buflen > 0) {
374 SGPropertyNode* props = globals->get_props();
375 naRef val = args[argc-1];
378 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
380 naRef n = naNumValue(val);
382 naRuntimeError(c, "setprop() value is not string or number");
384 if (SGMisc<double>::isNaN(n.num)) {
385 naRuntimeError(c, "setprop() passed a NaN");
388 result = props->setDoubleValue(buf, n.num);
390 } catch (const string& err) {
391 naRuntimeError(c, (char *)err.c_str());
393 return naNum(result);
397 // print() extension function. Concatenates and prints its arguments
398 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
399 // make sure it appears. Is there better way to do this?
400 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
404 for(int i=0; i<n; i++) {
405 naRef s = naStringValue(c, args[i]);
406 if(naIsNil(s)) continue;
407 buf += naStr_data(s);
409 SG_LOG(SG_NASAL, SG_ALERT, buf);
410 return naNum(buf.length());
413 // logprint() extension function. Same as above, all arguments after the
414 // first argument are concatenated. Argument 0 is the log-level, matching
416 static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
419 naRuntimeError(c, "no prioirty argument to logprint()");
421 naRef priority = args[0];
424 for(int i=1; i<n; i++) {
425 naRef s = naStringValue(c, args[i]);
426 if(naIsNil(s)) continue;
427 buf += naStr_data(s);
429 // use the nasal source file and line for the message location, since
430 // that's more useful than the location here!
431 sglog().log(SG_NASAL, (sgDebugPriority)(int) priority.num,
432 naStr_data(naGetSourceFile(c, 0)),
433 naGetLine(c, 0), buf);
434 return naNum(buf.length());
438 // fgcommand() extension function. Executes a named command via the
439 // FlightGear command manager. Takes a single property node name as
441 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
443 naRef cmd = argc > 0 ? args[0] : naNil();
444 naRef props = argc > 1 ? args[1] : naNil();
445 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
446 naRuntimeError(c, "bad arguments to fgcommand()");
447 SGPropertyNode_ptr tmp, *node;
449 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
451 tmp = new SGPropertyNode();
454 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
457 // settimer(func, dt, simtime) extension function. Falls through to
458 // FGNasalSys::setTimer(). See there for docs.
459 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
461 nasalSys->setTimer(c, argc, args);
465 static naRef f_makeTimer(naContext c, naRef me, int argc, naRef* args)
467 if (!naIsNum(args[0])) {
468 naRuntimeError(c, "bad interval argument to maketimer");
471 naRef func, self = naNil();
472 if (naIsFunc(args[1])) {
474 } else if ((argc == 3) && naIsFunc(args[2])) {
479 TimerObj* timerObj = new TimerObj(nasalSys, func, self, args[0].num);
480 return NasalTimerObj::create(c, timerObj);
483 // setlistener(func, property, bool) extension function. Falls through to
484 // FGNasalSys::setListener(). See there for docs.
485 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
487 return nasalSys->setListener(c, argc, args);
490 // removelistener(int) extension function. Falls through to
491 // FGNasalSys::removeListener(). See there for docs.
492 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
494 return nasalSys->removeListener(c, argc, args);
497 // Returns a ghost handle to the argument to the currently executing
499 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
501 return nasalSys->cmdArgGhost();
504 // Sets up a property interpolation. The first argument is either a
505 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
506 // interpolate. The second argument is a vector of pairs of
507 // value/delta numbers.
508 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
510 SGPropertyNode* node;
511 naRef prop = argc > 0 ? args[0] : naNil();
512 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
513 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
516 naRef curve = argc > 1 ? args[1] : naNil();
517 if(!naIsVector(curve)) return naNil();
518 int nPoints = naVec_size(curve) / 2;
520 simgear::PropertyList value_nodes;
521 value_nodes.reserve(nPoints);
523 deltas.reserve(nPoints);
525 for( int i = 0; i < nPoints; ++i )
527 SGPropertyNode* val = new SGPropertyNode;
528 val->setDoubleValue(naNumValue(naVec_get(curve, 2*i)).num);
529 value_nodes.push_back(val);
530 deltas.push_back(naNumValue(naVec_get(curve, 2*i+1)).num);
533 node->interpolate("numeric", value_nodes, deltas, "linear");
537 // This is a better RNG than the one in the default Nasal distribution
538 // (which is based on the C library rand() implementation). It will
540 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
542 return naNum(sg_random());
545 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
551 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
557 // Return an array listing of all files in a directory
558 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
560 if(argc != 1 || !naIsString(args[0]))
561 naRuntimeError(c, "bad arguments to directory()");
563 simgear::Dir d(SGPath(naStr_data(args[0])));
564 if(!d.exists()) return naNil();
565 naRef result = naNewVector(c);
567 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
568 for (unsigned int i=0; i<paths.size(); ++i) {
569 std::string p = paths[i].file();
570 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
577 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
579 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
581 if(argc != 1 || !naIsString(args[0]))
582 naRuntimeError(c, "bad arguments to resolveDataPath()");
584 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
585 const char* pdata = p.c_str();
586 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
589 static naRef f_findDataDir(naContext c, naRef me, int argc, naRef* args)
591 if(argc != 1 || !naIsString(args[0]))
592 naRuntimeError(c, "bad arguments to findDataDir()");
594 SGPath p = globals->find_data_dir(naStr_data(args[0]));
595 const char* pdata = p.c_str();
596 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
599 class NasalCommand : public SGCommandMgr::Command
602 NasalCommand(FGNasalSys* sys, naRef f) :
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 */);
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 naRef func = args[1];
637 NasalCommand* cmd = new NasalCommand(nasalSys, func);
638 globals->get_commands()->addCommandObject(naStr_data(args[0]), cmd);
642 static naRef f_removeCommand(naContext c, naRef me, int argc, naRef* args)
644 SGCommandMgr::Command* cmd = globals->get_commands()->getCommand(naStr_data(args[0]));
646 // SGCommandMgr::Command* cmd = globals->get_commands()->removeCommand(naStr_data(args[0]))
654 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
656 // <path> ... absolute path to an XML file
657 // <start-tag> ... callback function with two args: tag name, attribute hash
658 // <end-tag> ... callback function with one arg: tag name
659 // <data> ... callback function with one arg: data
660 // <pi> ... callback function with two args: target, data
661 // (pi = "processing instruction")
662 // All four callback functions are optional and default to nil.
663 // The function returns nil on error, or the validated file name otherwise.
664 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
666 if(argc < 1 || !naIsString(args[0]))
667 naRuntimeError(c, "parsexml(): path argument missing or not a string");
668 if(argc > 5) argc = 5;
669 for(int i=1; i<argc; i++)
670 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
671 naRuntimeError(c, "parsexml(): callback argument not a function");
673 const char* file = fgValidatePath(naStr_data(args[0]), false);
675 naRuntimeError(c, "parsexml(): reading '%s' denied "
676 "(unauthorized access)", naStr_data(args[0]));
679 std::ifstream input(file);
680 NasalXMLVisitor visitor(c, argc, args);
682 readXML(input, visitor);
683 } catch (const sg_exception& e) {
684 naRuntimeError(c, "parsexml(): file '%s' %s",
685 file, e.getFormattedMessage().c_str());
688 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
691 // Return UNIX epoch time in seconds.
692 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
696 GetSystemTimeAsFileTime(&ft);
697 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
698 // Converts from 100ns units in 1601 epoch to unix epoch in sec
699 return naNum((t * 1e-7) - 11644473600.0);
702 gettimeofday(&td, 0);
703 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
707 // Table of extension functions. Terminate with zeros.
708 static struct { const char* name; naCFunction func; } funcs[] = {
709 { "getprop", f_getprop },
710 { "setprop", f_setprop },
711 { "print", f_print },
712 { "logprint", f_logprint },
713 { "_fgcommand", f_fgcommand },
714 { "settimer", f_settimer },
715 { "maketimer", f_makeTimer },
716 { "_setlistener", f_setlistener },
717 { "removelistener", f_removelistener },
718 { "addcommand", f_addCommand },
719 { "removecommand", f_removeCommand },
720 { "_cmdarg", f_cmdarg },
721 { "_interpolate", f_interpolate },
723 { "srand", f_srand },
724 { "abort", f_abort },
725 { "directory", f_directory },
726 { "resolvepath", f_resolveDataPath },
727 { "finddata", f_findDataDir },
728 { "parsexml", f_parsexml },
729 { "systime", f_systime },
733 naRef FGNasalSys::cmdArgGhost()
735 return propNodeGhost(_cmdArg);
738 void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
743 void FGNasalSys::init()
747 _context = naNewContext();
749 // Start with globals. Add it to itself as a recursive
750 // sub-reference under the name "globals". This gives client-code
751 // write access to the namespace if someone wants to do something
753 _globals = naInit_std(_context);
754 naSave(_context, _globals);
755 hashset(_globals, "globals", _globals);
757 hashset(_globals, "math", naInit_math(_context));
758 hashset(_globals, "bits", naInit_bits(_context));
759 hashset(_globals, "io", naInit_io(_context));
760 hashset(_globals, "thread", naInit_thread(_context));
761 hashset(_globals, "utf8", naInit_utf8(_context));
763 // Add our custom extension functions:
764 for(i=0; funcs[i].name; i++)
765 hashset(_globals, funcs[i].name,
766 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
768 // And our SGPropertyNode wrapper
769 hashset(_globals, "props", genPropsModule());
771 // Add string methods
772 _string = naInit_string(_context);
773 naSave(_context, _string);
774 initNasalString(_globals, _string, _context);
776 initNasalPositioned(_globals, _context);
777 initNasalPositioned_cppbind(_globals, _context);
778 NasalClipboard::init(this);
779 initNasalCanvas(_globals, _context);
780 initNasalCondition(_globals, _context);
782 NasalTimerObj::init("Timer")
783 .method("start", &TimerObj::start)
784 .method("stop", &TimerObj::stop)
785 .method("restart", &TimerObj::restart)
786 .member("singleShot", &TimerObj::isSingleShot, &TimerObj::setSingleShot)
787 .member("isRunning", &TimerObj::isRunning);
789 // Now load the various source files in the Nasal directory
790 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
791 loadScriptDirectory(nasalDir);
793 // Add modules in Nasal subdirectories to property tree
794 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
795 simgear::Dir::NO_DOT_OR_DOTDOT, "");
796 for (unsigned int i=0; i<directories.size(); ++i) {
797 simgear::Dir dir(directories[i]);
798 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
799 addModule(directories[i].file(), scripts);
802 // set signal and remove node to avoid restoring at reinit
803 const char *s = "nasal-dir-initialized";
804 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
805 signal->setBoolValue(s, true);
806 signal->removeChildren(s, false);
808 // Pull scripts out of the property tree, too
809 loadPropertyScripts();
811 // now Nasal modules are loaded, we can do some delayed work
812 postinitNasalPositioned(_globals, _context);
813 postinitNasalGUI(_globals, _context);
816 naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps)
818 static naRef wrapNodeFunc = naNil();
819 if (naIsNil(wrapNodeFunc)) {
820 nasal::Hash props = getGlobals().get<nasal::Hash>("props");
821 wrapNodeFunc = props.get("wrapNode");
825 args[0] = propNodeGhost(aProps);
826 return naCall(_context, wrapNodeFunc, 1, args, naNil(), naNil());
829 void FGNasalSys::update(double)
831 if( NasalClipboard::getInstance() )
832 NasalClipboard::getInstance()->update();
834 if(!_dead_listener.empty()) {
835 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
836 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
837 _dead_listener.clear();
840 if (!_loadList.empty())
845 // process Nasal load hook (only one per update loop to avoid excessive lags)
846 _loadList.pop()->load();
849 if (!_unloadList.empty())
851 // process pending Nasal unload hooks after _all_ load hooks were processed
852 // (only unload one per update loop to avoid excessive lags)
853 _unloadList.pop()->unload();
856 // The global context is a legacy thing. We use dynamically
857 // created contexts for naCall() now, so that we can call them
858 // recursively. But there are still spots that want to use it for
859 // naNew*() calls, which end up leaking memory because the context
860 // only clears out its temporary vector when it's *used*. So just
861 // junk it and fetch a new/reinitialized one every frame. This is
862 // clumsy: the right solution would use the dynamic context in all
863 // cases and eliminate _context entirely. But that's more work,
864 // and this works fine (yes, they say "New" and "Free", but
865 // they're very fast, just trust me). -Andy
866 naFreeContext(_context);
867 _context = naNewContext();
870 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
872 return p1.file() < p2.file();
875 // Loads all scripts in given directory
876 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
878 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
879 // Note: simgear::Dir already reports file entries in a deterministic order,
880 // so a fixed loading sequence is guaranteed (same for every user)
881 for (unsigned int i=0; i<scripts.size(); ++i) {
882 SGPath fullpath(scripts[i]);
883 SGPath file = fullpath.file();
884 loadModule(fullpath, file.base().c_str());
888 // Create module with list of scripts
889 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
891 if (! scripts.empty())
893 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
894 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
895 for (unsigned int i=0; i<scripts.size(); ++i) {
896 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
897 pFileNode->setStringValue(scripts[i].c_str());
899 if (!module_node->hasChild("enabled",0))
901 SGPropertyNode* node = module_node->getChild("enabled",0,true);
902 node->setBoolValue(true);
903 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
908 // Loads the scripts found under /nasal in the global tree
909 void FGNasalSys::loadPropertyScripts()
911 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
914 for(int i=0; i<nasal->nChildren(); i++)
916 SGPropertyNode* n = nasal->getChild(i);
917 loadPropertyScripts(n);
921 // Loads the scripts found under /nasal in the global tree
922 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
924 bool is_loaded = false;
926 const char* module = n->getName();
927 if(n->hasChild("module"))
928 module = n->getStringValue("module");
929 if (n->getBoolValue("enabled",true))
931 // allow multiple files to be specified within a single
935 bool file_specified = false;
937 while((fn = n->getChild("file", j)) != NULL) {
938 file_specified = true;
939 const char* file = fn->getStringValue();
941 if (!p.isAbsolute() || !p.exists())
943 p = globals->resolve_maybe_aircraft_path(file);
946 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
947 file << "' for module '" << module << "'.");
950 ok &= p.isNull() ? false : loadModule(p, module);
954 const char* src = n->getStringValue("script");
955 if(!n->hasChild("script")) src = 0; // Hrm...
957 createModule(module, n->getPath().c_str(), src, strlen(src));
959 if(!file_specified && !src)
961 // module no longer exists - clear the archived "enable" flag
962 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
963 SGPropertyNode* node = n->getChild("enabled",0,false);
965 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
967 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
968 "no <file> or <script> defined in " <<
969 "/nasal/" << module);
976 SGPropertyNode* enable = n->getChild("enabled");
979 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
980 enable->addChangeListener(listener, false);
983 SGPropertyNode* loaded = n->getChild("loaded",0,true);
984 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
985 loaded->setBoolValue(is_loaded);
988 // Logs a runtime error, with stack trace, to the FlightGear log stream
989 void FGNasalSys::logError(naContext context)
991 SG_LOG(SG_NASAL, SG_ALERT,
992 "Nasal runtime error: " << naGetError(context));
993 SG_LOG(SG_NASAL, SG_ALERT,
994 " at " << naStr_data(naGetSourceFile(context, 0)) <<
995 ", line " << naGetLine(context, 0));
996 for(int i=1; i<naStackDepth(context); i++)
997 SG_LOG(SG_NASAL, SG_ALERT,
998 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
999 ", line " << naGetLine(context, i));
1002 // Reads a script file, executes it, and places the resulting
1003 // namespace into the global namespace under the specified module
1005 bool FGNasalSys::loadModule(SGPath file, const char* module)
1008 char* buf = readfile(file.c_str(), &len);
1010 SG_LOG(SG_NASAL, SG_ALERT,
1011 "Nasal error: could not read script file " << file.c_str()
1012 << " into module " << module);
1016 bool ok = createModule(module, file.c_str(), buf, len);
1021 // Parse and run. Save the local variables namespace, as it will
1022 // become a sub-object of globals. The optional "arg" argument can be
1023 // used to pass an associated property node to the module, which can then
1024 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
1025 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1026 const char* src, int len,
1027 const SGPropertyNode* cmdarg,
1028 int argc, naRef* args)
1030 naRef code = parse(fileName, src, len);
1034 // See if we already have a module hash to use. This allows the
1035 // user to, for example, add functions to the built-in math
1036 // module. Make a new one if necessary.
1038 naRef modname = naNewString(_context);
1039 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1040 if(!naHash_get(_globals, modname, &locals))
1041 locals = naNewHash(_context);
1043 _cmdArg = (SGPropertyNode*)cmdarg;
1045 call(code, argc, args, locals);
1046 hashset(_globals, moduleName, locals);
1050 void FGNasalSys::deleteModule(const char* moduleName)
1052 naRef modname = naNewString(_context);
1053 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1054 naHash_delete(_globals, modname);
1057 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
1060 naRef srcfile = naNewString(_context);
1061 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1062 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
1064 SG_LOG(SG_NASAL, SG_ALERT,
1065 "Nasal parse error: " << naGetError(_context) <<
1066 " in "<< filename <<", line " << errLine);
1070 // Bind to the global namespace before returning
1071 return naBindFunction(_context, code, _globals);
1074 bool FGNasalSys::handleCommand( const char* moduleName,
1075 const char* fileName,
1077 const SGPropertyNode* arg )
1079 naRef code = parse(fileName, src, strlen(src));
1080 if(naIsNil(code)) return false;
1082 // Commands can be run "in" a module. Make sure that module
1083 // exists, and set it up as the local variables hash for the
1085 naRef locals = naNil();
1087 naRef modname = naNewString(_context);
1088 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1089 if(!naHash_get(_globals, modname, &locals)) {
1090 locals = naNewHash(_context);
1091 naHash_set(_globals, modname, locals);
1095 // Cache this command's argument for inspection via cmdarg(). For
1096 // performance reasons, we won't bother with it if the invoked
1097 // code doesn't need it.
1098 _cmdArg = (SGPropertyNode*)arg;
1100 call(code, 0, 0, locals);
1104 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1106 const char* src = arg->getStringValue("script");
1107 const char* moduleName = arg->getStringValue("module");
1109 return handleCommand( moduleName,
1110 arg ? arg->getPath(true).c_str() : moduleName,
1115 // settimer(func, dt, simtime) extension function. The first argument
1116 // is a Nasal function to call, the second is a delta time (from now),
1117 // in seconds. The third, if present, is a boolean value indicating
1118 // that "real world" time (rather than simulator time) is to be used.
1120 // Implementation note: the FGTimer objects don't live inside the
1121 // garbage collector, so the Nasal handler functions have to be
1122 // "saved" somehow lest they be inadvertently cleaned. In this case,
1123 // they are inserted into a globals.__gcsave hash and removed on
1125 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1127 // Extract the handler, delta, and simtime arguments:
1128 naRef handler = argc > 0 ? args[0] : naNil();
1129 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1130 naRuntimeError(c, "settimer() with invalid function argument");
1134 naRef delta = argc > 1 ? args[1] : naNil();
1135 if(naIsNil(delta)) {
1136 naRuntimeError(c, "settimer() with invalid time argument");
1140 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1142 // Generate and register a C++ timer handler
1143 NasalTimer* t = new NasalTimer;
1144 t->handler = handler;
1145 t->gcKey = gcSave(handler);
1148 globals->get_event_mgr()->addEvent("NasalTimer",
1149 t, &NasalTimer::timerExpired,
1150 delta.num, simtime);
1153 void FGNasalSys::handleTimer(NasalTimer* t)
1155 call(t->handler, 0, 0, naNil());
1156 gcRelease(t->gcKey);
1159 int FGNasalSys::gcSave(naRef r)
1164 void FGNasalSys::gcRelease(int key)
1169 void FGNasalSys::NasalTimer::timerExpired()
1171 nasal->handleTimer(this);
1175 int FGNasalSys::_listenerId = 0;
1177 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1178 // Attaches a callback function to a property (specified as a global
1179 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1180 // optional argument (default=0) is set to 1, then the function is also
1181 // called initially. If the fourth, optional argument is set to 0, then the
1182 // function is only called when the property node value actually changes.
1183 // Otherwise it's called independent of the value whenever the node is
1184 // written to (default). The setlistener() function returns a unique
1185 // id number, which is to be used as argument to the removelistener()
1187 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1189 SGPropertyNode_ptr node;
1190 naRef prop = argc > 0 ? args[0] : naNil();
1191 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1192 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1194 naRuntimeError(c, "setlistener() with invalid property argument");
1199 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1202 naRef code = argc > 1 ? args[1] : naNil();
1203 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1204 naRuntimeError(c, "setlistener() with invalid function argument");
1208 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1209 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1210 FGNasalListener *nl = new FGNasalListener(node, code, this,
1211 gcSave(code), _listenerId, init, type);
1213 node->addChangeListener(nl, init != 0);
1215 _listener[_listenerId] = nl;
1216 return naNum(_listenerId++);
1219 // removelistener(int) extension function. The argument is the id of
1220 // a listener as returned by the setlistener() function.
1221 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1223 naRef id = argc > 0 ? args[0] : naNil();
1224 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1226 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1227 naRuntimeError(c, "removelistener() with invalid listener id");
1231 it->second->_dead = true;
1232 _dead_listener.push_back(it->second);
1233 _listener.erase(it);
1234 return naNum(_listener.size());
1237 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1239 if( _loadList.empty() )
1241 _loadList.push(data);
1244 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1246 _unloadList.push(data);
1249 //////////////////////////////////////////////////////////////////////////
1250 // FGNasalListener class.
1252 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1253 FGNasalSys* nasal, int key, int id,
1254 int init, int type) :
1267 if(_type == 0 && !_init)
1271 FGNasalListener::~FGNasalListener()
1273 _node->removeChangeListener(this);
1274 _nas->gcRelease(_gcKey);
1277 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1279 if(_active || _dead) return;
1282 arg[0] = _nas->propNodeGhost(which);
1283 arg[1] = _nas->propNodeGhost(_node);
1284 arg[2] = mode; // value changed, child added/removed
1285 arg[3] = naNum(_node != which); // child event?
1286 _nas->call(_code, 4, arg, naNil());
1290 void FGNasalListener::valueChanged(SGPropertyNode* node)
1292 if(_type < 2 && node != _node) return; // skip child events
1293 if(_type > 0 || changed(_node) || _init)
1294 call(node, naNum(0));
1299 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1301 if(_type == 2) call(child, naNum(1));
1304 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1306 if(_type == 2) call(child, naNum(-1));
1309 bool FGNasalListener::changed(SGPropertyNode* node)
1311 using namespace simgear;
1312 props::Type type = node->getType();
1313 if(type == props::NONE) return false;
1314 if(type == props::UNSPECIFIED) return true;
1322 long l = node->getLongValue();
1323 result = l != _last_int;
1330 double d = node->getDoubleValue();
1331 result = d != _last_float;
1337 string s = node->getStringValue();
1338 result = s != _last_string;
1345 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1347 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1348 _c(naSubContext(c)),
1349 _start_element(argc > 1 ? args[1] : naNil()),
1350 _end_element(argc > 2 ? args[2] : naNil()),
1351 _data(argc > 3 ? args[3] : naNil()),
1352 _pi(argc > 4 ? args[4] : naNil())
1356 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1358 if(naIsNil(_start_element)) return;
1359 naRef attr = naNewHash(_c);
1360 for(int i=0; i<a.size(); i++) {
1361 naRef name = make_string(a.getName(i));
1362 naRef value = make_string(a.getValue(i));
1363 naHash_set(attr, name, value);
1365 call(_start_element, 2, make_string(tag), attr);
1368 void NasalXMLVisitor::endElement(const char* tag)
1370 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1373 void NasalXMLVisitor::data(const char* str, int len)
1375 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1378 void NasalXMLVisitor::pi(const char* target, const char* data)
1380 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1383 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1388 naCall(_c, func, num, args, naNil(), naNil());
1393 naRef NasalXMLVisitor::make_string(const char* s, int n)
1395 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1396 n < 0 ? strlen(s) : n);