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>
31 #include "NasalSys.hxx"
32 #include "NasalPositioned.hxx"
33 #include "NasalCanvas.hxx"
34 #include "NasalClipboard.hxx"
35 #include "NasalCondition.hxx"
36 #include "NasalString.hxx"
38 #include <Main/globals.hxx>
39 #include <Main/util.hxx>
40 #include <Main/fg_props.hxx>
45 void postinitNasalGUI(naRef globals, naContext c);
47 static FGNasalSys* nasalSys = 0;
49 // Listener class for loading Nasal modules on demand
50 class FGNasalModuleListener : public SGPropertyChangeListener
53 FGNasalModuleListener(SGPropertyNode* node);
55 virtual void valueChanged(SGPropertyNode* node);
58 SGPropertyNode_ptr _node;
61 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
65 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
67 if (_node->getBoolValue("enabled",false)&&
68 !_node->getBoolValue("loaded",true))
70 nasalSys->loadPropertyScripts(_node);
75 // Read and return file contents in a single buffer. Note use of
76 // stat() to get the file size. This is a win32 function, believe it
77 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
78 // Text mode brain damage will kill us if we're trying to do bytewise
80 static char* readfile(const char* file, int* lenOut)
83 if(stat(file, &data) != 0) return 0;
84 FILE* f = fopen(file, "rb");
86 char* buf = new char[data.st_size];
87 *lenOut = fread(buf, 1, data.st_size, f);
89 if(*lenOut != data.st_size) {
90 // Shouldn't happen, but warn anyway since it represents a
91 // platform bug and not a typical runtime error (missing file,
93 SG_LOG(SG_NASAL, SG_ALERT,
94 "ERROR in Nasal initialization: " <<
95 "short count returned from fread() of " << file <<
96 ". Check your C library!");
103 FGNasalSys::FGNasalSys()
110 _nextGCKey = 0; // Any value will do
114 // Utility. Sets a named key in a hash by C string, rather than nasal
116 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
118 naRef s = naNewString(_context);
119 naStr_fromdata(s, (char*)key, strlen(key));
120 naHash_set(hash, s, val);
123 void FGNasalSys::globalsSet(const char* key, naRef val)
125 hashset(_globals, key, val);
128 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
130 return callMethod(code, naNil(), argc, args, locals);
133 // Does a naCall() in a new context. Wrapped here to make lock
134 // tracking easier. Extension functions are called with the lock, but
135 // we have to release it before making a new naCall(). So rather than
136 // drop the lock in every extension function that might call back into
137 // Nasal, we keep a stack depth counter here and only unlock/lock
138 // around the naCall if it isn't the first one.
140 naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals)
142 naContext ctx = naNewContext();
143 if(_callCount) naModUnlock();
145 naRef result = naCall(ctx, code, argc, args, self, locals);
149 if(_callCount) naModLock();
154 FGNasalSys::~FGNasalSys()
157 map<int, FGNasalListener *>::iterator it, end = _listener.end();
158 for(it = _listener.begin(); it != end; ++it)
161 naFreeContext(_context);
166 bool FGNasalSys::parseAndRun(const char* sourceCode)
168 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
172 call(code, 0, 0, naNil());
176 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
178 FGNasalScript* script = new FGNasalScript();
179 script->_gcKey = -1; // important, if we delete it on a parse
180 script->_nas = this; // error, don't clobber a real handle!
184 sprintf(buf, "FGNasalScript@%p", (void *)script);
188 script->_code = parse(name, src, strlen(src));
189 if(naIsNil(script->_code)) {
194 script->_gcKey = gcSave(script->_code);
198 // The get/setprop functions accept a *list* of strings and walk
199 // through the property tree with them to find the appropriate node.
200 // This allows a Nasal object to hold onto a property path and use it
201 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
202 // is the utility function that walks the property tree.
203 // Future enhancement: support integer arguments to specify array
205 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
207 SGPropertyNode* p = globals->get_props();
209 for(int i=0; i<len; i++) {
211 if(!naIsString(a)) return 0;
212 p = p->getNode(naStr_data(a));
215 } catch (const string& err) {
216 naRuntimeError(c, (char *)err.c_str());
222 // getprop() extension function. Concatenates its string arguments as
223 // property names and returns the value of the specified property. Or
224 // nil if it doesn't exist.
225 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
227 using namespace simgear;
228 const SGPropertyNode* p = findnode(c, args, argc);
229 if(!p) return naNil();
231 switch(p->getType()) {
232 case props::BOOL: case props::INT:
233 case props::LONG: case props::FLOAT:
236 double dv = p->getDoubleValue();
237 if (SGMisc<double>::isNaN(dv)) {
238 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
246 case props::UNSPECIFIED:
248 naRef nastr = naNewString(c);
249 const char* val = p->getStringValue();
250 naStr_fromdata(nastr, (char*)val, strlen(val));
253 case props::ALIAS: // <--- FIXME, recurse?
259 // setprop() extension function. Concatenates its string arguments as
260 // property names and sets the value of the specified property to the
262 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
265 char buf[BUFLEN + 1];
269 if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
270 for(int i=0; i<argc-1; i++) {
271 naRef s = naStringValue(c, args[i]);
272 if(naIsNil(s)) return naNil();
273 strncpy(p, naStr_data(s), buflen);
275 buflen = BUFLEN - (p - buf);
276 if(i < (argc-2) && buflen > 0) {
282 SGPropertyNode* props = globals->get_props();
283 naRef val = args[argc-1];
286 if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
288 naRef n = naNumValue(val);
290 naRuntimeError(c, "setprop() value is not string or number");
292 if (SGMisc<double>::isNaN(n.num)) {
293 naRuntimeError(c, "setprop() passed a NaN");
296 result = props->setDoubleValue(buf, n.num);
298 } catch (const string& err) {
299 naRuntimeError(c, (char *)err.c_str());
301 return naNum(result);
305 // print() extension function. Concatenates and prints its arguments
306 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
307 // make sure it appears. Is there better way to do this?
308 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
312 for(int i=0; i<n; i++) {
313 naRef s = naStringValue(c, args[i]);
314 if(naIsNil(s)) continue;
315 buf += naStr_data(s);
317 SG_LOG(SG_NASAL, SG_ALERT, buf);
318 return naNum(buf.length());
321 // logprint() extension function. Same as above, all arguments after the
322 // first argument are concatenated. Argument 0 is the log-level, matching
324 static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
327 naRuntimeError(c, "no prioirty argument to logprint()");
329 naRef priority = args[0];
332 for(int i=1; i<n; i++) {
333 naRef s = naStringValue(c, args[i]);
334 if(naIsNil(s)) continue;
335 buf += naStr_data(s);
337 SG_LOG(SG_NASAL, (sgDebugPriority)(int) priority.num, buf);
338 return naNum(buf.length());
342 // fgcommand() extension function. Executes a named command via the
343 // FlightGear command manager. Takes a single property node name as
345 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
347 naRef cmd = argc > 0 ? args[0] : naNil();
348 naRef props = argc > 1 ? args[1] : naNil();
349 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
350 naRuntimeError(c, "bad arguments to fgcommand()");
351 SGPropertyNode_ptr tmp, *node;
353 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
355 tmp = new SGPropertyNode();
358 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
361 // settimer(func, dt, simtime) extension function. Falls through to
362 // FGNasalSys::setTimer(). See there for docs.
363 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
365 nasalSys->setTimer(c, argc, args);
369 // setlistener(func, property, bool) extension function. Falls through to
370 // FGNasalSys::setListener(). See there for docs.
371 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
373 return nasalSys->setListener(c, argc, args);
376 // removelistener(int) extension function. Falls through to
377 // FGNasalSys::removeListener(). See there for docs.
378 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
380 return nasalSys->removeListener(c, argc, args);
383 // Returns a ghost handle to the argument to the currently executing
385 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
387 return nasalSys->cmdArgGhost();
390 // Sets up a property interpolation. The first argument is either a
391 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
392 // interpolate. The second argument is a vector of pairs of
393 // value/delta numbers.
394 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
396 SGPropertyNode* node;
397 naRef prop = argc > 0 ? args[0] : naNil();
398 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
399 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
402 naRef curve = argc > 1 ? args[1] : naNil();
403 if(!naIsVector(curve)) return naNil();
404 int nPoints = naVec_size(curve) / 2;
405 double* values = new double[nPoints];
406 double* deltas = new double[nPoints];
407 for(int i=0; i<nPoints; i++) {
408 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
409 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
412 ((SGInterpolator*)globals->get_subsystem_mgr()
413 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
414 ->interpolate(node, nPoints, values, deltas);
421 // This is a better RNG than the one in the default Nasal distribution
422 // (which is based on the C library rand() implementation). It will
424 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
426 return naNum(sg_random());
429 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
435 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
441 // Return an array listing of all files in a directory
442 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
444 if(argc != 1 || !naIsString(args[0]))
445 naRuntimeError(c, "bad arguments to directory()");
447 simgear::Dir d(SGPath(naStr_data(args[0])));
448 if(!d.exists()) return naNil();
449 naRef result = naNewVector(c);
451 simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
452 for (unsigned int i=0; i<paths.size(); ++i) {
453 std::string p = paths[i].file();
454 naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
461 * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
463 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
465 if(argc != 1 || !naIsString(args[0]))
466 naRuntimeError(c, "bad arguments to resolveDataPath()");
468 SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
469 const char* pdata = p.c_str();
470 return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
474 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
476 // <path> ... absolute path to an XML file
477 // <start-tag> ... callback function with two args: tag name, attribute hash
478 // <end-tag> ... callback function with one arg: tag name
479 // <data> ... callback function with one arg: data
480 // <pi> ... callback function with two args: target, data
481 // (pi = "processing instruction")
482 // All four callback functions are optional and default to nil.
483 // The function returns nil on error, or the validated file name otherwise.
484 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
486 if(argc < 1 || !naIsString(args[0]))
487 naRuntimeError(c, "parsexml(): path argument missing or not a string");
488 if(argc > 5) argc = 5;
489 for(int i=1; i<argc; i++)
490 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
491 naRuntimeError(c, "parsexml(): callback argument not a function");
493 const char* file = fgValidatePath(naStr_data(args[0]), false);
495 naRuntimeError(c, "parsexml(): reading '%s' denied "
496 "(unauthorized access)", naStr_data(args[0]));
499 std::ifstream input(file);
500 NasalXMLVisitor visitor(c, argc, args);
502 readXML(input, visitor);
503 } catch (const sg_exception& e) {
504 naRuntimeError(c, "parsexml(): file '%s' %s",
505 file, e.getFormattedMessage().c_str());
508 return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
511 // Return UNIX epoch time in seconds.
512 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
516 GetSystemTimeAsFileTime(&ft);
517 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
518 // Converts from 100ns units in 1601 epoch to unix epoch in sec
519 return naNum((t * 1e-7) - 11644473600.0);
522 gettimeofday(&td, 0);
523 return naNum(td.tv_sec + 1e-6 * td.tv_usec);
527 // Table of extension functions. Terminate with zeros.
528 static struct { const char* name; naCFunction func; } funcs[] = {
529 { "getprop", f_getprop },
530 { "setprop", f_setprop },
531 { "print", f_print },
532 { "logprint", f_logprint },
533 { "_fgcommand", f_fgcommand },
534 { "settimer", f_settimer },
535 { "_setlistener", f_setlistener },
536 { "removelistener", f_removelistener },
537 { "_cmdarg", f_cmdarg },
538 { "_interpolate", f_interpolate },
540 { "srand", f_srand },
541 { "abort", f_abort },
542 { "directory", f_directory },
543 { "resolvepath", f_resolveDataPath },
544 { "parsexml", f_parsexml },
545 { "systime", f_systime },
549 naRef FGNasalSys::cmdArgGhost()
551 return propNodeGhost(_cmdArg);
554 void FGNasalSys::init()
558 _context = naNewContext();
560 // Start with globals. Add it to itself as a recursive
561 // sub-reference under the name "globals". This gives client-code
562 // write access to the namespace if someone wants to do something
564 _globals = naInit_std(_context);
565 naSave(_context, _globals);
566 hashset(_globals, "globals", _globals);
568 hashset(_globals, "math", naInit_math(_context));
569 hashset(_globals, "bits", naInit_bits(_context));
570 hashset(_globals, "io", naInit_io(_context));
571 hashset(_globals, "thread", naInit_thread(_context));
572 hashset(_globals, "utf8", naInit_utf8(_context));
574 // Add our custom extension functions:
575 for(i=0; funcs[i].name; i++)
576 hashset(_globals, funcs[i].name,
577 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
579 // And our SGPropertyNode wrapper
580 hashset(_globals, "props", genPropsModule());
582 // Make a "__gcsave" hash to hold the naRef objects which get
583 // passed to handles outside the interpreter (to protect them from
584 // begin garbage-collected).
585 _gcHash = naNewHash(_context);
586 hashset(_globals, "__gcsave", _gcHash);
588 // Add string methods
589 _string = naInit_string(_context);
590 naSave(_context, _string);
591 initNasalString(_globals, _string, _context, _gcHash);
593 initNasalPositioned(_globals, _context, _gcHash);
594 NasalClipboard::init(this);
595 initNasalCanvas(_globals, _context, _gcHash);
596 initNasalCondition(_globals, _context, _gcHash);
598 // Now load the various source files in the Nasal directory
599 simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
600 loadScriptDirectory(nasalDir);
602 // Add modules in Nasal subdirectories to property tree
603 simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
604 simgear::Dir::NO_DOT_OR_DOTDOT, "");
605 for (unsigned int i=0; i<directories.size(); ++i) {
606 simgear::Dir dir(directories[i]);
607 simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
608 addModule(directories[i].file(), scripts);
611 // set signal and remove node to avoid restoring at reinit
612 const char *s = "nasal-dir-initialized";
613 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
614 signal->setBoolValue(s, true);
615 signal->removeChildren(s, false);
617 // Pull scripts out of the property tree, too
618 loadPropertyScripts();
620 // now Nasal modules are loaded, we can do some delayed work
621 postinitNasalPositioned(_globals, _context);
622 postinitNasalGUI(_globals, _context);
625 void FGNasalSys::update(double)
627 if( NasalClipboard::getInstance() )
628 NasalClipboard::getInstance()->update();
630 if(!_dead_listener.empty()) {
631 vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
632 for(it = _dead_listener.begin(); it != end; ++it) delete *it;
633 _dead_listener.clear();
636 if (!_loadList.empty())
638 // process Nasal load hook (only one per update loop to avoid excessive lags)
639 _loadList.pop()->load();
642 if (!_unloadList.empty())
644 // process pending Nasal unload hooks after _all_ load hooks were processed
645 // (only unload one per update loop to avoid excessive lags)
646 _unloadList.pop()->unload();
649 // The global context is a legacy thing. We use dynamically
650 // created contexts for naCall() now, so that we can call them
651 // recursively. But there are still spots that want to use it for
652 // naNew*() calls, which end up leaking memory because the context
653 // only clears out its temporary vector when it's *used*. So just
654 // junk it and fetch a new/reinitialized one every frame. This is
655 // clumsy: the right solution would use the dynamic context in all
656 // cases and eliminate _context entirely. But that's more work,
657 // and this works fine (yes, they say "New" and "Free", but
658 // they're very fast, just trust me). -Andy
659 naFreeContext(_context);
660 _context = naNewContext();
663 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
665 return p1.file() < p2.file();
668 // Loads all scripts in given directory
669 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
671 simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
672 // Note: simgear::Dir already reports file entries in a deterministic order,
673 // so a fixed loading sequence is guaranteed (same for every user)
674 for (unsigned int i=0; i<scripts.size(); ++i) {
675 SGPath fullpath(scripts[i]);
676 SGPath file = fullpath.file();
677 loadModule(fullpath, file.base().c_str());
681 // Create module with list of scripts
682 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
684 if (scripts.size()>0)
686 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
687 SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
688 for (unsigned int i=0; i<scripts.size(); ++i) {
689 SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
690 pFileNode->setStringValue(scripts[i].c_str());
692 if (!module_node->hasChild("enabled",0))
694 SGPropertyNode* node = module_node->getChild("enabled",0,true);
695 node->setBoolValue(true);
696 node->setAttribute(SGPropertyNode::USERARCHIVE,true);
701 // Loads the scripts found under /nasal in the global tree
702 void FGNasalSys::loadPropertyScripts()
704 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
707 for(int i=0; i<nasal->nChildren(); i++)
709 SGPropertyNode* n = nasal->getChild(i);
710 loadPropertyScripts(n);
714 // Loads the scripts found under /nasal in the global tree
715 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
717 bool is_loaded = false;
719 const char* module = n->getName();
720 if(n->hasChild("module"))
721 module = n->getStringValue("module");
722 if (n->getBoolValue("enabled",true))
724 // allow multiple files to be specified within a single
728 bool file_specified = false;
730 while((fn = n->getChild("file", j)) != NULL) {
731 file_specified = true;
732 const char* file = fn->getStringValue();
734 if (!p.isAbsolute() || !p.exists())
736 p = globals->resolve_maybe_aircraft_path(file);
739 SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
740 file << "' for module '" << module << "'.");
743 ok &= p.isNull() ? false : loadModule(p, module);
747 const char* src = n->getStringValue("script");
748 if(!n->hasChild("script")) src = 0; // Hrm...
750 createModule(module, n->getPath().c_str(), src, strlen(src));
752 if(!file_specified && !src)
754 // module no longer exists - clear the archived "enable" flag
755 n->setAttribute(SGPropertyNode::USERARCHIVE,false);
756 SGPropertyNode* node = n->getChild("enabled",0,false);
758 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
760 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
761 "no <file> or <script> defined in " <<
762 "/nasal/" << module);
769 SGPropertyNode* enable = n->getChild("enabled");
772 FGNasalModuleListener* listener = new FGNasalModuleListener(n);
773 enable->addChangeListener(listener, false);
776 SGPropertyNode* loaded = n->getChild("loaded",0,true);
777 loaded->setAttribute(SGPropertyNode::PRESERVE,true);
778 loaded->setBoolValue(is_loaded);
781 // Logs a runtime error, with stack trace, to the FlightGear log stream
782 void FGNasalSys::logError(naContext context)
784 SG_LOG(SG_NASAL, SG_ALERT,
785 "Nasal runtime error: " << naGetError(context));
786 SG_LOG(SG_NASAL, SG_ALERT,
787 " at " << naStr_data(naGetSourceFile(context, 0)) <<
788 ", line " << naGetLine(context, 0));
789 for(int i=1; i<naStackDepth(context); i++)
790 SG_LOG(SG_NASAL, SG_ALERT,
791 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
792 ", line " << naGetLine(context, i));
795 // Reads a script file, executes it, and places the resulting
796 // namespace into the global namespace under the specified module
798 bool FGNasalSys::loadModule(SGPath file, const char* module)
801 char* buf = readfile(file.c_str(), &len);
803 SG_LOG(SG_NASAL, SG_ALERT,
804 "Nasal error: could not read script file " << file.c_str()
805 << " into module " << module);
809 bool ok = createModule(module, file.c_str(), buf, len);
814 // Parse and run. Save the local variables namespace, as it will
815 // become a sub-object of globals. The optional "arg" argument can be
816 // used to pass an associated property node to the module, which can then
817 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
818 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
819 const char* src, int len,
820 const SGPropertyNode* cmdarg,
821 int argc, naRef* args)
823 naRef code = parse(fileName, src, len);
827 // See if we already have a module hash to use. This allows the
828 // user to, for example, add functions to the built-in math
829 // module. Make a new one if necessary.
831 naRef modname = naNewString(_context);
832 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
833 if(!naHash_get(_globals, modname, &locals))
834 locals = naNewHash(_context);
836 _cmdArg = (SGPropertyNode*)cmdarg;
838 call(code, argc, args, locals);
839 hashset(_globals, moduleName, locals);
843 void FGNasalSys::deleteModule(const char* moduleName)
845 naRef modname = naNewString(_context);
846 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
847 naHash_delete(_globals, modname);
850 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
853 naRef srcfile = naNewString(_context);
854 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
855 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
857 SG_LOG(SG_NASAL, SG_ALERT,
858 "Nasal parse error: " << naGetError(_context) <<
859 " in "<< filename <<", line " << errLine);
863 // Bind to the global namespace before returning
864 return naBindFunction(_context, code, _globals);
867 bool FGNasalSys::handleCommand( const char* moduleName,
868 const char* fileName,
870 const SGPropertyNode* arg )
872 naRef code = parse(fileName, src, strlen(src));
873 if(naIsNil(code)) return false;
875 // Commands can be run "in" a module. Make sure that module
876 // exists, and set it up as the local variables hash for the
878 naRef locals = naNil();
880 naRef modname = naNewString(_context);
881 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
882 if(!naHash_get(_globals, modname, &locals)) {
883 locals = naNewHash(_context);
884 naHash_set(_globals, modname, locals);
888 // Cache this command's argument for inspection via cmdarg(). For
889 // performance reasons, we won't bother with it if the invoked
890 // code doesn't need it.
891 _cmdArg = (SGPropertyNode*)arg;
893 call(code, 0, 0, locals);
897 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
899 const char* src = arg->getStringValue("script");
900 const char* moduleName = arg->getStringValue("module");
902 return handleCommand( moduleName,
903 arg ? arg->getPath(true).c_str() : moduleName,
908 // settimer(func, dt, simtime) extension function. The first argument
909 // is a Nasal function to call, the second is a delta time (from now),
910 // in seconds. The third, if present, is a boolean value indicating
911 // that "real world" time (rather than simulator time) is to be used.
913 // Implementation note: the FGTimer objects don't live inside the
914 // garbage collector, so the Nasal handler functions have to be
915 // "saved" somehow lest they be inadvertently cleaned. In this case,
916 // they are inserted into a globals.__gcsave hash and removed on
918 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
920 // Extract the handler, delta, and simtime arguments:
921 naRef handler = argc > 0 ? args[0] : naNil();
922 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
923 naRuntimeError(c, "settimer() with invalid function argument");
927 naRef delta = argc > 1 ? args[1] : naNil();
929 naRuntimeError(c, "settimer() with invalid time argument");
933 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
935 // Generate and register a C++ timer handler
936 NasalTimer* t = new NasalTimer;
937 t->handler = handler;
938 t->gcKey = gcSave(handler);
941 globals->get_event_mgr()->addEvent("NasalTimer",
942 t, &NasalTimer::timerExpired,
946 void FGNasalSys::handleTimer(NasalTimer* t)
948 call(t->handler, 0, 0, naNil());
952 int FGNasalSys::gcSave(naRef r)
954 int key = _nextGCKey++;
955 naHash_set(_gcHash, naNum(key), r);
959 void FGNasalSys::gcRelease(int key)
961 naHash_delete(_gcHash, naNum(key));
964 void FGNasalSys::NasalTimer::timerExpired()
966 nasal->handleTimer(this);
970 int FGNasalSys::_listenerId = 0;
972 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
973 // Attaches a callback function to a property (specified as a global
974 // property path string or a SGPropertyNode_ptr* ghost). If the third,
975 // optional argument (default=0) is set to 1, then the function is also
976 // called initially. If the fourth, optional argument is set to 0, then the
977 // function is only called when the property node value actually changes.
978 // Otherwise it's called independent of the value whenever the node is
979 // written to (default). The setlistener() function returns a unique
980 // id number, which is to be used as argument to the removelistener()
982 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
984 SGPropertyNode_ptr node;
985 naRef prop = argc > 0 ? args[0] : naNil();
986 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
987 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
989 naRuntimeError(c, "setlistener() with invalid property argument");
994 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
997 naRef code = argc > 1 ? args[1] : naNil();
998 if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
999 naRuntimeError(c, "setlistener() with invalid function argument");
1003 int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1004 int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1005 FGNasalListener *nl = new FGNasalListener(node, code, this,
1006 gcSave(code), _listenerId, init, type);
1008 node->addChangeListener(nl, init != 0);
1010 _listener[_listenerId] = nl;
1011 return naNum(_listenerId++);
1014 // removelistener(int) extension function. The argument is the id of
1015 // a listener as returned by the setlistener() function.
1016 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1018 naRef id = argc > 0 ? args[0] : naNil();
1019 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1021 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1022 naRuntimeError(c, "removelistener() with invalid listener id");
1026 it->second->_dead = true;
1027 _dead_listener.push_back(it->second);
1028 _listener.erase(it);
1029 return naNum(_listener.size());
1034 // FGNasalListener class.
1036 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1037 FGNasalSys* nasal, int key, int id,
1038 int init, int type) :
1051 if(_type == 0 && !_init)
1055 FGNasalListener::~FGNasalListener()
1057 _node->removeChangeListener(this);
1058 _nas->gcRelease(_gcKey);
1061 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1063 if(_active || _dead) return;
1064 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1067 arg[0] = _nas->propNodeGhost(which);
1068 arg[1] = _nas->propNodeGhost(_node);
1069 arg[2] = mode; // value changed, child added/removed
1070 arg[3] = naNum(_node != which); // child event?
1071 _nas->call(_code, 4, arg, naNil());
1075 void FGNasalListener::valueChanged(SGPropertyNode* node)
1077 if(_type < 2 && node != _node) return; // skip child events
1078 if(_type > 0 || changed(_node) || _init)
1079 call(node, naNum(0));
1084 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1086 if(_type == 2) call(child, naNum(1));
1089 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1091 if(_type == 2) call(child, naNum(-1));
1094 bool FGNasalListener::changed(SGPropertyNode* node)
1096 using namespace simgear;
1097 props::Type type = node->getType();
1098 if(type == props::NONE) return false;
1099 if(type == props::UNSPECIFIED) return true;
1107 long l = node->getLongValue();
1108 result = l != _last_int;
1115 double d = node->getDoubleValue();
1116 result = d != _last_float;
1122 string s = node->getStringValue();
1123 result = s != _last_string;
1132 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
1133 // such a class, then it lets modelLoaded() run the <load> script, and the
1134 // destructor the <unload> script. The latter happens when the model branch
1135 // is removed from the scene graph.
1137 unsigned int FGNasalModelData::_module_id = 0;
1139 void FGNasalModelData::load()
1141 std::stringstream m;
1142 m << "__model" << _module_id++;
1145 SG_LOG(SG_NASAL, SG_DEBUG, "Loading nasal module " << _module.c_str());
1147 const char *s = _load ? _load->getStringValue() : "";
1150 arg[0] = nasalSys->propNodeGhost(_root);
1151 arg[1] = nasalSys->propNodeGhost(_prop);
1152 nasalSys->createModule(_module.c_str(), _path.c_str(), s, strlen(s),
1156 void FGNasalModelData::unload()
1158 if (_module.empty())
1162 SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1163 "without Nasal subsystem present.");
1167 SG_LOG(SG_NASAL, SG_DEBUG, "Unloading nasal module " << _module.c_str());
1171 const char *s = _unload->getStringValue();
1172 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _root);
1175 nasalSys->deleteModule(_module.c_str());
1178 void FGNasalModelDataProxy::modelLoaded(const string& path, SGPropertyNode *prop,
1182 SG_LOG(SG_NASAL, SG_WARN, "Trying to run a <load> script "
1183 "without Nasal subsystem present.");
1190 SGPropertyNode *nasal = prop->getNode("nasal");
1194 SGPropertyNode* load = nasal->getNode("load");
1195 SGPropertyNode* unload = nasal->getNode("unload");
1197 if ((!load) && (!unload))
1200 _data = new FGNasalModelData(_root, path, prop, load, unload);
1202 // register Nasal module to be created and loaded in the main thread.
1203 nasalSys->registerToLoad(_data);
1206 FGNasalModelDataProxy::~FGNasalModelDataProxy()
1208 // when necessary, register Nasal module to be destroyed/unloaded
1209 // in the main thread.
1210 if ((_data.valid())&&(nasalSys))
1211 nasalSys->registerToUnload(_data);
1214 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1216 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1217 _c(naSubContext(c)),
1218 _start_element(argc > 1 ? args[1] : naNil()),
1219 _end_element(argc > 2 ? args[2] : naNil()),
1220 _data(argc > 3 ? args[3] : naNil()),
1221 _pi(argc > 4 ? args[4] : naNil())
1225 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1227 if(naIsNil(_start_element)) return;
1228 naRef attr = naNewHash(_c);
1229 for(int i=0; i<a.size(); i++) {
1230 naRef name = make_string(a.getName(i));
1231 naRef value = make_string(a.getValue(i));
1232 naHash_set(attr, name, value);
1234 call(_start_element, 2, make_string(tag), attr);
1237 void NasalXMLVisitor::endElement(const char* tag)
1239 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1242 void NasalXMLVisitor::data(const char* str, int len)
1244 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1247 void NasalXMLVisitor::pi(const char* target, const char* data)
1249 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1252 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1257 naCall(_c, func, num, args, naNil(), naNil());
1262 naRef NasalXMLVisitor::make_string(const char* s, int n)
1264 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1265 n < 0 ? strlen(s) : n);