13 #include <simgear/nasal/nasal.h>
14 #include <simgear/props/props.hxx>
15 #include <simgear/math/sg_random.h>
16 #include <simgear/misc/sg_path.hxx>
17 #include <simgear/misc/interpolator.hxx>
18 #include <simgear/structure/commands.hxx>
20 #include <Main/globals.hxx>
21 #include <Main/fg_props.hxx>
23 #include "NasalSys.hxx"
25 // Read and return file contents in a single buffer. Note use of
26 // stat() to get the file size. This is a win32 function, believe it
27 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
28 // Text mode brain damage will kill us if we're trying to do bytewise
30 static char* readfile(const char* file, int* lenOut)
33 if(stat(file, &data) != 0) return 0;
34 FILE* f = fopen(file, "rb");
36 char* buf = new char[data.st_size];
37 *lenOut = fread(buf, 1, data.st_size, f);
39 if(*lenOut != data.st_size) {
40 // Shouldn't happen, but warn anyway since it represents a
41 // platform bug and not a typical runtime error (missing file,
43 SG_LOG(SG_NASAL, SG_ALERT,
44 "ERROR in Nasal initialization: " <<
45 "short count returned from fread() of " << file <<
46 ". Check your C library!");
53 FGNasalSys::FGNasalSys()
58 _nextGCKey = 0; // Any value will do
60 _purgeListeners = false;
63 // Does a naCall() in a new context. Wrapped here to make lock
64 // tracking easier. Extension functions are called with the lock, but
65 // we have to release it before making a new naCall(). So rather than
66 // drop the lock in every extension function that might call back into
67 // Nasal, we keep a stack depth counter here and only unlock/lock
68 // around the naCall if it isn't the first one.
69 naRef FGNasalSys::call(naRef code, naRef locals)
71 naContext ctx = naNewContext();
72 if(_callCount) naModUnlock();
74 naRef result = naCall(ctx, code, 0, 0, naNil(), locals);
78 if(_callCount) naModLock();
83 FGNasalSys::~FGNasalSys()
85 map<int, FGNasalListener *>::iterator it, end = _listener.end();
86 for(it = _listener.begin(); it != end; ++it)
89 // Nasal doesn't have a "destroy context" API yet. :(
90 // Not a problem for a global subsystem that will never be
91 // destroyed. And the context is actually a global, so no memory
92 // is technically leaked (although the GC pool memory obviously
98 bool FGNasalSys::parseAndRun(const char* sourceCode)
100 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
108 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
110 FGNasalScript* script = new FGNasalScript();
111 script->_gcKey = -1; // important, if we delete it on a parse
112 script->_nas = this; // error, don't clobber a real handle!
116 sprintf(buf, "FGNasalScript@%p", script);
120 script->_code = parse(name, src, strlen(src));
121 if(naIsNil(script->_code)) {
126 script->_gcKey = gcSave(script->_code);
130 // Utility. Sets a named key in a hash by C string, rather than nasal
132 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
134 naRef s = naNewString(_context);
135 naStr_fromdata(s, (char*)key, strlen(key));
136 naHash_set(hash, s, val);
139 // The get/setprop functions accept a *list* of strings and walk
140 // through the property tree with them to find the appropriate node.
141 // This allows a Nasal object to hold onto a property path and use it
142 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
143 // is the utility function that walks the property tree.
144 // Future enhancement: support integer arguments to specify array
146 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
148 SGPropertyNode* p = globals->get_props();
150 for(int i=0; i<len; i++) {
152 if(!naIsString(a)) return 0;
153 p = p->getNode(naStr_data(a));
156 } catch (const string& err) {
157 naRuntimeError(c, (char *)err.c_str());
163 // getprop() extension function. Concatenates its string arguments as
164 // property names and returns the value of the specified property. Or
165 // nil if it doesn't exist.
166 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
168 const SGPropertyNode* p = findnode(c, args, argc);
169 if(!p) return naNil();
171 switch(p->getType()) {
172 case SGPropertyNode::BOOL: case SGPropertyNode::INT:
173 case SGPropertyNode::LONG: case SGPropertyNode::FLOAT:
174 case SGPropertyNode::DOUBLE:
175 return naNum(p->getDoubleValue());
177 case SGPropertyNode::STRING:
178 case SGPropertyNode::UNSPECIFIED:
180 naRef nastr = naNewString(c);
181 const char* val = p->getStringValue();
182 naStr_fromdata(nastr, (char*)val, strlen(val));
185 case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
191 // setprop() extension function. Concatenates its string arguments as
192 // property names and sets the value of the specified property to the
194 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
197 char buf[BUFLEN + 1];
201 for(int i=0; i<argc-1; i++) {
202 naRef s = naStringValue(c, args[i]);
203 if(naIsNil(s)) return naNil();
204 strncpy(p, naStr_data(s), buflen);
206 buflen = BUFLEN - (p - buf);
207 if(i < (argc-2) && buflen > 0) {
213 SGPropertyNode* props = globals->get_props();
214 naRef val = args[argc-1];
216 if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
218 naRef n = naNumValue(val);
220 naRuntimeError(c, "setprop() value is not string or number");
221 props->setDoubleValue(buf, n.num);
223 } catch (const string& err) {
224 naRuntimeError(c, (char *)err.c_str());
230 // print() extension function. Concatenates and prints its arguments
231 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
232 // make sure it appears. Is there better way to do this?
233 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
236 char buf[BUFLEN + 1];
237 buf[BUFLEN] = 0; // extra nul to handle strncpy brain damage
238 buf[0] = 0; // Zero-length in case there are no arguments
242 for(int i=0; i<n; i++) {
243 naRef s = naStringValue(c, args[i]);
244 if(naIsNil(s)) continue;
245 strncpy(p, naStr_data(s), buflen);
247 buflen = BUFLEN - (p - buf);
248 if(buflen <= 0) break;
250 SG_LOG(SG_GENERAL, SG_ALERT, buf);
255 // fgcommand() extension function. Executes a named command via the
256 // FlightGear command manager. Takes a single property node name as
258 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
260 if(argc < 2 || !naIsString(args[0]) || !naIsGhost(args[1]))
261 naRuntimeError(c, "bad arguments to fgcommand()");
262 naRef cmd = args[0], props = args[1];
263 SGPropertyNode_ptr* node = (SGPropertyNode_ptr*)naGhost_ptr(props);
264 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
267 // settimer(func, dt, simtime) extension function. Falls through to
268 // FGNasalSys::setTimer(). See there for docs.
269 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
271 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
272 nasal->setTimer(argc, args);
276 // setlistener(func, property, bool) extension function. Falls through to
277 // FGNasalSys::setListener(). See there for docs.
278 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
280 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
281 return nasal->setListener(argc, args);
284 // removelistener(int) extension function. Falls through to
285 // FGNasalSys::removeListener(). See there for docs.
286 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
288 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
289 return nasal->removeListener(c, argc, args);
292 // Returns a ghost handle to the argument to the currently executing
294 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
296 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
297 return nasal->cmdArgGhost();
300 // Sets up a property interpolation. The first argument is either a
301 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
302 // interpolate. The second argument is a vector of pairs of
303 // value/delta numbers.
304 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
306 SGPropertyNode* node;
307 naRef prop = argc > 0 ? args[0] : naNil();
308 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
309 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
312 naRef curve = argc > 1 ? args[1] : naNil();
313 if(!naIsVector(curve)) return naNil();
314 int nPoints = naVec_size(curve) / 2;
315 double* values = new double[nPoints];
316 double* deltas = new double[nPoints];
317 for(int i=0; i<nPoints; i++) {
318 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
319 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
322 ((SGInterpolator*)globals->get_subsystem("interpolator"))
323 ->interpolate(node, nPoints, values, deltas);
328 // This is a better RNG than the one in the default Nasal distribution
329 // (which is based on the C library rand() implementation). It will
331 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
333 return naNum(sg_random());
336 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
342 // Return an array listing of all files in a directory
343 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
345 if(argc != 1 || !naIsString(args[0]))
346 naRuntimeError(c, "bad arguments to directory()");
347 naRef ldir = args[0];
348 ulDir* dir = ulOpenDir(naStr_data(args[0]));
349 if(!dir) return naNil();
350 naRef result = naNewVector(c);
352 while((dent = ulReadDir(dir)))
353 naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
354 strlen(dent->d_name)));
359 // Table of extension functions. Terminate with zeros.
360 static struct { char* name; naCFunction func; } funcs[] = {
361 { "getprop", f_getprop },
362 { "setprop", f_setprop },
363 { "print", f_print },
364 { "_fgcommand", f_fgcommand },
365 { "settimer", f_settimer },
366 { "_setlistener", f_setlistener },
367 { "removelistener", f_removelistener },
368 { "_cmdarg", f_cmdarg },
369 { "_interpolate", f_interpolate },
371 { "srand", f_srand },
372 { "directory", f_directory },
376 naRef FGNasalSys::cmdArgGhost()
378 return propNodeGhost(_cmdArg);
381 void FGNasalSys::init()
385 _context = naNewContext();
387 // Start with globals. Add it to itself as a recursive
388 // sub-reference under the name "globals". This gives client-code
389 // write access to the namespace if someone wants to do something
391 _globals = naStdLib(_context);
392 naSave(_context, _globals);
393 hashset(_globals, "globals", _globals);
395 // Add in the math library under "math"
396 hashset(_globals, "math", naMathLib(_context));
398 // Add in the IO library. Disabled currently until after the
400 // hashset(_globals, "io", naIOLib(_context));
401 // hashset(_globals, "bits", naBitsLib(_context));
403 // Add our custom extension functions:
404 for(i=0; funcs[i].name; i++)
405 hashset(_globals, funcs[i].name,
406 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
408 // And our SGPropertyNode wrapper
409 hashset(_globals, "props", genPropsModule());
411 // Make a "__gcsave" hash to hold the naRef objects which get
412 // passed to handles outside the interpreter (to protect them from
413 // begin garbage-collected).
414 _gcHash = naNewHash(_context);
415 hashset(_globals, "__gcsave", _gcHash);
417 // Now load the various source files in the Nasal directory
418 SGPath p(globals->get_fg_root());
421 ulDir* dir = ulOpenDir(p.c_str());
422 while(dir && (dent = ulReadDir(dir)) != 0) {
424 fullpath.append(dent->d_name);
425 SGPath file(dent->d_name);
426 if(file.extension() != "nas") continue;
427 loadModule(fullpath, file.base().c_str());
431 // set signal and remove node to avoid restoring at reinit
432 const char *s = "nasal-dir-initialized";
433 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
434 signal->setBoolValue(s, true);
435 signal->removeChildren(s);
437 // Pull scripts out of the property tree, too
438 loadPropertyScripts();
441 void FGNasalSys::update(double)
443 if(_purgeListeners) {
444 _purgeListeners = false;
445 map<int, FGNasalListener *>::iterator it, end = _listener.end();
446 for(it = _listener.end(); --it != end;) {
447 FGNasalListener *nl = it->second;
456 // Loads the scripts found under /nasal in the global tree
457 void FGNasalSys::loadPropertyScripts()
459 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
462 for(int i=0; i<nasal->nChildren(); i++) {
463 SGPropertyNode* n = nasal->getChild(i);
465 const char* module = n->getName();
466 if(n->hasChild("module"))
467 module = n->getStringValue("module");
469 // allow multiple files to be specified within in a single
473 bool file_specified = false;
474 while ( (fn = n->getChild("file", j)) != NULL ) {
475 file_specified = true;
476 const char* file = fn->getStringValue();
477 SGPath p(globals->get_fg_root());
479 loadModule(p, module);
483 // Old code which only allowed a single file to be specified per module
485 const char* file = n->getStringValue("file");
486 if(!n->hasChild("file")) file = 0; // Hrm...
488 SGPath p(globals->get_fg_root());
490 loadModule(p, module);
494 const char* src = n->getStringValue("script");
495 if(!n->hasChild("script")) src = 0; // Hrm...
497 createModule(module, n->getPath(), src, strlen(src));
499 if(!file_specified && !src)
500 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
501 "no <file> or <script> defined in " <<
502 "/nasal/" << module);
506 // Logs a runtime error, with stack trace, to the FlightGear log stream
507 void FGNasalSys::logError(naContext context)
509 SG_LOG(SG_NASAL, SG_ALERT,
510 "Nasal runtime error: " << naGetError(context));
511 SG_LOG(SG_NASAL, SG_ALERT,
512 " at " << naStr_data(naGetSourceFile(context, 0)) <<
513 ", line " << naGetLine(context, 0));
514 for(int i=1; i<naStackDepth(context); i++)
515 SG_LOG(SG_NASAL, SG_ALERT,
516 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
517 ", line " << naGetLine(context, i));
520 // Reads a script file, executes it, and places the resulting
521 // namespace into the global namespace under the specified module
523 void FGNasalSys::loadModule(SGPath file, const char* module)
526 char* buf = readfile(file.c_str(), &len);
528 SG_LOG(SG_NASAL, SG_ALERT,
529 "Nasal error: could not read script file " << file.c_str()
530 << " into module " << module);
534 createModule(module, file.c_str(), buf, len);
538 // Parse and run. Save the local variables namespace, as it will
539 // become a sub-object of globals. The optional "arg" argument can be
540 // used to pass an associated property node to the module, which can then
541 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
542 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
543 const char* src, int len, const SGPropertyNode* arg)
545 naRef code = parse(fileName, src, len);
549 // See if we already have a module hash to use. This allows the
550 // user to, for example, add functions to the built-in math
551 // module. Make a new one if necessary.
553 naRef modname = naNewString(_context);
554 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
555 if(!naHash_get(_globals, modname, &locals))
556 locals = naNewHash(_context);
558 _cmdArg = (SGPropertyNode*)arg;
561 hashset(_globals, moduleName, locals);
564 void FGNasalSys::deleteModule(const char* moduleName)
566 naRef modname = naNewString(_context);
567 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
568 naHash_delete(_globals, modname);
571 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
574 naRef srcfile = naNewString(_context);
575 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
576 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
578 SG_LOG(SG_NASAL, SG_ALERT,
579 "Nasal parse error: " << naGetError(_context) <<
580 " in "<< filename <<", line " << errLine);
584 // Bind to the global namespace before returning
585 return naBindFunction(_context, code, _globals);
588 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
590 const char* nasal = arg->getStringValue("script");
591 const char* moduleName = arg->getStringValue("module");
592 naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
593 if(naIsNil(code)) return false;
595 naContext c = naNewContext();
596 naRef locals = naNil();
598 naRef modname = naNewString(c);
599 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
600 if(!naHash_get(_globals, modname, &locals))
601 locals = naNewHash(c);
603 // Cache the command argument for inspection via cmdarg(). For
604 // performance reasons, we won't bother with it if the invoked
605 // code doesn't need it.
606 _cmdArg = (SGPropertyNode*)arg;
613 // settimer(func, dt, simtime) extension function. The first argument
614 // is a Nasal function to call, the second is a delta time (from now),
615 // in seconds. The third, if present, is a boolean value indicating
616 // that "real world" time (rather than simulator time) is to be used.
618 // Implementation note: the FGTimer objects don't live inside the
619 // garbage collector, so the Nasal handler functions have to be
620 // "saved" somehow lest they be inadvertently cleaned. In this case,
621 // they are inserted into a globals.__gcsave hash and removed on
623 void FGNasalSys::setTimer(int argc, naRef* args)
625 // Extract the handler, delta, and simtime arguments:
626 naRef handler = argc > 0 ? args[0] : naNil();
627 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
630 naRef delta = argc > 1 ? args[1] : naNil();
631 if(naIsNil(delta)) return;
633 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
635 // Generate and register a C++ timer handler
636 NasalTimer* t = new NasalTimer;
637 t->handler = handler;
638 t->gcKey = gcSave(handler);
641 globals->get_event_mgr()->addEvent("NasalTimer",
642 t, &NasalTimer::timerExpired,
646 void FGNasalSys::handleTimer(NasalTimer* t)
648 call(t->handler, naNil());
652 int FGNasalSys::gcSave(naRef r)
654 int key = _nextGCKey++;
655 naHash_set(_gcHash, naNum(key), r);
659 void FGNasalSys::gcRelease(int key)
661 naHash_delete(_gcHash, naNum(key));
664 void FGNasalSys::NasalTimer::timerExpired()
666 nasal->handleTimer(this);
670 int FGNasalSys::_listenerId = 0;
672 // setlistener(property, func, bool) extension function. The first argument
673 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
674 // path), the second is a Nasal function, the optional third one a bool.
675 // If the bool is true, then the listener is executed initially. The
676 // setlistener() function returns a unique id number, that can be used
677 // as argument to the removelistener() function.
678 naRef FGNasalSys::setListener(int argc, naRef* args)
680 SGPropertyNode_ptr node;
681 naRef prop = argc > 0 ? args[0] : naNil();
682 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
683 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
687 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
690 naRef handler = argc > 1 ? args[1] : naNil();
691 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
694 bool initial = argc > 2 && naTrue(args[2]);
696 FGNasalListener *nl = new FGNasalListener(node, handler, this,
698 node->addChangeListener(nl, initial);
700 _listener[_listenerId] = nl;
701 return naNum(_listenerId++);
704 // removelistener(int) extension function. The argument is the id of
705 // a listener as returned by the setlistener() function.
706 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
708 naRef id = argc > 0 ? args[0] : naNil();
709 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
711 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
712 naRuntimeError(c, "removelistener() with invalid listener id");
716 FGNasalListener *nl = it->second;
719 _purgeListeners = true;
725 return naNum(_listener.size());
730 // FGNasalListener class.
732 FGNasalListener::FGNasalListener(SGPropertyNode_ptr node, naRef handler,
733 FGNasalSys* nasal, int key) :
743 FGNasalListener::~FGNasalListener()
745 _node->removeChangeListener(this);
746 _nas->gcRelease(_gcKey);
749 void FGNasalListener::valueChanged(SGPropertyNode* node)
751 // drop recursive listener calls
756 _nas->_cmdArg = node;
757 _nas->call(_handler, naNil());
764 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
765 // such a class, then it lets modelLoaded() run the <load> script, and the
766 // destructor the <unload> script. The latter happens when the model branch
767 // is removed from the scene graph.
769 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
772 SGPropertyNode *n = prop->getNode("nasal"), *load;
776 load = n->getNode("load");
777 _unload = n->getNode("unload");
778 if(!load && !_unload)
782 const char *s = load ? load->getStringValue() : "";
783 FGNasalSys *nas = (FGNasalSys *)globals->get_subsystem("nasal");
784 nas->createModule(_module.c_str(), _module.c_str(), s, strlen(s));
787 FGNasalModelData::~FGNasalModelData()
792 FGNasalSys *nas = (FGNasalSys *)globals->get_subsystem("nasal");
794 SG_LOG(SG_NASAL, SG_ALERT, "Trying to run an <unload> script "
795 "without Nasal subsystem present.");
800 const char *s = _unload->getStringValue();
801 nas->createModule(_module.c_str(), _module.c_str(), s, strlen(s));
803 nas->deleteModule(_module.c_str());