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/misc/interpolator.hxx>
27 #include <simgear/structure/commands.hxx>
28 #include <simgear/math/sg_geodesy.hxx>
29 #include <simgear/structure/event_mgr.hxx>
30 #include <simgear/debug/BufferedLogCallback.hxx>
31 #include <simgear/nasal/cppbind/NasalHash.hxx>
33 #include "NasalSys.hxx"
34 #include "NasalSys_private.hxx"
35 #include "NasalModelData.hxx"
36 #include "NasalPositioned.hxx"
37 #include "NasalCanvas.hxx"
38 #include "NasalClipboard.hxx"
39 #include "NasalCondition.hxx"
40 #include "NasalString.hxx"
42 #include <Main/globals.hxx>
43 #include <Main/util.hxx>
44 #include <Main/fg_props.hxx>
49 void postinitNasalGUI(naRef globals, naContext c);
51 static FGNasalSys* nasalSys = 0;
53 // Listener class for loading Nasal modules on demand
54 class FGNasalModuleListener : public SGPropertyChangeListener
57 FGNasalModuleListener(SGPropertyNode* node);
59 virtual void valueChanged(SGPropertyNode* node);
62 SGPropertyNode_ptr _node;
65 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
69 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
71 if (_node->getBoolValue("enabled",false)&&
72 !_node->getBoolValue("loaded",true))
74 nasalSys->loadPropertyScripts(_node);
79 // Read and return file contents in a single buffer. Note use of
80 // stat() to get the file size. This is a win32 function, believe it
81 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
82 // Text mode brain damage will kill us if we're trying to do bytewise
84 static char* readfile(const char* file, int* lenOut)
87 if(stat(file, &data) != 0) return 0;
88 FILE* f = fopen(file, "rb");
90 char* buf = new char[data.st_size];
91 *lenOut = fread(buf, 1, data.st_size, f);
93 if(*lenOut != data.st_size) {
94 // Shouldn't happen, but warn anyway since it represents a
95 // platform bug and not a typical runtime error (missing file,
97 SG_LOG(SG_NASAL, SG_ALERT,
98 "ERROR in Nasal initialization: " <<
99 "short count returned from fread() of " << file <<
100 ". Check your C library!");
107 FGNasalSys::FGNasalSys()
114 _nextGCKey = 0; // Any value will do
117 _log = new simgear::BufferedLogCallback(SG_NASAL, SG_INFO);
118 _log->truncateAt(255);
119 sglog().addCallback(_log);
122 // Utility. Sets a named key in a hash by C string, rather than nasal
124 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
126 naRef s = naNewString(_context);
127 naStr_fromdata(s, (char*)key, strlen(key));
128 naHash_set(hash, s, val);
131 void FGNasalSys::globalsSet(const char* key, naRef val)
133 hashset(_globals, key, val);
136 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
138 return callMethod(code, naNil(), argc, args, locals);
141 // Does a naCall() in a new context. Wrapped here to make lock
142 // tracking easier. Extension functions are called with the lock, but
143 // we have to release it before making a new naCall(). So rather than
144 // drop the lock in every extension function that might call back into
145 // Nasal, we keep a stack depth counter here and only unlock/lock
146 // around the naCall if it isn't the first one.
148 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
150 naContext ctx = naNewContext();
151 if(_callCount) naModUnlock();
153 naRef result = naCall(ctx, code, argc, args, self, locals);
157 if(_callCount) naModLock();
162 FGNasalSys::~FGNasalSys()
165 map<int, FGNasalListener *>::iterator it, end = _listener.end();
166 for(it = _listener.begin(); it != end; ++it)
169 naFreeContext(_context);
174 bool FGNasalSys::parseAndRun(const char* sourceCode)
176 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
180 call(code, 0, 0, naNil());
185 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
187 FGNasalScript* script = new FGNasalScript();
188 script->_gcKey = -1; // important, if we delete it on a parse
189 script->_nas = this; // error, don't clobber a real handle!
193 sprintf(buf, "FGNasalScript@%p", (void *)script);
197 script->_code = parse(name, src, strlen(src));
198 if(naIsNil(script->_code)) {
203 script->_gcKey = gcSave(script->_code);
208 // The get/setprop functions accept a *list* of strings and walk
209 // through the property tree with them to find the appropriate node.
210 // This allows a Nasal object to hold onto a property path and use it
211 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
212 // is the utility function that walks the property tree.
213 // Future enhancement: support integer arguments to specify array
215 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
217 SGPropertyNode* p = globals->get_props();
219 for(int i=0; i<len; i++) {
221 if(!naIsString(a)) return 0;
222 p = p->getNode(naStr_data(a));
225 } catch (const string& err) {
226 naRuntimeError(c, (char *)err.c_str());
232 // getprop() extension function. Concatenates its string arguments as
233 // property names and returns the value of the specified property. Or
234 // nil if it doesn't exist.
235 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
237 using namespace simgear;
238 const SGPropertyNode* p = findnode(c, args, argc);
239 if(!p) return naNil();
241 switch(p->getType()) {
242 case props::BOOL: case props::INT:
243 case props::LONG: case props::FLOAT:
246 double dv = p->getDoubleValue();
247 if (SGMisc<double>::isNaN(dv)) {
248 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
256 case props::UNSPECIFIED:
258 naRef nastr = naNewString(c);
259 const char* val = p->getStringValue();
260 naStr_fromdata(nastr, (char*)val, strlen(val));
263 case props::ALIAS: // <--- FIXME, recurse?
269 // setprop() extension function. Concatenates its string arguments as
270 // property names and sets the value of the specified property to the
272 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
275 char buf[BUFLEN + 1];
279 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
280 for(int i=0; i<argc-1; i++) {
281 naRef s = naStringValue(c, args[i]);
282 if(naIsNil(s)) return naNil();
283 strncpy(p, naStr_data(s), buflen);
285 buflen = BUFLEN - (p - buf);
286 if(i < (argc-2) && buflen > 0) {
292 SGPropertyNode* props = globals->get_props();
293 naRef val = args[argc-1];
296 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
298 naRef n = naNumValue(val);
300 naRuntimeError(c, "setprop() value is not string or number");
302 if (SGMisc<double>::isNaN(n.num)) {
303 naRuntimeError(c, "setprop() passed a NaN");
306 result = props->setDoubleValue(buf, n.num);
308 } catch (const string& err) {
309 naRuntimeError(c, (char *)err.c_str());
311 return naNum(result);
315 // print() extension function. Concatenates and prints its arguments
316 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
317 // make sure it appears. Is there better way to do this?
318 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
322 for(int i=0; i<n; i++) {
323 naRef s = naStringValue(c, args[i]);
324 if(naIsNil(s)) continue;
325 buf += naStr_data(s);
327 SG_LOG(SG_NASAL, SG_ALERT, buf);
328 return naNum(buf.length());
331 // logprint() extension function. Same as above, all arguments after the
332 // first argument are concatenated. Argument 0 is the log-level, matching
334 static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
337 naRuntimeError(c, "no prioirty argument to logprint()");
339 naRef priority = args[0];
342 for(int i=1; i<n; i++) {
343 naRef s = naStringValue(c, args[i]);
344 if(naIsNil(s)) continue;
345 buf += naStr_data(s);
347 // use the nasal source file and line for the message location, since
348 // that's more useful than the location here!
349 sglog().log(SG_NASAL, (sgDebugPriority)(int) priority.num,
350 naStr_data(naGetSourceFile(c, 0)),
351 naGetLine(c, 0), buf);
352 return naNum(buf.length());
356 // fgcommand() extension function. Executes a named command via the
357 // FlightGear command manager. Takes a single property node name as
359 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
361 naRef cmd = argc > 0 ? args[0] : naNil();
362 naRef props = argc > 1 ? args[1] : naNil();
363 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
364 naRuntimeError(c, "bad arguments to fgcommand()");
365 SGPropertyNode_ptr tmp, *node;
367 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
369 tmp = new SGPropertyNode();
372 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
375 // settimer(func, dt, simtime) extension function. Falls through to
376 // FGNasalSys::setTimer(). See there for docs.
377 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
379 nasalSys->setTimer(c, argc, args);
383 // setlistener(func, property, bool) extension function. Falls through to
384 // FGNasalSys::setListener(). See there for docs.
385 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
387 return nasalSys->setListener(c, argc, args);
390 // removelistener(int) extension function. Falls through to
391 // FGNasalSys::removeListener(). See there for docs.
392 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
394 return nasalSys->removeListener(c, argc, args);
397 // Returns a ghost handle to the argument to the currently executing
399 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
401 return nasalSys->cmdArgGhost();
404 // Sets up a property interpolation. The first argument is either a
405 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
406 // interpolate. The second argument is a vector of pairs of
407 // value/delta numbers.
408 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
410 SGPropertyNode* node;
411 naRef prop = argc > 0 ? args[0] : naNil();
412 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
413 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
416 naRef curve = argc > 1 ? args[1] : naNil();
417 if(!naIsVector(curve)) return naNil();
418 int nPoints = naVec_size(curve) / 2;
419 double* values = new double[nPoints];
420 double* deltas = new double[nPoints];
421 for(int i=0; i<nPoints; i++) {
422 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
423 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
426 ((SGInterpolator*)globals->get_subsystem_mgr()
427 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
428 ->interpolate(node, nPoints, values, deltas);
435 // This is a better RNG than the one in the default Nasal distribution
436 // (which is based on the C library rand() implementation). It will
438 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
440 return naNum(sg_random());
443 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
449 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
455 // Return an array listing of all files in a directory
456 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
458 if(argc != 1 || !naIsString(args[0]))
459 naRuntimeError(c, "bad arguments to directory()");
461 simgear::Dir d(SGPath(naStr_data(args[0])));
462 if(!d.exists()) return naNil();
463 naRef result = naNewVector(c);
465 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
466 for (unsigned int i=0; i<paths.size(); ++i) {
467 std::string p = paths[i].file();
468 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
475 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
477 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
479 if(argc != 1 || !naIsString(args[0]))
480 naRuntimeError(c, "bad arguments to resolveDataPath()");
482 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
483 const char* pdata = p.c_str();
484 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
487 class NasalCommand : public SGCommandMgr::Command
490 NasalCommand(FGNasalSys* sys, naRef f) :
494 _gcRoot = sys->gcSave(f);
497 virtual ~NasalCommand()
499 _sys->gcRelease(_gcRoot);
502 virtual bool operator()(const SGPropertyNode* aNode)
504 _sys->setCmdArg(const_cast<SGPropertyNode*>(aNode));
506 args[0] = _sys->wrappedPropsNode(const_cast<SGPropertyNode*>(aNode));
508 _sys->callMethod(_func, naNil(), 1, args, naNil() /* locals */);
519 static naRef f_addCommand(naContext c, naRef me, int argc, naRef* args)
521 if(argc != 2 || !naIsString(args[0]) || !naIsFunc(args[1]))
522 naRuntimeError(c, "bad arguments to addcommand()");
524 naRef func = args[1];
525 NasalCommand* cmd = new NasalCommand(nasalSys, func);
526 globals->get_commands()->addCommandObject(naStr_data(args[0]), cmd);
530 static naRef f_removeCommand(naContext c, naRef me, int argc, naRef* args)
532 SGCommandMgr::Command* cmd = globals->get_commands()->getCommand(naStr_data(args[0]));
534 // SGCommandMgr::Command* cmd = globals->get_commands()->removeCommand(naStr_data(args[0]))
542 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
544 // <path> ... absolute path to an XML file
545 // <start-tag> ... callback function with two args: tag name, attribute hash
546 // <end-tag> ... callback function with one arg: tag name
547 // <data> ... callback function with one arg: data
548 // <pi> ... callback function with two args: target, data
549 // (pi = "processing instruction")
550 // All four callback functions are optional and default to nil.
551 // The function returns nil on error, or the validated file name otherwise.
552 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
554 if(argc < 1 || !naIsString(args[0]))
555 naRuntimeError(c, "parsexml(): path argument missing or not a string");
556 if(argc > 5) argc = 5;
557 for(int i=1; i<argc; i++)
558 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
559 naRuntimeError(c, "parsexml(): callback argument not a function");
561 const char* file = fgValidatePath(naStr_data(args[0]), false);
563 naRuntimeError(c, "parsexml(): reading '%s' denied "
564 "(unauthorized access)", naStr_data(args[0]));
567 std::ifstream input(file);
568 NasalXMLVisitor visitor(c, argc, args);
570 readXML(input, visitor);
571 } catch (const sg_exception& e) {
572 naRuntimeError(c, "parsexml(): file '%s' %s",
573 file, e.getFormattedMessage().c_str());
576 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
579 // Return UNIX epoch time in seconds.
580 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
584 GetSystemTimeAsFileTime(&ft);
585 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
586 // Converts from 100ns units in 1601 epoch to unix epoch in sec
587 return naNum((t * 1e-7) - 11644473600.0);
590 gettimeofday(&td, 0);
591 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
595 // Table of extension functions. Terminate with zeros.
596 static struct { const char* name; naCFunction func; } funcs[] = {
597 { "getprop", f_getprop },
598 { "setprop", f_setprop },
599 { "print", f_print },
600 { "logprint", f_logprint },
601 { "_fgcommand", f_fgcommand },
602 { "settimer", f_settimer },
603 { "_setlistener", f_setlistener },
604 { "removelistener", f_removelistener },
605 { "addcommand", f_addCommand },
606 { "removecommand", f_removeCommand },
607 { "_cmdarg", f_cmdarg },
608 { "_interpolate", f_interpolate },
610 { "srand", f_srand },
611 { "abort", f_abort },
612 { "directory", f_directory },
613 { "resolvepath", f_resolveDataPath },
614 { "parsexml", f_parsexml },
615 { "systime", f_systime },
619 naRef FGNasalSys::cmdArgGhost()
621 return propNodeGhost(_cmdArg);
624 void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
629 void FGNasalSys::init()
633 _context = naNewContext();
635 // Start with globals. Add it to itself as a recursive
636 // sub-reference under the name "globals". This gives client-code
637 // write access to the namespace if someone wants to do something
639 _globals = naInit_std(_context);
640 naSave(_context, _globals);
641 hashset(_globals, "globals", _globals);
643 hashset(_globals, "math", naInit_math(_context));
644 hashset(_globals, "bits", naInit_bits(_context));
645 hashset(_globals, "io", naInit_io(_context));
646 hashset(_globals, "thread", naInit_thread(_context));
647 hashset(_globals, "utf8", naInit_utf8(_context));
649 // Add our custom extension functions:
650 for(i=0; funcs[i].name; i++)
651 hashset(_globals, funcs[i].name,
652 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
654 // And our SGPropertyNode wrapper
655 hashset(_globals, "props", genPropsModule());
657 // Make a "__gcsave" hash to hold the naRef objects which get
658 // passed to handles outside the interpreter (to protect them from
659 // begin garbage-collected).
660 _gcHash = naNewHash(_context);
661 hashset(_globals, "__gcsave", _gcHash);
663 // Add string methods
664 _string = naInit_string(_context);
665 naSave(_context, _string);
666 initNasalString(_globals, _string, _context, _gcHash);
668 initNasalPositioned(_globals, _context, _gcHash);
669 initNasalPositioned_cppbind(_globals, _context, _gcHash);
670 NasalClipboard::init(this);
671 initNasalCanvas(_globals, _context, _gcHash);
672 initNasalCondition(_globals, _context, _gcHash);
674 // Now load the various source files in the Nasal directory
675 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
676 loadScriptDirectory(nasalDir);
678 // Add modules in Nasal subdirectories to property tree
679 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
680 simgear::Dir::NO_DOT_OR_DOTDOT, "");
681 for (unsigned int i=0; i<directories.size(); ++i) {
682 simgear::Dir dir(directories[i]);
683 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
684 addModule(directories[i].file(), scripts);
687 // set signal and remove node to avoid restoring at reinit
688 const char *s = "nasal-dir-initialized";
689 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
690 signal->setBoolValue(s, true);
691 signal->removeChildren(s, false);
693 // Pull scripts out of the property tree, too
694 loadPropertyScripts();
696 // now Nasal modules are loaded, we can do some delayed work
697 postinitNasalPositioned(_globals, _context);
698 postinitNasalGUI(_globals, _context);
701 naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps)
703 static naRef wrapNodeFunc = naNil();
704 if (naIsNil(wrapNodeFunc)) {
705 nasal::Hash g(_globals, _context);
706 nasal::Hash props = g.get<nasal::Hash>("props");
707 wrapNodeFunc = props.get("wrapNode");
711 args[0] = propNodeGhost(aProps);
712 return naCall(_context, wrapNodeFunc, 1, args, naNil(), naNil());
715 void FGNasalSys::update(double)
717 if( NasalClipboard::getInstance() )
718 NasalClipboard::getInstance()->update();
720 if(!_dead_listener.empty()) {
721 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
722 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
723 _dead_listener.clear();
726 if (!_loadList.empty())
728 // process Nasal load hook (only one per update loop to avoid excessive lags)
729 _loadList.pop()->load();
732 if (!_unloadList.empty())
734 // process pending Nasal unload hooks after _all_ load hooks were processed
735 // (only unload one per update loop to avoid excessive lags)
736 _unloadList.pop()->unload();
739 // The global context is a legacy thing. We use dynamically
740 // created contexts for naCall() now, so that we can call them
741 // recursively. But there are still spots that want to use it for
742 // naNew*() calls, which end up leaking memory because the context
743 // only clears out its temporary vector when it's *used*. So just
744 // junk it and fetch a new/reinitialized one every frame. This is
745 // clumsy: the right solution would use the dynamic context in all
746 // cases and eliminate _context entirely. But that's more work,
747 // and this works fine (yes, they say "New" and "Free", but
748 // they're very fast, just trust me). -Andy
749 naFreeContext(_context);
750 _context = naNewContext();
753 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
755 return p1.file() < p2.file();
758 // Loads all scripts in given directory
759 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
761 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
762 // Note: simgear::Dir already reports file entries in a deterministic order,
763 // so a fixed loading sequence is guaranteed (same for every user)
764 for (unsigned int i=0; i<scripts.size(); ++i) {
765 SGPath fullpath(scripts[i]);
766 SGPath file = fullpath.file();
767 loadModule(fullpath, file.base().c_str());
771 // Create module with list of scripts
772 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
774 if (scripts.size()>0)
776 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
777 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
778 for (unsigned int i=0; i<scripts.size(); ++i) {
779 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
780 pFileNode->setStringValue(scripts[i].c_str());
782 if (!module_node->hasChild("enabled",0))
784 SGPropertyNode* node = module_node->getChild("enabled",0,true);
785 node->setBoolValue(true);
786 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
791 // Loads the scripts found under /nasal in the global tree
792 void FGNasalSys::loadPropertyScripts()
794 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
797 for(int i=0; i<nasal->nChildren(); i++)
799 SGPropertyNode* n = nasal->getChild(i);
800 loadPropertyScripts(n);
804 // Loads the scripts found under /nasal in the global tree
805 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
807 bool is_loaded = false;
809 const char* module = n->getName();
810 if(n->hasChild("module"))
811 module = n->getStringValue("module");
812 if (n->getBoolValue("enabled",true))
814 // allow multiple files to be specified within a single
818 bool file_specified = false;
820 while((fn = n->getChild("file", j)) != NULL) {
821 file_specified = true;
822 const char* file = fn->getStringValue();
824 if (!p.isAbsolute() || !p.exists())
826 p = globals->resolve_maybe_aircraft_path(file);
829 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
830 file << "' for module '" << module << "'.");
833 ok &= p.isNull() ? false : loadModule(p, module);
837 const char* src = n->getStringValue("script");
838 if(!n->hasChild("script")) src = 0; // Hrm...
840 createModule(module, n->getPath().c_str(), src, strlen(src));
842 if(!file_specified && !src)
844 // module no longer exists - clear the archived "enable" flag
845 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
846 SGPropertyNode* node = n->getChild("enabled",0,false);
848 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
850 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
851 "no <file> or <script> defined in " <<
852 "/nasal/" << module);
859 SGPropertyNode* enable = n->getChild("enabled");
862 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
863 enable->addChangeListener(listener, false);
866 SGPropertyNode* loaded = n->getChild("loaded",0,true);
867 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
868 loaded->setBoolValue(is_loaded);
871 // Logs a runtime error, with stack trace, to the FlightGear log stream
872 void FGNasalSys::logError(naContext context)
874 SG_LOG(SG_NASAL, SG_ALERT,
875 "Nasal runtime error: " << naGetError(context));
876 SG_LOG(SG_NASAL, SG_ALERT,
877 " at " << naStr_data(naGetSourceFile(context, 0)) <<
878 ", line " << naGetLine(context, 0));
879 for(int i=1; i<naStackDepth(context); i++)
880 SG_LOG(SG_NASAL, SG_ALERT,
881 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
882 ", line " << naGetLine(context, i));
885 // Reads a script file, executes it, and places the resulting
886 // namespace into the global namespace under the specified module
888 bool FGNasalSys::loadModule(SGPath file, const char* module)
891 char* buf = readfile(file.c_str(), &len);
893 SG_LOG(SG_NASAL, SG_ALERT,
894 "Nasal error: could not read script file " << file.c_str()
895 << " into module " << module);
899 bool ok = createModule(module, file.c_str(), buf, len);
904 // Parse and run. Save the local variables namespace, as it will
905 // become a sub-object of globals. The optional "arg" argument can be
906 // used to pass an associated property node to the module, which can then
907 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
908 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
909 const char* src, int len,
910 const SGPropertyNode* cmdarg,
911 int argc, naRef* args)
913 naRef code = parse(fileName, src, len);
917 // See if we already have a module hash to use. This allows the
918 // user to, for example, add functions to the built-in math
919 // module. Make a new one if necessary.
921 naRef modname = naNewString(_context);
922 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
923 if(!naHash_get(_globals, modname, &locals))
924 locals = naNewHash(_context);
926 _cmdArg = (SGPropertyNode*)cmdarg;
928 call(code, argc, args, locals);
929 hashset(_globals, moduleName, locals);
933 void FGNasalSys::deleteModule(const char* moduleName)
935 naRef modname = naNewString(_context);
936 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
937 naHash_delete(_globals, modname);
940 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
943 naRef srcfile = naNewString(_context);
944 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
945 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
947 SG_LOG(SG_NASAL, SG_ALERT,
948 "Nasal parse error: " << naGetError(_context) <<
949 " in "<< filename <<", line " << errLine);
953 // Bind to the global namespace before returning
954 return naBindFunction(_context, code, _globals);
957 bool FGNasalSys::handleCommand( const char* moduleName,
958 const char* fileName,
960 const SGPropertyNode* arg )
962 naRef code = parse(fileName, src, strlen(src));
963 if(naIsNil(code)) return false;
965 // Commands can be run "in" a module. Make sure that module
966 // exists, and set it up as the local variables hash for the
968 naRef locals = naNil();
970 naRef modname = naNewString(_context);
971 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
972 if(!naHash_get(_globals, modname, &locals)) {
973 locals = naNewHash(_context);
974 naHash_set(_globals, modname, locals);
978 // Cache this command's argument for inspection via cmdarg(). For
979 // performance reasons, we won't bother with it if the invoked
980 // code doesn't need it.
981 _cmdArg = (SGPropertyNode*)arg;
983 call(code, 0, 0, locals);
987 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
989 const char* src = arg->getStringValue("script");
990 const char* moduleName = arg->getStringValue("module");
992 return handleCommand( moduleName,
993 arg ? arg->getPath(true).c_str() : moduleName,
998 // settimer(func, dt, simtime) extension function. The first argument
999 // is a Nasal function to call, the second is a delta time (from now),
1000 // in seconds. The third, if present, is a boolean value indicating
1001 // that "real world" time (rather than simulator time) is to be used.
1003 // Implementation note: the FGTimer objects don't live inside the
1004 // garbage collector, so the Nasal handler functions have to be
1005 // "saved" somehow lest they be inadvertently cleaned. In this case,
1006 // they are inserted into a globals.__gcsave hash and removed on
1008 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1010 // Extract the handler, delta, and simtime arguments:
1011 naRef handler = argc > 0 ? args[0] : naNil();
1012 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1013 naRuntimeError(c, "settimer() with invalid function argument");
1017 naRef delta = argc > 1 ? args[1] : naNil();
1018 if(naIsNil(delta)) {
1019 naRuntimeError(c, "settimer() with invalid time argument");
1023 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1025 // Generate and register a C++ timer handler
1026 NasalTimer* t = new NasalTimer;
1027 t->handler = handler;
1028 t->gcKey = gcSave(handler);
1031 globals->get_event_mgr()->addEvent("NasalTimer",
1032 t, &NasalTimer::timerExpired,
1033 delta.num, simtime);
1036 void FGNasalSys::handleTimer(NasalTimer* t)
1038 call(t->handler, 0, 0, naNil());
1039 gcRelease(t->gcKey);
1042 int FGNasalSys::gcSave(naRef r)
1044 int key = _nextGCKey++;
1045 naHash_set(_gcHash, naNum(key), r);
1049 void FGNasalSys::gcRelease(int key)
1051 naHash_delete(_gcHash, naNum(key));
1054 void FGNasalSys::NasalTimer::timerExpired()
1056 nasal->handleTimer(this);
1060 int FGNasalSys::_listenerId = 0;
1062 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1063 // Attaches a callback function to a property (specified as a global
1064 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1065 // optional argument (default=0) is set to 1, then the function is also
1066 // called initially. If the fourth, optional argument is set to 0, then the
1067 // function is only called when the property node value actually changes.
1068 // Otherwise it's called independent of the value whenever the node is
1069 // written to (default). The setlistener() function returns a unique
1070 // id number, which is to be used as argument to the removelistener()
1072 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1074 SGPropertyNode_ptr node;
1075 naRef prop = argc > 0 ? args[0] : naNil();
1076 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1077 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1079 naRuntimeError(c, "setlistener() with invalid property argument");
1084 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1087 naRef code = argc > 1 ? args[1] : naNil();
1088 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1089 naRuntimeError(c, "setlistener() with invalid function argument");
1093 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1094 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1095 FGNasalListener *nl = new FGNasalListener(node, code, this,
1096 gcSave(code), _listenerId, init, type);
1098 node->addChangeListener(nl, init != 0);
1100 _listener[_listenerId] = nl;
1101 return naNum(_listenerId++);
1104 // removelistener(int) extension function. The argument is the id of
1105 // a listener as returned by the setlistener() function.
1106 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1108 naRef id = argc > 0 ? args[0] : naNil();
1109 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1111 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1112 naRuntimeError(c, "removelistener() with invalid listener id");
1116 it->second->_dead = true;
1117 _dead_listener.push_back(it->second);
1118 _listener.erase(it);
1119 return naNum(_listener.size());
1122 void FGNasalSys::registerToLoad(FGNasalModelData *data)
1124 _loadList.push(data);
1127 void FGNasalSys::registerToUnload(FGNasalModelData *data)
1129 _unloadList.push(data);
1133 // FGNasalListener class.
1135 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1136 FGNasalSys* nasal, int key, int id,
1137 int init, int type) :
1150 if(_type == 0 && !_init)
1154 FGNasalListener::~FGNasalListener()
1156 _node->removeChangeListener(this);
1157 _nas->gcRelease(_gcKey);
1160 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1162 if(_active || _dead) return;
1163 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1166 arg[0] = _nas->propNodeGhost(which);
1167 arg[1] = _nas->propNodeGhost(_node);
1168 arg[2] = mode; // value changed, child added/removed
1169 arg[3] = naNum(_node != which); // child event?
1170 _nas->call(_code, 4, arg, naNil());
1174 void FGNasalListener::valueChanged(SGPropertyNode* node)
1176 if(_type < 2 && node != _node) return; // skip child events
1177 if(_type > 0 || changed(_node) || _init)
1178 call(node, naNum(0));
1183 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1185 if(_type == 2) call(child, naNum(1));
1188 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1190 if(_type == 2) call(child, naNum(-1));
1193 bool FGNasalListener::changed(SGPropertyNode* node)
1195 using namespace simgear;
1196 props::Type type = node->getType();
1197 if(type == props::NONE) return false;
1198 if(type == props::UNSPECIFIED) return true;
1206 long l = node->getLongValue();
1207 result = l != _last_int;
1214 double d = node->getDoubleValue();
1215 result = d != _last_float;
1221 string s = node->getStringValue();
1222 result = s != _last_string;
1229 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1231 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1232 _c(naSubContext(c)),
1233 _start_element(argc > 1 ? args[1] : naNil()),
1234 _end_element(argc > 2 ? args[2] : naNil()),
1235 _data(argc > 3 ? args[3] : naNil()),
1236 _pi(argc > 4 ? args[4] : naNil())
1240 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1242 if(naIsNil(_start_element)) return;
1243 naRef attr = naNewHash(_c);
1244 for(int i=0; i<a.size(); i++) {
1245 naRef name = make_string(a.getName(i));
1246 naRef value = make_string(a.getValue(i));
1247 naHash_set(attr, name, value);
1249 call(_start_element, 2, make_string(tag), attr);
1252 void NasalXMLVisitor::endElement(const char* tag)
1254 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1257 void NasalXMLVisitor::data(const char* str, int len)
1259 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1262 void NasalXMLVisitor::pi(const char* target, const char* data)
1264 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1267 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1272 naCall(_c, func, num, args, naNil(), naNil());
1277 naRef NasalXMLVisitor::make_string(const char* s, int n)
1279 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1280 n < 0 ? strlen(s) : n);