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"
32 #include "NasalString.hxx"
34 #include <Main/globals.hxx>
35 #include <Main/util.hxx>
36 #include <Main/fg_props.hxx>
41 void postinitNasalGUI(naRef globals, naContext c);
43 static FGNasalSys* nasalSys = 0;
45 // Listener class for loading Nasal modules on demand
46 class FGNasalModuleListener : public SGPropertyChangeListener
49 FGNasalModuleListener(SGPropertyNode* node);
51 virtual void valueChanged(SGPropertyNode* node);
54 SGPropertyNode_ptr _node;
57 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
61 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
63 if (_node->getBoolValue("enabled",false)&&
64 !_node->getBoolValue("loaded",true))
66 nasalSys->loadPropertyScripts(_node);
71 // Read and return file contents in a single buffer. Note use of
72 // stat() to get the file size. This is a win32 function, believe it
73 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
74 // Text mode brain damage will kill us if we're trying to do bytewise
76 static char* readfile(const char* file, int* lenOut)
79 if(stat(file, &data) != 0) return 0;
80 FILE* f = fopen(file, "rb");
82 char* buf = new char[data.st_size];
83 *lenOut = fread(buf, 1, data.st_size, f);
85 if(*lenOut != data.st_size) {
86 // Shouldn't happen, but warn anyway since it represents a
87 // platform bug and not a typical runtime error (missing file,
89 SG_LOG(SG_NASAL, SG_ALERT,
90 "ERROR in Nasal initialization: " <<
91 "short count returned from fread() of " << file <<
92 ". Check your C library!");
99 FGNasalSys::FGNasalSys()
106 _nextGCKey = 0; // Any value will do
110 // Utility. Sets a named key in a hash by C string, rather than nasal
112 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
114 naRef s = naNewString(_context);
115 naStr_fromdata(s, (char*)key, strlen(key));
116 naHash_set(hash, s, val);
119 void FGNasalSys::globalsSet(const char* key, naRef val)
121 hashset(_globals, key, val);
124 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
126 return callMethod(code, naNil(), argc, args, locals);
129 // Does a naCall() in a new context. Wrapped here to make lock
130 // tracking easier. Extension functions are called with the lock, but
131 // we have to release it before making a new naCall(). So rather than
132 // drop the lock in every extension function that might call back into
133 // Nasal, we keep a stack depth counter here and only unlock/lock
134 // around the naCall if it isn't the first one.
136 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
138 naContext ctx = naNewContext();
139 if(_callCount) naModUnlock();
141 naRef result = naCall(ctx, code, argc, args, self, locals);
145 if(_callCount) naModLock();
150 FGNasalSys::~FGNasalSys()
153 map<int, FGNasalListener *>::iterator it, end = _listener.end();
154 for(it = _listener.begin(); it != end; ++it)
157 naFreeContext(_context);
162 bool FGNasalSys::parseAndRun(const char* sourceCode)
164 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
168 call(code, 0, 0, naNil());
172 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
174 FGNasalScript* script = new FGNasalScript();
175 script->_gcKey = -1; // important, if we delete it on a parse
176 script->_nas = this; // error, don't clobber a real handle!
180 sprintf(buf, "FGNasalScript@%p", (void *)script);
184 script->_code = parse(name, src, strlen(src));
185 if(naIsNil(script->_code)) {
190 script->_gcKey = gcSave(script->_code);
194 // The get/setprop functions accept a *list* of strings and walk
195 // through the property tree with them to find the appropriate node.
196 // This allows a Nasal object to hold onto a property path and use it
197 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
198 // is the utility function that walks the property tree.
199 // Future enhancement: support integer arguments to specify array
201 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
203 SGPropertyNode* p = globals->get_props();
205 for(int i=0; i<len; i++) {
207 if(!naIsString(a)) return 0;
208 p = p->getNode(naStr_data(a));
211 } catch (const string& err) {
212 naRuntimeError(c, (char *)err.c_str());
218 // getprop() extension function. Concatenates its string arguments as
219 // property names and returns the value of the specified property. Or
220 // nil if it doesn't exist.
221 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
223 using namespace simgear;
224 const SGPropertyNode* p = findnode(c, args, argc);
225 if(!p) return naNil();
227 switch(p->getType()) {
228 case props::BOOL: case props::INT:
229 case props::LONG: case props::FLOAT:
232 double dv = p->getDoubleValue();
233 if (SGMisc<double>::isNaN(dv)) {
234 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
242 case props::UNSPECIFIED:
244 naRef nastr = naNewString(c);
245 const char* val = p->getStringValue();
246 naStr_fromdata(nastr, (char*)val, strlen(val));
249 case props::ALIAS: // <--- FIXME, recurse?
255 // setprop() extension function. Concatenates its string arguments as
256 // property names and sets the value of the specified property to the
258 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
261 char buf[BUFLEN + 1];
265 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
266 for(int i=0; i<argc-1; i++) {
267 naRef s = naStringValue(c, args[i]);
268 if(naIsNil(s)) return naNil();
269 strncpy(p, naStr_data(s), buflen);
271 buflen = BUFLEN - (p - buf);
272 if(i < (argc-2) && buflen > 0) {
278 SGPropertyNode* props = globals->get_props();
279 naRef val = args[argc-1];
282 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
284 naRef n = naNumValue(val);
286 naRuntimeError(c, "setprop() value is not string or number");
288 if (SGMisc<double>::isNaN(n.num)) {
289 naRuntimeError(c, "setprop() passed a NaN");
292 result = props->setDoubleValue(buf, n.num);
294 } catch (const string& err) {
295 naRuntimeError(c, (char *)err.c_str());
297 return naNum(result);
301 // print() extension function. Concatenates and prints its arguments
302 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
303 // make sure it appears. Is there better way to do this?
304 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
308 for(int i=0; i<n; i++) {
309 naRef s = naStringValue(c, args[i]);
310 if(naIsNil(s)) continue;
311 buf += naStr_data(s);
313 SG_LOG(SG_NASAL, SG_ALERT, buf);
314 return naNum(buf.length());
317 // fgcommand() extension function. Executes a named command via the
318 // FlightGear command manager. Takes a single property node name as
320 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
322 naRef cmd = argc > 0 ? args[0] : naNil();
323 naRef props = argc > 1 ? args[1] : naNil();
324 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
325 naRuntimeError(c, "bad arguments to fgcommand()");
326 SGPropertyNode_ptr tmp, *node;
328 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
330 tmp = new SGPropertyNode();
333 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
336 // settimer(func, dt, simtime) extension function. Falls through to
337 // FGNasalSys::setTimer(). See there for docs.
338 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
340 nasalSys->setTimer(c, argc, args);
344 // setlistener(func, property, bool) extension function. Falls through to
345 // FGNasalSys::setListener(). See there for docs.
346 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
348 return nasalSys->setListener(c, argc, args);
351 // removelistener(int) extension function. Falls through to
352 // FGNasalSys::removeListener(). See there for docs.
353 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
355 return nasalSys->removeListener(c, argc, args);
358 // Returns a ghost handle to the argument to the currently executing
360 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
362 return nasalSys->cmdArgGhost();
365 // Sets up a property interpolation. The first argument is either a
366 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
367 // interpolate. The second argument is a vector of pairs of
368 // value/delta numbers.
369 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
371 SGPropertyNode* node;
372 naRef prop = argc > 0 ? args[0] : naNil();
373 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
374 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
377 naRef curve = argc > 1 ? args[1] : naNil();
378 if(!naIsVector(curve)) return naNil();
379 int nPoints = naVec_size(curve) / 2;
380 double* values = new double[nPoints];
381 double* deltas = new double[nPoints];
382 for(int i=0; i<nPoints; i++) {
383 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
384 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
387 ((SGInterpolator*)globals->get_subsystem_mgr()
388 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
389 ->interpolate(node, nPoints, values, deltas);
396 // This is a better RNG than the one in the default Nasal distribution
397 // (which is based on the C library rand() implementation). It will
399 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
401 return naNum(sg_random());
404 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
410 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
416 // Return an array listing of all files in a directory
417 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
419 if(argc != 1 || !naIsString(args[0]))
420 naRuntimeError(c, "bad arguments to directory()");
422 simgear::Dir d(SGPath(naStr_data(args[0])));
423 if(!d.exists()) return naNil();
424 naRef result = naNewVector(c);
426 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
427 for (unsigned int i=0; i<paths.size(); ++i) {
428 std::string p = paths[i].file();
429 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
436 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
438 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
440 if(argc != 1 || !naIsString(args[0]))
441 naRuntimeError(c, "bad arguments to resolveDataPath()");
443 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
444 const char* pdata = p.c_str();
445 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
449 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
451 // <path> ... absolute path to an XML file
452 // <start-tag> ... callback function with two args: tag name, attribute hash
453 // <end-tag> ... callback function with one arg: tag name
454 // <data> ... callback function with one arg: data
455 // <pi> ... callback function with two args: target, data
456 // (pi = "processing instruction")
457 // All four callback functions are optional and default to nil.
458 // The function returns nil on error, or the validated file name otherwise.
459 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
461 if(argc < 1 || !naIsString(args[0]))
462 naRuntimeError(c, "parsexml(): path argument missing or not a string");
463 if(argc > 5) argc = 5;
464 for(int i=1; i<argc; i++)
465 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
466 naRuntimeError(c, "parsexml(): callback argument not a function");
468 const char* file = fgValidatePath(naStr_data(args[0]), false);
470 naRuntimeError(c, "parsexml(): reading '%s' denied "
471 "(unauthorized access)", naStr_data(args[0]));
474 std::ifstream input(file);
475 NasalXMLVisitor visitor(c, argc, args);
477 readXML(input, visitor);
478 } catch (const sg_exception& e) {
479 naRuntimeError(c, "parsexml(): file '%s' %s",
480 file, e.getFormattedMessage().c_str());
483 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
486 // Return UNIX epoch time in seconds.
487 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
491 GetSystemTimeAsFileTime(&ft);
492 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
493 // Converts from 100ns units in 1601 epoch to unix epoch in sec
494 return naNum((t * 1e-7) - 11644473600.0);
497 gettimeofday(&td, 0);
498 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
502 // Table of extension functions. Terminate with zeros.
503 static struct { const char* name; naCFunction func; } funcs[] = {
504 { "getprop", f_getprop },
505 { "setprop", f_setprop },
506 { "print", f_print },
507 { "_fgcommand", f_fgcommand },
508 { "settimer", f_settimer },
509 { "_setlistener", f_setlistener },
510 { "removelistener", f_removelistener },
511 { "_cmdarg", f_cmdarg },
512 { "_interpolate", f_interpolate },
514 { "srand", f_srand },
515 { "abort", f_abort },
516 { "directory", f_directory },
517 { "resolvepath", f_resolveDataPath },
518 { "parsexml", f_parsexml },
519 { "systime", f_systime },
523 naRef FGNasalSys::cmdArgGhost()
525 return propNodeGhost(_cmdArg);
528 void FGNasalSys::init()
532 _context = naNewContext();
534 // Start with globals. Add it to itself as a recursive
535 // sub-reference under the name "globals". This gives client-code
536 // write access to the namespace if someone wants to do something
538 _globals = naInit_std(_context);
539 naSave(_context, _globals);
540 hashset(_globals, "globals", _globals);
542 hashset(_globals, "math", naInit_math(_context));
543 hashset(_globals, "bits", naInit_bits(_context));
544 hashset(_globals, "io", naInit_io(_context));
545 hashset(_globals, "thread", naInit_thread(_context));
546 hashset(_globals, "utf8", naInit_utf8(_context));
548 // Add our custom extension functions:
549 for(i=0; funcs[i].name; i++)
550 hashset(_globals, funcs[i].name,
551 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
553 // And our SGPropertyNode wrapper
554 hashset(_globals, "props", genPropsModule());
556 // Make a "__gcsave" hash to hold the naRef objects which get
557 // passed to handles outside the interpreter (to protect them from
558 // begin garbage-collected).
559 _gcHash = naNewHash(_context);
560 hashset(_globals, "__gcsave", _gcHash);
562 // Add string methods
563 _string = naInit_string(_context);
564 naSave(_context, _string);
565 initNasalString(_globals, _string, _context, _gcHash);
567 initNasalPositioned(_globals, _context, _gcHash);
568 NasalClipboard::init(this);
569 initNasalCanvas(_globals, _context, _gcHash);
570 initNasalCondition(_globals, _context, _gcHash);
572 // Now load the various source files in the Nasal directory
573 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
574 loadScriptDirectory(nasalDir);
576 // Add modules in Nasal subdirectories to property tree
577 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
578 simgear::Dir::NO_DOT_OR_DOTDOT, "");
579 for (unsigned int i=0; i<directories.size(); ++i) {
580 simgear::Dir dir(directories[i]);
581 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
582 addModule(directories[i].file(), scripts);
585 // set signal and remove node to avoid restoring at reinit
586 const char *s = "nasal-dir-initialized";
587 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
588 signal->setBoolValue(s, true);
589 signal->removeChildren(s, false);
591 // Pull scripts out of the property tree, too
592 loadPropertyScripts();
594 // now Nasal modules are loaded, we can do some delayed work
595 postinitNasalPositioned(_globals, _context);
596 postinitNasalGUI(_globals, _context);
599 void FGNasalSys::update(double)
601 if( NasalClipboard::getInstance() )
602 NasalClipboard::getInstance()->update();
604 if(!_dead_listener.empty()) {
605 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
606 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
607 _dead_listener.clear();
610 if (!_loadList.empty())
612 // process Nasal load hook (only one per update loop to avoid excessive lags)
613 _loadList.pop()->load();
616 if (!_unloadList.empty())
618 // process pending Nasal unload hooks after _all_ load hooks were processed
619 // (only unload one per update loop to avoid excessive lags)
620 _unloadList.pop()->unload();
623 // The global context is a legacy thing. We use dynamically
624 // created contexts for naCall() now, so that we can call them
625 // recursively. But there are still spots that want to use it for
626 // naNew*() calls, which end up leaking memory because the context
627 // only clears out its temporary vector when it's *used*. So just
628 // junk it and fetch a new/reinitialized one every frame. This is
629 // clumsy: the right solution would use the dynamic context in all
630 // cases and eliminate _context entirely. But that's more work,
631 // and this works fine (yes, they say "New" and "Free", but
632 // they're very fast, just trust me). -Andy
633 naFreeContext(_context);
634 _context = naNewContext();
637 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
639 return p1.file() < p2.file();
642 // Loads all scripts in given directory
643 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
645 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
646 // Note: simgear::Dir already reports file entries in a deterministic order,
647 // so a fixed loading sequence is guaranteed (same for every user)
648 for (unsigned int i=0; i<scripts.size(); ++i) {
649 SGPath fullpath(scripts[i]);
650 SGPath file = fullpath.file();
651 loadModule(fullpath, file.base().c_str());
655 // Create module with list of scripts
656 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
658 if (scripts.size()>0)
660 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
661 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
662 for (unsigned int i=0; i<scripts.size(); ++i) {
663 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
664 pFileNode->setStringValue(scripts[i].c_str());
666 if (!module_node->hasChild("enabled",0))
668 SGPropertyNode* node = module_node->getChild("enabled",0,true);
669 node->setBoolValue(true);
670 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
675 // Loads the scripts found under /nasal in the global tree
676 void FGNasalSys::loadPropertyScripts()
678 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
681 for(int i=0; i<nasal->nChildren(); i++)
683 SGPropertyNode* n = nasal->getChild(i);
684 loadPropertyScripts(n);
688 // Loads the scripts found under /nasal in the global tree
689 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
691 bool is_loaded = false;
693 const char* module = n->getName();
694 if(n->hasChild("module"))
695 module = n->getStringValue("module");
696 if (n->getBoolValue("enabled",true))
698 // allow multiple files to be specified within a single
702 bool file_specified = false;
704 while((fn = n->getChild("file", j)) != NULL) {
705 file_specified = true;
706 const char* file = fn->getStringValue();
708 if (!p.isAbsolute() || !p.exists())
710 p = globals->resolve_maybe_aircraft_path(file);
713 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
714 file << "' for module '" << module << "'.");
717 ok &= p.isNull() ? false : loadModule(p, module);
721 const char* src = n->getStringValue("script");
722 if(!n->hasChild("script")) src = 0; // Hrm...
724 createModule(module, n->getPath().c_str(), src, strlen(src));
726 if(!file_specified && !src)
728 // module no longer exists - clear the archived "enable" flag
729 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
730 SGPropertyNode* node = n->getChild("enabled",0,false);
732 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
734 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
735 "no <file> or <script> defined in " <<
736 "/nasal/" << module);
743 SGPropertyNode* enable = n->getChild("enabled");
746 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
747 enable->addChangeListener(listener, false);
750 SGPropertyNode* loaded = n->getChild("loaded",0,true);
751 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
752 loaded->setBoolValue(is_loaded);
755 // Logs a runtime error, with stack trace, to the FlightGear log stream
756 void FGNasalSys::logError(naContext context)
758 SG_LOG(SG_NASAL, SG_ALERT,
759 "Nasal runtime error: " << naGetError(context));
760 SG_LOG(SG_NASAL, SG_ALERT,
761 " at " << naStr_data(naGetSourceFile(context, 0)) <<
762 ", line " << naGetLine(context, 0));
763 for(int i=1; i<naStackDepth(context); i++)
764 SG_LOG(SG_NASAL, SG_ALERT,
765 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
766 ", line " << naGetLine(context, i));
769 // Reads a script file, executes it, and places the resulting
770 // namespace into the global namespace under the specified module
772 bool FGNasalSys::loadModule(SGPath file, const char* module)
775 char* buf = readfile(file.c_str(), &len);
777 SG_LOG(SG_NASAL, SG_ALERT,
778 "Nasal error: could not read script file " << file.c_str()
779 << " into module " << module);
783 bool ok = createModule(module, file.c_str(), buf, len);
788 // Parse and run. Save the local variables namespace, as it will
789 // become a sub-object of globals. The optional "arg" argument can be
790 // used to pass an associated property node to the module, which can then
791 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
792 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
793 const char* src, int len,
794 const SGPropertyNode* cmdarg,
795 int argc, naRef* args)
797 naRef code = parse(fileName, src, len);
801 // See if we already have a module hash to use. This allows the
802 // user to, for example, add functions to the built-in math
803 // module. Make a new one if necessary.
805 naRef modname = naNewString(_context);
806 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
807 if(!naHash_get(_globals, modname, &locals))
808 locals = naNewHash(_context);
810 _cmdArg = (SGPropertyNode*)cmdarg;
812 call(code, argc, args, locals);
813 hashset(_globals, moduleName, locals);
817 void FGNasalSys::deleteModule(const char* moduleName)
819 naRef modname = naNewString(_context);
820 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
821 naHash_delete(_globals, modname);
824 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
827 naRef srcfile = naNewString(_context);
828 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
829 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
831 SG_LOG(SG_NASAL, SG_ALERT,
832 "Nasal parse error: " << naGetError(_context) <<
833 " in "<< filename <<", line " << errLine);
837 // Bind to the global namespace before returning
838 return naBindFunction(_context, code, _globals);
841 bool FGNasalSys::handleCommand( const char* moduleName,
842 const char* fileName,
844 const SGPropertyNode* arg )
846 naRef code = parse(fileName, src, strlen(src));
847 if(naIsNil(code)) return false;
849 // Commands can be run "in" a module. Make sure that module
850 // exists, and set it up as the local variables hash for the
852 naRef locals = naNil();
854 naRef modname = naNewString(_context);
855 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
856 if(!naHash_get(_globals, modname, &locals)) {
857 locals = naNewHash(_context);
858 naHash_set(_globals, modname, locals);
862 // Cache this command's argument for inspection via cmdarg(). For
863 // performance reasons, we won't bother with it if the invoked
864 // code doesn't need it.
865 _cmdArg = (SGPropertyNode*)arg;
867 call(code, 0, 0, locals);
871 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
873 const char* src = arg->getStringValue("script");
874 const char* moduleName = arg->getStringValue("module");
876 return handleCommand( moduleName,
877 arg ? arg->getPath(true).c_str() : moduleName,
882 // settimer(func, dt, simtime) extension function. The first argument
883 // is a Nasal function to call, the second is a delta time (from now),
884 // in seconds. The third, if present, is a boolean value indicating
885 // that "real world" time (rather than simulator time) is to be used.
887 // Implementation note: the FGTimer objects don't live inside the
888 // garbage collector, so the Nasal handler functions have to be
889 // "saved" somehow lest they be inadvertently cleaned. In this case,
890 // they are inserted into a globals.__gcsave hash and removed on
892 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
894 // Extract the handler, delta, and simtime arguments:
895 naRef handler = argc > 0 ? args[0] : naNil();
896 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
897 naRuntimeError(c, "settimer() with invalid function argument");
901 naRef delta = argc > 1 ? args[1] : naNil();
903 naRuntimeError(c, "settimer() with invalid time argument");
907 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
909 // Generate and register a C++ timer handler
910 NasalTimer* t = new NasalTimer;
911 t->handler = handler;
912 t->gcKey = gcSave(handler);
915 globals->get_event_mgr()->addEvent("NasalTimer",
916 t, &NasalTimer::timerExpired,
920 void FGNasalSys::handleTimer(NasalTimer* t)
922 call(t->handler, 0, 0, naNil());
926 int FGNasalSys::gcSave(naRef r)
928 int key = _nextGCKey++;
929 naHash_set(_gcHash, naNum(key), r);
933 void FGNasalSys::gcRelease(int key)
935 naHash_delete(_gcHash, naNum(key));
938 void FGNasalSys::NasalTimer::timerExpired()
940 nasal->handleTimer(this);
944 int FGNasalSys::_listenerId = 0;
946 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
947 // Attaches a callback function to a property (specified as a global
948 // property path string or a SGPropertyNode_ptr* ghost). If the third,
949 // optional argument (default=0) is set to 1, then the function is also
950 // called initially. If the fourth, optional argument is set to 0, then the
951 // function is only called when the property node value actually changes.
952 // Otherwise it's called independent of the value whenever the node is
953 // written to (default). The setlistener() function returns a unique
954 // id number, which is to be used as argument to the removelistener()
956 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
958 SGPropertyNode_ptr node;
959 naRef prop = argc > 0 ? args[0] : naNil();
960 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
961 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
963 naRuntimeError(c, "setlistener() with invalid property argument");
968 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
971 naRef code = argc > 1 ? args[1] : naNil();
972 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
973 naRuntimeError(c, "setlistener() with invalid function argument");
977 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
978 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
979 FGNasalListener *nl = new FGNasalListener(node, code, this,
980 gcSave(code), _listenerId, init, type);
982 node->addChangeListener(nl, init != 0);
984 _listener[_listenerId] = nl;
985 return naNum(_listenerId++);
988 // removelistener(int) extension function. The argument is the id of
989 // a listener as returned by the setlistener() function.
990 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
992 naRef id = argc > 0 ? args[0] : naNil();
993 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
995 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
996 naRuntimeError(c, "removelistener() with invalid listener id");
1000 it->second->_dead = true;
1001 _dead_listener.push_back(it->second);
1002 _listener.erase(it);
1003 return naNum(_listener.size());
1008 // FGNasalListener class.
1010 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1011 FGNasalSys* nasal, int key, int id,
1012 int init, int type) :
1025 if(_type == 0 && !_init)
1029 FGNasalListener::~FGNasalListener()
1031 _node->removeChangeListener(this);
1032 _nas->gcRelease(_gcKey);
1035 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1037 if(_active || _dead) return;
1038 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1041 arg[0] = _nas->propNodeGhost(which);
1042 arg[1] = _nas->propNodeGhost(_node);
1043 arg[2] = mode; // value changed, child added/removed
1044 arg[3] = naNum(_node != which); // child event?
1045 _nas->call(_code, 4, arg, naNil());
1049 void FGNasalListener::valueChanged(SGPropertyNode* node)
1051 if(_type < 2 && node != _node) return; // skip child events
1052 if(_type > 0 || changed(_node) || _init)
1053 call(node, naNum(0));
1058 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1060 if(_type == 2) call(child, naNum(1));
1063 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1065 if(_type == 2) call(child, naNum(-1));
1068 bool FGNasalListener::changed(SGPropertyNode* node)
1070 using namespace simgear;
1071 props::Type type = node->getType();
1072 if(type == props::NONE) return false;
1073 if(type == props::UNSPECIFIED) return true;
1081 long l = node->getLongValue();
1082 result = l != _last_int;
1089 double d = node->getDoubleValue();
1090 result = d != _last_float;
1096 string s = node->getStringValue();
1097 result = s != _last_string;
1106 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
1107 // such a class, then it lets modelLoaded() run the <load> script, and the
1108 // destructor the <unload> script. The latter happens when the model branch
1109 // is removed from the scene graph.
1111 unsigned int FGNasalModelData::_module_id = 0;
1113 void FGNasalModelData::load()
1115 std::stringstream m;
1116 m << "__model" << _module_id++;
1119 SG_LOG(SG_NASAL, SG_DEBUG, "Loading nasal module " << _module.c_str());
1121 const char *s = _load ? _load->getStringValue() : "";
1124 arg[0] = nasalSys->propNodeGhost(_root);
1125 arg[1] = nasalSys->propNodeGhost(_prop);
1126 nasalSys->createModule(_module.c_str(), _path.c_str(), s, strlen(s),
1130 void FGNasalModelData::unload()
1132 if (_module.empty())
1136 SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1137 "without Nasal subsystem present.");
1141 SG_LOG(SG_NASAL, SG_DEBUG, "Unloading nasal module " << _module.c_str());
1145 const char *s = _unload->getStringValue();
1146 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _root);
1149 nasalSys->deleteModule(_module.c_str());
1152 void FGNasalModelDataProxy::modelLoaded(const string& path, SGPropertyNode *prop,
1156 SG_LOG(SG_NASAL, SG_WARN, "Trying to run a <load> script "
1157 "without Nasal subsystem present.");
1164 SGPropertyNode *nasal = prop->getNode("nasal");
1168 SGPropertyNode* load = nasal->getNode("load");
1169 SGPropertyNode* unload = nasal->getNode("unload");
1171 if ((!load) && (!unload))
1174 _data = new FGNasalModelData(_root, path, prop, load, unload);
1176 // register Nasal module to be created and loaded in the main thread.
1177 nasalSys->registerToLoad(_data);
1180 FGNasalModelDataProxy::~FGNasalModelDataProxy()
1182 // when necessary, register Nasal module to be destroyed/unloaded
1183 // in the main thread.
1184 if ((_data.valid())&&(nasalSys))
1185 nasalSys->registerToUnload(_data);
1188 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1190 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1191 _c(naSubContext(c)),
1192 _start_element(argc > 1 ? args[1] : naNil()),
1193 _end_element(argc > 2 ? args[2] : naNil()),
1194 _data(argc > 3 ? args[3] : naNil()),
1195 _pi(argc > 4 ? args[4] : naNil())
1199 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1201 if(naIsNil(_start_element)) return;
1202 naRef attr = naNewHash(_c);
1203 for(int i=0; i<a.size(); i++) {
1204 naRef name = make_string(a.getName(i));
1205 naRef value = make_string(a.getValue(i));
1206 naHash_set(attr, name, value);
1208 call(_start_element, 2, make_string(tag), attr);
1211 void NasalXMLVisitor::endElement(const char* tag)
1213 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1216 void NasalXMLVisitor::data(const char* str, int len)
1218 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1221 void NasalXMLVisitor::pi(const char* target, const char* data)
1223 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1226 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1231 naCall(_c, func, num, args, naNil(), naNil());
1236 naRef NasalXMLVisitor::make_string(const char* s, int n)
1238 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1239 n < 0 ? strlen(s) : n);