7 # include <sys/time.h> // gettimeofday
12 #include <sys/types.h>
17 #include <simgear/nasal/nasal.h>
18 #include <simgear/props/props.hxx>
19 #include <simgear/math/sg_random.h>
20 #include <simgear/misc/sg_path.hxx>
21 #include <simgear/misc/sg_dir.hxx>
22 #include <simgear/misc/interpolator.hxx>
23 #include <simgear/structure/commands.hxx>
24 #include <simgear/math/sg_geodesy.hxx>
25 #include <simgear/structure/event_mgr.hxx>
27 #include "NasalSys.hxx"
28 #include "NasalPositioned.hxx"
29 #include "NasalCanvas.hxx"
30 #include "NasalClipboard.hxx"
31 #include "NasalCondition.hxx"
33 #include <Main/globals.hxx>
34 #include <Main/util.hxx>
35 #include <Main/fg_props.hxx>
40 static FGNasalSys* nasalSys = 0;
42 // Listener class for loading Nasal modules on demand
43 class FGNasalModuleListener : public SGPropertyChangeListener
46 FGNasalModuleListener(SGPropertyNode* node);
48 virtual void valueChanged(SGPropertyNode* node);
51 SGPropertyNode_ptr _node;
54 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
58 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
60 if (_node->getBoolValue("enabled",false)&&
61 !_node->getBoolValue("loaded",true))
63 nasalSys->loadPropertyScripts(_node);
68 // Read and return file contents in a single buffer. Note use of
69 // stat() to get the file size. This is a win32 function, believe it
70 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
71 // Text mode brain damage will kill us if we're trying to do bytewise
73 static char* readfile(const char* file, int* lenOut)
76 if(stat(file, &data) != 0) return 0;
77 FILE* f = fopen(file, "rb");
79 char* buf = new char[data.st_size];
80 *lenOut = fread(buf, 1, data.st_size, f);
82 if(*lenOut != data.st_size) {
83 // Shouldn't happen, but warn anyway since it represents a
84 // platform bug and not a typical runtime error (missing file,
86 SG_LOG(SG_NASAL, SG_ALERT,
87 "ERROR in Nasal initialization: " <<
88 "short count returned from fread() of " << file <<
89 ". Check your C library!");
96 FGNasalSys::FGNasalSys()
102 _nextGCKey = 0; // Any value will do
106 // Utility. Sets a named key in a hash by C string, rather than nasal
108 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
110 naRef s = naNewString(_context);
111 naStr_fromdata(s, (char*)key, strlen(key));
112 naHash_set(hash, s, val);
115 void FGNasalSys::globalsSet(const char* key, naRef val)
117 hashset(_globals, key, val);
120 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
122 return callMethod(code, naNil(), argc, args, locals);
125 // Does a naCall() in a new context. Wrapped here to make lock
126 // tracking easier. Extension functions are called with the lock, but
127 // we have to release it before making a new naCall(). So rather than
128 // drop the lock in every extension function that might call back into
129 // Nasal, we keep a stack depth counter here and only unlock/lock
130 // around the naCall if it isn't the first one.
132 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
134 naContext ctx = naNewContext();
135 if(_callCount) naModUnlock();
137 naRef result = naCall(ctx, code, argc, args, self, locals);
141 if(_callCount) naModLock();
146 FGNasalSys::~FGNasalSys()
149 map<int, FGNasalListener *>::iterator it, end = _listener.end();
150 for(it = _listener.begin(); it != end; ++it)
153 naFreeContext(_context);
157 bool FGNasalSys::parseAndRun(const char* sourceCode)
159 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
163 call(code, 0, 0, naNil());
167 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
169 FGNasalScript* script = new FGNasalScript();
170 script->_gcKey = -1; // important, if we delete it on a parse
171 script->_nas = this; // error, don't clobber a real handle!
175 sprintf(buf, "FGNasalScript@%p", (void *)script);
179 script->_code = parse(name, src, strlen(src));
180 if(naIsNil(script->_code)) {
185 script->_gcKey = gcSave(script->_code);
189 // The get/setprop functions accept a *list* of strings and walk
190 // through the property tree with them to find the appropriate node.
191 // This allows a Nasal object to hold onto a property path and use it
192 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
193 // is the utility function that walks the property tree.
194 // Future enhancement: support integer arguments to specify array
196 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
198 SGPropertyNode* p = globals->get_props();
200 for(int i=0; i<len; i++) {
202 if(!naIsString(a)) return 0;
203 p = p->getNode(naStr_data(a));
206 } catch (const string& err) {
207 naRuntimeError(c, (char *)err.c_str());
213 // getprop() extension function. Concatenates its string arguments as
214 // property names and returns the value of the specified property. Or
215 // nil if it doesn't exist.
216 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
218 using namespace simgear;
219 const SGPropertyNode* p = findnode(c, args, argc);
220 if(!p) return naNil();
222 switch(p->getType()) {
223 case props::BOOL: case props::INT:
224 case props::LONG: case props::FLOAT:
227 double dv = p->getDoubleValue();
228 if (SGMisc<double>::isNaN(dv)) {
229 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
237 case props::UNSPECIFIED:
239 naRef nastr = naNewString(c);
240 const char* val = p->getStringValue();
241 naStr_fromdata(nastr, (char*)val, strlen(val));
244 case props::ALIAS: // <--- FIXME, recurse?
250 // setprop() extension function. Concatenates its string arguments as
251 // property names and sets the value of the specified property to the
253 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
256 char buf[BUFLEN + 1];
260 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
261 for(int i=0; i<argc-1; i++) {
262 naRef s = naStringValue(c, args[i]);
263 if(naIsNil(s)) return naNil();
264 strncpy(p, naStr_data(s), buflen);
266 buflen = BUFLEN - (p - buf);
267 if(i < (argc-2) && buflen > 0) {
273 SGPropertyNode* props = globals->get_props();
274 naRef val = args[argc-1];
277 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
279 naRef n = naNumValue(val);
281 naRuntimeError(c, "setprop() value is not string or number");
283 if (SGMisc<double>::isNaN(n.num)) {
284 naRuntimeError(c, "setprop() passed a NaN");
287 result = props->setDoubleValue(buf, n.num);
289 } catch (const string& err) {
290 naRuntimeError(c, (char *)err.c_str());
292 return naNum(result);
296 // print() extension function. Concatenates and prints its arguments
297 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
298 // make sure it appears. Is there better way to do this?
299 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
303 for(int i=0; i<n; i++) {
304 naRef s = naStringValue(c, args[i]);
305 if(naIsNil(s)) continue;
306 buf += naStr_data(s);
308 SG_LOG(SG_NASAL, SG_ALERT, buf);
309 return naNum(buf.length());
312 // fgcommand() extension function. Executes a named command via the
313 // FlightGear command manager. Takes a single property node name as
315 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
317 naRef cmd = argc > 0 ? args[0] : naNil();
318 naRef props = argc > 1 ? args[1] : naNil();
319 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
320 naRuntimeError(c, "bad arguments to fgcommand()");
321 SGPropertyNode_ptr tmp, *node;
323 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
325 tmp = new SGPropertyNode();
328 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
331 // settimer(func, dt, simtime) extension function. Falls through to
332 // FGNasalSys::setTimer(). See there for docs.
333 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
335 nasalSys->setTimer(c, argc, args);
339 // setlistener(func, property, bool) extension function. Falls through to
340 // FGNasalSys::setListener(). See there for docs.
341 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
343 return nasalSys->setListener(c, argc, args);
346 // removelistener(int) extension function. Falls through to
347 // FGNasalSys::removeListener(). See there for docs.
348 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
350 return nasalSys->removeListener(c, argc, args);
353 // Returns a ghost handle to the argument to the currently executing
355 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
357 return nasalSys->cmdArgGhost();
360 // Sets up a property interpolation. The first argument is either a
361 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
362 // interpolate. The second argument is a vector of pairs of
363 // value/delta numbers.
364 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
366 SGPropertyNode* node;
367 naRef prop = argc > 0 ? args[0] : naNil();
368 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
369 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
372 naRef curve = argc > 1 ? args[1] : naNil();
373 if(!naIsVector(curve)) return naNil();
374 int nPoints = naVec_size(curve) / 2;
375 double* values = new double[nPoints];
376 double* deltas = new double[nPoints];
377 for(int i=0; i<nPoints; i++) {
378 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
379 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
382 ((SGInterpolator*)globals->get_subsystem_mgr()
383 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
384 ->interpolate(node, nPoints, values, deltas);
391 // This is a better RNG than the one in the default Nasal distribution
392 // (which is based on the C library rand() implementation). It will
394 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
396 return naNum(sg_random());
399 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
405 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
411 // Return an array listing of all files in a directory
412 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
414 if(argc != 1 || !naIsString(args[0]))
415 naRuntimeError(c, "bad arguments to directory()");
417 simgear::Dir d(SGPath(naStr_data(args[0])));
418 if(!d.exists()) return naNil();
419 naRef result = naNewVector(c);
421 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
422 for (unsigned int i=0; i<paths.size(); ++i) {
423 std::string p = paths[i].file();
424 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
431 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
433 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
435 if(argc != 1 || !naIsString(args[0]))
436 naRuntimeError(c, "bad arguments to resolveDataPath()");
438 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
439 const char* pdata = p.c_str();
440 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
444 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
446 // <path> ... absolute path to an XML file
447 // <start-tag> ... callback function with two args: tag name, attribute hash
448 // <end-tag> ... callback function with one arg: tag name
449 // <data> ... callback function with one arg: data
450 // <pi> ... callback function with two args: target, data
451 // (pi = "processing instruction")
452 // All four callback functions are optional and default to nil.
453 // The function returns nil on error, or the validated file name otherwise.
454 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
456 if(argc < 1 || !naIsString(args[0]))
457 naRuntimeError(c, "parsexml(): path argument missing or not a string");
458 if(argc > 5) argc = 5;
459 for(int i=1; i<argc; i++)
460 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
461 naRuntimeError(c, "parsexml(): callback argument not a function");
463 const char* file = fgValidatePath(naStr_data(args[0]), false);
465 naRuntimeError(c, "parsexml(): reading '%s' denied "
466 "(unauthorized access)", naStr_data(args[0]));
469 std::ifstream input(file);
470 NasalXMLVisitor visitor(c, argc, args);
472 readXML(input, visitor);
473 } catch (const sg_exception& e) {
474 naRuntimeError(c, "parsexml(): file '%s' %s",
475 file, e.getFormattedMessage().c_str());
478 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
481 // Return UNIX epoch time in seconds.
482 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
486 GetSystemTimeAsFileTime(&ft);
487 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
488 // Converts from 100ns units in 1601 epoch to unix epoch in sec
489 return naNum((t * 1e-7) - 11644473600.0);
492 gettimeofday(&td, 0);
493 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
497 // Table of extension functions. Terminate with zeros.
498 static struct { const char* name; naCFunction func; } funcs[] = {
499 { "getprop", f_getprop },
500 { "setprop", f_setprop },
501 { "print", f_print },
502 { "_fgcommand", f_fgcommand },
503 { "settimer", f_settimer },
504 { "_setlistener", f_setlistener },
505 { "removelistener", f_removelistener },
506 { "_cmdarg", f_cmdarg },
507 { "_interpolate", f_interpolate },
509 { "srand", f_srand },
510 { "abort", f_abort },
511 { "directory", f_directory },
512 { "resolvepath", f_resolveDataPath },
513 { "parsexml", f_parsexml },
514 { "systime", f_systime },
518 naRef FGNasalSys::cmdArgGhost()
520 return propNodeGhost(_cmdArg);
523 void FGNasalSys::init()
527 _context = naNewContext();
529 // Start with globals. Add it to itself as a recursive
530 // sub-reference under the name "globals". This gives client-code
531 // write access to the namespace if someone wants to do something
533 _globals = naInit_std(_context);
534 naSave(_context, _globals);
535 hashset(_globals, "globals", _globals);
537 hashset(_globals, "math", naInit_math(_context));
538 hashset(_globals, "bits", naInit_bits(_context));
539 hashset(_globals, "io", naInit_io(_context));
540 hashset(_globals, "thread", naInit_thread(_context));
541 hashset(_globals, "utf8", naInit_utf8(_context));
543 // Add our custom extension functions:
544 for(i=0; funcs[i].name; i++)
545 hashset(_globals, funcs[i].name,
546 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
550 // And our SGPropertyNode wrapper
551 hashset(_globals, "props", genPropsModule());
553 // Make a "__gcsave" hash to hold the naRef objects which get
554 // passed to handles outside the interpreter (to protect them from
555 // begin garbage-collected).
556 _gcHash = naNewHash(_context);
557 hashset(_globals, "__gcsave", _gcHash);
559 initNasalPositioned(_globals, _context, _gcHash);
560 NasalClipboard::init(this);
561 initNasalCondition(_globals, _context, _gcHash);
563 // Now load the various source files in the Nasal directory
564 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
565 loadScriptDirectory(nasalDir);
567 // NasalCanvas needs to be initialized after the props module from props.nas
568 // (located in $FG_ROOT/Nasal/) has been loaded but before loading the
569 // canvas module or any script creating a canvas.
570 initNasalCanvas(_globals, _context, _gcHash);
572 // Add modules in Nasal subdirectories to property tree
573 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
574 simgear::Dir::NO_DOT_OR_DOTDOT, "");
575 for (unsigned int i=0; i<directories.size(); ++i) {
576 simgear::Dir dir(directories[i]);
577 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
578 addModule(directories[i].file(), scripts);
581 // set signal and remove node to avoid restoring at reinit
582 const char *s = "nasal-dir-initialized";
583 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
584 signal->setBoolValue(s, true);
585 signal->removeChildren(s, false);
587 // Pull scripts out of the property tree, too
588 loadPropertyScripts();
590 // now Nasal modules are loaded, we can do some delayed work
591 postinitNasalPositioned(_globals, _context);
594 void FGNasalSys::update(double)
596 if( NasalClipboard::getInstance() )
597 NasalClipboard::getInstance()->update();
599 if(!_dead_listener.empty()) {
600 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
601 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
602 _dead_listener.clear();
605 if (!_loadList.empty())
607 // process Nasal load hook (only one per update loop to avoid excessive lags)
608 _loadList.pop()->load();
611 if (!_unloadList.empty())
613 // process pending Nasal unload hooks after _all_ load hooks were processed
614 // (only unload one per update loop to avoid excessive lags)
615 _unloadList.pop()->unload();
618 // The global context is a legacy thing. We use dynamically
619 // created contexts for naCall() now, so that we can call them
620 // recursively. But there are still spots that want to use it for
621 // naNew*() calls, which end up leaking memory because the context
622 // only clears out its temporary vector when it's *used*. So just
623 // junk it and fetch a new/reinitialized one every frame. This is
624 // clumsy: the right solution would use the dynamic context in all
625 // cases and eliminate _context entirely. But that's more work,
626 // and this works fine (yes, they say "New" and "Free", but
627 // they're very fast, just trust me). -Andy
628 naFreeContext(_context);
629 _context = naNewContext();
632 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
634 return p1.file() < p2.file();
637 // Loads all scripts in given directory
638 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
640 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
641 // Note: simgear::Dir already reports file entries in a deterministic order,
642 // so a fixed loading sequence is guaranteed (same for every user)
643 for (unsigned int i=0; i<scripts.size(); ++i) {
644 SGPath fullpath(scripts[i]);
645 SGPath file = fullpath.file();
646 loadModule(fullpath, file.base().c_str());
650 // Create module with list of scripts
651 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
653 if (scripts.size()>0)
655 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
656 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
657 for (unsigned int i=0; i<scripts.size(); ++i) {
658 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
659 pFileNode->setStringValue(scripts[i].c_str());
661 if (!module_node->hasChild("enabled",0))
663 SGPropertyNode* node = module_node->getChild("enabled",0,true);
664 node->setBoolValue(true);
665 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
670 // Loads the scripts found under /nasal in the global tree
671 void FGNasalSys::loadPropertyScripts()
673 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
676 for(int i=0; i<nasal->nChildren(); i++)
678 SGPropertyNode* n = nasal->getChild(i);
679 loadPropertyScripts(n);
683 // Loads the scripts found under /nasal in the global tree
684 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
686 bool is_loaded = false;
688 const char* module = n->getName();
689 if(n->hasChild("module"))
690 module = n->getStringValue("module");
691 if (n->getBoolValue("enabled",true))
693 // allow multiple files to be specified within a single
697 bool file_specified = false;
699 while((fn = n->getChild("file", j)) != NULL) {
700 file_specified = true;
701 const char* file = fn->getStringValue();
703 if (!p.isAbsolute() || !p.exists())
705 p = globals->resolve_maybe_aircraft_path(file);
708 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
709 file << "' for module '" << module << "'.");
712 ok &= p.isNull() ? false : loadModule(p, module);
716 const char* src = n->getStringValue("script");
717 if(!n->hasChild("script")) src = 0; // Hrm...
719 createModule(module, n->getPath().c_str(), src, strlen(src));
721 if(!file_specified && !src)
723 // module no longer exists - clear the archived "enable" flag
724 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
725 SGPropertyNode* node = n->getChild("enabled",0,false);
727 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
729 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
730 "no <file> or <script> defined in " <<
731 "/nasal/" << module);
738 SGPropertyNode* enable = n->getChild("enabled");
741 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
742 enable->addChangeListener(listener, false);
745 SGPropertyNode* loaded = n->getChild("loaded",0,true);
746 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
747 loaded->setBoolValue(is_loaded);
750 // Logs a runtime error, with stack trace, to the FlightGear log stream
751 void FGNasalSys::logError(naContext context)
753 SG_LOG(SG_NASAL, SG_ALERT,
754 "Nasal runtime error: " << naGetError(context));
755 SG_LOG(SG_NASAL, SG_ALERT,
756 " at " << naStr_data(naGetSourceFile(context, 0)) <<
757 ", line " << naGetLine(context, 0));
758 for(int i=1; i<naStackDepth(context); i++)
759 SG_LOG(SG_NASAL, SG_ALERT,
760 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
761 ", line " << naGetLine(context, i));
764 // Reads a script file, executes it, and places the resulting
765 // namespace into the global namespace under the specified module
767 bool FGNasalSys::loadModule(SGPath file, const char* module)
770 char* buf = readfile(file.c_str(), &len);
772 SG_LOG(SG_NASAL, SG_ALERT,
773 "Nasal error: could not read script file " << file.c_str()
774 << " into module " << module);
778 bool ok = createModule(module, file.c_str(), buf, len);
783 // Parse and run. Save the local variables namespace, as it will
784 // become a sub-object of globals. The optional "arg" argument can be
785 // used to pass an associated property node to the module, which can then
786 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
787 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
788 const char* src, int len,
789 const SGPropertyNode* cmdarg,
790 int argc, naRef* args)
792 naRef code = parse(fileName, src, len);
796 // See if we already have a module hash to use. This allows the
797 // user to, for example, add functions to the built-in math
798 // module. Make a new one if necessary.
800 naRef modname = naNewString(_context);
801 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
802 if(!naHash_get(_globals, modname, &locals))
803 locals = naNewHash(_context);
805 _cmdArg = (SGPropertyNode*)cmdarg;
807 call(code, argc, args, locals);
808 hashset(_globals, moduleName, locals);
812 void FGNasalSys::deleteModule(const char* moduleName)
814 naRef modname = naNewString(_context);
815 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
816 naHash_delete(_globals, modname);
819 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
822 naRef srcfile = naNewString(_context);
823 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
824 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
826 SG_LOG(SG_NASAL, SG_ALERT,
827 "Nasal parse error: " << naGetError(_context) <<
828 " in "<< filename <<", line " << errLine);
832 // Bind to the global namespace before returning
833 return naBindFunction(_context, code, _globals);
836 bool FGNasalSys::handleCommand( const char* moduleName,
837 const char* fileName,
839 const SGPropertyNode* arg )
841 naRef code = parse(fileName, src, strlen(src));
842 if(naIsNil(code)) return false;
844 // Commands can be run "in" a module. Make sure that module
845 // exists, and set it up as the local variables hash for the
847 naRef locals = naNil();
849 naRef modname = naNewString(_context);
850 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
851 if(!naHash_get(_globals, modname, &locals)) {
852 locals = naNewHash(_context);
853 naHash_set(_globals, modname, locals);
857 // Cache this command's argument for inspection via cmdarg(). For
858 // performance reasons, we won't bother with it if the invoked
859 // code doesn't need it.
860 _cmdArg = (SGPropertyNode*)arg;
862 call(code, 0, 0, locals);
866 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
868 const char* src = arg->getStringValue("script");
869 const char* moduleName = arg->getStringValue("module");
871 return handleCommand( moduleName,
872 arg ? arg->getPath(true).c_str() : moduleName,
877 // settimer(func, dt, simtime) extension function. The first argument
878 // is a Nasal function to call, the second is a delta time (from now),
879 // in seconds. The third, if present, is a boolean value indicating
880 // that "real world" time (rather than simulator time) is to be used.
882 // Implementation note: the FGTimer objects don't live inside the
883 // garbage collector, so the Nasal handler functions have to be
884 // "saved" somehow lest they be inadvertently cleaned. In this case,
885 // they are inserted into a globals.__gcsave hash and removed on
887 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
889 // Extract the handler, delta, and simtime arguments:
890 naRef handler = argc > 0 ? args[0] : naNil();
891 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
892 naRuntimeError(c, "settimer() with invalid function argument");
896 naRef delta = argc > 1 ? args[1] : naNil();
898 naRuntimeError(c, "settimer() with invalid time argument");
902 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
904 // Generate and register a C++ timer handler
905 NasalTimer* t = new NasalTimer;
906 t->handler = handler;
907 t->gcKey = gcSave(handler);
910 globals->get_event_mgr()->addEvent("NasalTimer",
911 t, &NasalTimer::timerExpired,
915 void FGNasalSys::handleTimer(NasalTimer* t)
917 call(t->handler, 0, 0, naNil());
921 int FGNasalSys::gcSave(naRef r)
923 int key = _nextGCKey++;
924 naHash_set(_gcHash, naNum(key), r);
928 void FGNasalSys::gcRelease(int key)
930 naHash_delete(_gcHash, naNum(key));
933 void FGNasalSys::NasalTimer::timerExpired()
935 nasal->handleTimer(this);
939 int FGNasalSys::_listenerId = 0;
941 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
942 // Attaches a callback function to a property (specified as a global
943 // property path string or a SGPropertyNode_ptr* ghost). If the third,
944 // optional argument (default=0) is set to 1, then the function is also
945 // called initially. If the fourth, optional argument is set to 0, then the
946 // function is only called when the property node value actually changes.
947 // Otherwise it's called independent of the value whenever the node is
948 // written to (default). The setlistener() function returns a unique
949 // id number, which is to be used as argument to the removelistener()
951 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
953 SGPropertyNode_ptr node;
954 naRef prop = argc > 0 ? args[0] : naNil();
955 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
956 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
958 naRuntimeError(c, "setlistener() with invalid property argument");
963 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
966 naRef code = argc > 1 ? args[1] : naNil();
967 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
968 naRuntimeError(c, "setlistener() with invalid function argument");
972 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
973 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
974 FGNasalListener *nl = new FGNasalListener(node, code, this,
975 gcSave(code), _listenerId, init, type);
977 node->addChangeListener(nl, init != 0);
979 _listener[_listenerId] = nl;
980 return naNum(_listenerId++);
983 // removelistener(int) extension function. The argument is the id of
984 // a listener as returned by the setlistener() function.
985 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
987 naRef id = argc > 0 ? args[0] : naNil();
988 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
990 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
991 naRuntimeError(c, "removelistener() with invalid listener id");
995 it->second->_dead = true;
996 _dead_listener.push_back(it->second);
998 return naNum(_listener.size());
1003 // FGNasalListener class.
1005 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1006 FGNasalSys* nasal, int key, int id,
1007 int init, int type) :
1020 if(_type == 0 && !_init)
1024 FGNasalListener::~FGNasalListener()
1026 _node->removeChangeListener(this);
1027 _nas->gcRelease(_gcKey);
1030 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1032 if(_active || _dead) return;
1033 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1036 arg[0] = _nas->propNodeGhost(which);
1037 arg[1] = _nas->propNodeGhost(_node);
1038 arg[2] = mode; // value changed, child added/removed
1039 arg[3] = naNum(_node != which); // child event?
1040 _nas->call(_code, 4, arg, naNil());
1044 void FGNasalListener::valueChanged(SGPropertyNode* node)
1046 if(_type < 2 && node != _node) return; // skip child events
1047 if(_type > 0 || changed(_node) || _init)
1048 call(node, naNum(0));
1053 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1055 if(_type == 2) call(child, naNum(1));
1058 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1060 if(_type == 2) call(child, naNum(-1));
1063 bool FGNasalListener::changed(SGPropertyNode* node)
1065 using namespace simgear;
1066 props::Type type = node->getType();
1067 if(type == props::NONE) return false;
1068 if(type == props::UNSPECIFIED) return true;
1076 long l = node->getLongValue();
1077 result = l != _last_int;
1084 double d = node->getDoubleValue();
1085 result = d != _last_float;
1091 string s = node->getStringValue();
1092 result = s != _last_string;
1101 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
1102 // such a class, then it lets modelLoaded() run the <load> script, and the
1103 // destructor the <unload> script. The latter happens when the model branch
1104 // is removed from the scene graph.
1106 unsigned int FGNasalModelData::_module_id = 0;
1108 void FGNasalModelData::load()
1110 std::stringstream m;
1111 m << "__model" << _module_id++;
1114 SG_LOG(SG_NASAL, SG_DEBUG, "Loading nasal module " << _module.c_str());
1116 const char *s = _load ? _load->getStringValue() : "";
1119 arg[0] = nasalSys->propNodeGhost(_root);
1120 arg[1] = nasalSys->propNodeGhost(_prop);
1121 nasalSys->createModule(_module.c_str(), _path.c_str(), s, strlen(s),
1125 void FGNasalModelData::unload()
1127 if (_module.empty())
1131 SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1132 "without Nasal subsystem present.");
1136 SG_LOG(SG_NASAL, SG_DEBUG, "Unloading nasal module " << _module.c_str());
1140 const char *s = _unload->getStringValue();
1141 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _root);
1144 nasalSys->deleteModule(_module.c_str());
1147 void FGNasalModelDataProxy::modelLoaded(const string& path, SGPropertyNode *prop,
1151 SG_LOG(SG_NASAL, SG_WARN, "Trying to run a <load> script "
1152 "without Nasal subsystem present.");
1159 SGPropertyNode *nasal = prop->getNode("nasal");
1163 SGPropertyNode* load = nasal->getNode("load");
1164 SGPropertyNode* unload = nasal->getNode("unload");
1166 if ((!load) && (!unload))
1169 _data = new FGNasalModelData(_root, path, prop, load, unload);
1171 // register Nasal module to be created and loaded in the main thread.
1172 nasalSys->registerToLoad(_data);
1175 FGNasalModelDataProxy::~FGNasalModelDataProxy()
1177 // when necessary, register Nasal module to be destroyed/unloaded
1178 // in the main thread.
1179 if ((_data.valid())&&(nasalSys))
1180 nasalSys->registerToUnload(_data);
1183 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1185 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1186 _c(naSubContext(c)),
1187 _start_element(argc > 1 ? args[1] : naNil()),
1188 _end_element(argc > 2 ? args[2] : naNil()),
1189 _data(argc > 3 ? args[3] : naNil()),
1190 _pi(argc > 4 ? args[4] : naNil())
1194 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1196 if(naIsNil(_start_element)) return;
1197 naRef attr = naNewHash(_c);
1198 for(int i=0; i<a.size(); i++) {
1199 naRef name = make_string(a.getName(i));
1200 naRef value = make_string(a.getValue(i));
1201 naHash_set(attr, name, value);
1203 call(_start_element, 2, make_string(tag), attr);
1206 void NasalXMLVisitor::endElement(const char* tag)
1208 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1211 void NasalXMLVisitor::data(const char* str, int len)
1213 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1216 void NasalXMLVisitor::pi(const char* target, const char* data)
1218 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1221 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1226 naCall(_c, func, num, args, naNil(), naNil());
1231 naRef NasalXMLVisitor::make_string(const char* s, int n)
1233 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1234 n < 0 ? strlen(s) : n);