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
61 FGNasalSys::~FGNasalSys()
63 // Nasal doesn't have a "destroy context" API yet. :(
64 // Not a problem for a global subsystem that will never be
65 // destroyed. And the context is actually a global, so no memory
66 // is technically leaked (although the GC pool memory obviously
72 bool FGNasalSys::parseAndRun(const char* sourceCode)
74 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
79 naCall(_context, code, 0, 0, naNil(), naNil());
81 if(!naGetError(_context)) return true;
86 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
88 FGNasalScript* script = new FGNasalScript();
89 script->_gcKey = -1; // important, if we delete it on a parse
90 script->_nas = this; // error, don't clobber a real handle!
94 sprintf(buf, "FGNasalScript@%p", script);
98 script->_code = parse(name, src, strlen(src));
99 if(naIsNil(script->_code)) {
104 script->_gcKey = gcSave(script->_code);
108 // Utility. Sets a named key in a hash by C string, rather than nasal
110 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
112 naRef s = naNewString(_context);
113 naStr_fromdata(s, (char*)key, strlen(key));
114 naHash_set(hash, s, val);
117 // The get/setprop functions accept a *list* of strings and walk
118 // through the property tree with them to find the appropriate node.
119 // This allows a Nasal object to hold onto a property path and use it
120 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
121 // is the utility function that walks the property tree.
122 // Future enhancement: support integer arguments to specify array
124 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
126 SGPropertyNode* p = globals->get_props();
128 for(int i=0; i<len; i++) {
130 if(!naIsString(a)) return 0;
131 p = p->getNode(naStr_data(a));
134 } catch (const string& err) {
135 naRuntimeError(c, (char *)err.c_str());
141 // getprop() extension function. Concatenates its string arguments as
142 // property names and returns the value of the specified property. Or
143 // nil if it doesn't exist.
144 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
146 const SGPropertyNode* p = findnode(c, args, argc);
147 if(!p) return naNil();
149 switch(p->getType()) {
150 case SGPropertyNode::BOOL: case SGPropertyNode::INT:
151 case SGPropertyNode::LONG: case SGPropertyNode::FLOAT:
152 case SGPropertyNode::DOUBLE:
153 return naNum(p->getDoubleValue());
155 case SGPropertyNode::STRING:
156 case SGPropertyNode::UNSPECIFIED:
158 naRef nastr = naNewString(c);
159 const char* val = p->getStringValue();
160 naStr_fromdata(nastr, (char*)val, strlen(val));
163 case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
169 // setprop() extension function. Concatenates its string arguments as
170 // property names and sets the value of the specified property to the
172 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
175 char buf[BUFLEN + 1];
179 for(int i=0; i<argc-1; i++) {
180 naRef s = naStringValue(c, args[i]);
181 if(naIsNil(s)) return naNil();
182 strncpy(p, naStr_data(s), buflen);
184 buflen = BUFLEN - (p - buf);
185 if(i < (argc-2) && buflen > 0) {
191 SGPropertyNode* props = globals->get_props();
192 naRef val = args[argc-1];
194 if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
195 else props->setDoubleValue(buf, naNumValue(val).num);
196 } catch (const string& err) {
197 naRuntimeError(c, (char *)err.c_str());
203 // print() extension function. Concatenates and prints its arguments
204 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
205 // make sure it appears. Is there better way to do this?
206 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
209 char buf[BUFLEN + 1];
210 buf[BUFLEN] = 0; // extra nul to handle strncpy brain damage
211 buf[0] = 0; // Zero-length in case there are no arguments
215 for(int i=0; i<n; i++) {
216 naRef s = naStringValue(c, args[i]);
217 if(naIsNil(s)) continue;
218 strncpy(p, naStr_data(s), buflen);
220 buflen = BUFLEN - (p - buf);
221 if(buflen <= 0) break;
223 SG_LOG(SG_GENERAL, SG_ALERT, buf);
228 // fgcommand() extension function. Executes a named command via the
229 // FlightGear command manager. Takes a single property node name as
231 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
233 if(argc < 2 || !naIsString(args[0]) || !naIsGhost(args[1]))
234 naRuntimeError(c, "bad arguments to fgcommand()");
235 naRef cmd = args[0], props = args[1];
236 SGPropertyNode_ptr* node = (SGPropertyNode_ptr*)naGhost_ptr(props);
237 globals->get_commands()->execute(naStr_data(cmd), *node);
242 // settimer(func, dt, simtime) extension function. Falls through to
243 // FGNasalSys::setTimer(). See there for docs.
244 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
246 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
247 nasal->setTimer(argc, args);
251 // setlistener(func, property, bool) extension function. Falls through to
252 // FGNasalSys::setListener(). See there for docs.
253 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
255 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
256 return nasal->setListener(argc, args);
259 // removelistener(int) extension function. Falls through to
260 // FGNasalSys::removeListener(). See there for docs.
261 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
263 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
264 return nasal->removeListener(argc, args);
267 // Returns a ghost handle to the argument to the currently executing
269 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
271 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
272 return nasal->cmdArgGhost();
275 // Sets up a property interpolation. The first argument is either a
276 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
277 // interpolate. The second argument is a vector of pairs of
278 // value/delta numbers.
279 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
281 SGPropertyNode* node;
282 naRef prop = argc > 0 ? args[0] : naNil();
283 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
284 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
287 naRef curve = argc > 1 ? args[1] : naNil();
288 if(!naIsVector(curve)) return naNil();
289 int nPoints = naVec_size(curve) / 2;
290 double* values = new double[nPoints];
291 double* deltas = new double[nPoints];
292 for(int i=0; i<nPoints; i++) {
293 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
294 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
297 ((SGInterpolator*)globals->get_subsystem("interpolator"))
298 ->interpolate(node, nPoints, values, deltas);
303 // This is a better RNG than the one in the default Nasal distribution
304 // (which is based on the C library rand() implementation). It will
306 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
308 return naNum(sg_random());
311 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
317 // Return an array listing of all files in a directory
318 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
320 if(argc != 1 || !naIsString(args[0]))
321 naRuntimeError(c, "bad arguments to directory()");
322 naRef ldir = args[0];
323 ulDir* dir = ulOpenDir(naStr_data(args[0]));
324 if(!dir) return naNil();
325 naRef result = naNewVector(c);
327 while((dent = ulReadDir(dir)))
328 naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
329 strlen(dent->d_name)));
334 // Table of extension functions. Terminate with zeros.
335 static struct { char* name; naCFunction func; } funcs[] = {
336 { "getprop", f_getprop },
337 { "setprop", f_setprop },
338 { "print", f_print },
339 { "_fgcommand", f_fgcommand },
340 { "settimer", f_settimer },
341 { "_setlistener", f_setlistener },
342 { "removelistener", f_removelistener },
343 { "_cmdarg", f_cmdarg },
344 { "_interpolate", f_interpolate },
346 { "srand", f_srand },
347 { "directory", f_directory },
351 naRef FGNasalSys::cmdArgGhost()
353 return propNodeGhost(_cmdArg);
356 void FGNasalSys::init()
360 _context = naNewContext();
362 // Start with globals. Add it to itself as a recursive
363 // sub-reference under the name "globals". This gives client-code
364 // write access to the namespace if someone wants to do something
366 _globals = naStdLib(_context);
367 naSave(_context, _globals);
368 hashset(_globals, "globals", _globals);
370 // Add in the math library under "math"
371 hashset(_globals, "math", naMathLib(_context));
373 // Add in the IO library. Disabled currently until after the
375 // hashset(_globals, "io", naIOLib(_context));
376 // hashset(_globals, "bits", naBitsLib(_context));
378 // Add our custom extension functions:
379 for(i=0; funcs[i].name; i++)
380 hashset(_globals, funcs[i].name,
381 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
383 // And our SGPropertyNode wrapper
384 hashset(_globals, "props", genPropsModule());
386 // Make a "__gcsave" hash to hold the naRef objects which get
387 // passed to handles outside the interpreter (to protect them from
388 // begin garbage-collected).
389 _gcHash = naNewHash(_context);
390 hashset(_globals, "__gcsave", _gcHash);
392 // Now load the various source files in the Nasal directory
393 SGPath p(globals->get_fg_root());
396 ulDir* dir = ulOpenDir(p.c_str());
397 while(dir && (dent = ulReadDir(dir)) != 0) {
399 fullpath.append(dent->d_name);
400 SGPath file(dent->d_name);
401 if(file.extension() != "nas") continue;
402 loadModule(fullpath, file.base().c_str());
406 // Pull scripts out of the property tree, too
407 loadPropertyScripts();
410 // Loads the scripts found under /nasal in the global tree
411 void FGNasalSys::loadPropertyScripts()
413 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
416 for(int i=0; i<nasal->nChildren(); i++) {
417 SGPropertyNode* n = nasal->getChild(i);
419 const char* module = n->getName();
420 if(n->hasChild("module"))
421 module = n->getStringValue("module");
423 // allow multiple files to be specified within in a single
427 bool file_specified = false;
428 while ( (fn = n->getChild("file", j)) != NULL ) {
429 file_specified = true;
430 const char* file = fn->getStringValue();
431 SGPath p(globals->get_fg_root());
433 loadModule(p, module);
437 // Old code which only allowed a single file to be specified per module
439 const char* file = n->getStringValue("file");
440 if(!n->hasChild("file")) file = 0; // Hrm...
442 SGPath p(globals->get_fg_root());
444 loadModule(p, module);
448 const char* src = n->getStringValue("script");
449 if(!n->hasChild("script")) src = 0; // Hrm...
451 createModule(module, n->getPath(), src, strlen(src));
453 if(!file_specified && !src)
454 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
455 "no <file> or <script> defined in " <<
456 "/nasal/" << module);
460 // Logs a runtime error, with stack trace, to the FlightGear log stream
461 void FGNasalSys::logError(naContext context)
463 SG_LOG(SG_NASAL, SG_ALERT,
464 "Nasal runtime error: " << naGetError(context));
465 SG_LOG(SG_NASAL, SG_ALERT,
466 " at " << naStr_data(naGetSourceFile(context, 0)) <<
467 ", line " << naGetLine(context, 0));
468 for(int i=1; i<naStackDepth(context); i++)
469 SG_LOG(SG_NASAL, SG_ALERT,
470 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
471 ", line " << naGetLine(context, i));
474 // Reads a script file, executes it, and places the resulting
475 // namespace into the global namespace under the specified module
477 void FGNasalSys::loadModule(SGPath file, const char* module)
480 char* buf = readfile(file.c_str(), &len);
482 SG_LOG(SG_NASAL, SG_ALERT,
483 "Nasal error: could not read script file " << file.c_str()
484 << " into module " << module);
488 createModule(module, file.c_str(), buf, len);
492 // Parse and run. Save the local variables namespace, as it will
493 // become a sub-object of globals. The optional "arg" argument can be
494 // used to pass an associated property node to the module, which can then
495 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
496 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
497 const char* src, int len, const SGPropertyNode* arg)
499 naRef code = parse(fileName, src, len);
503 // See if we already have a module hash to use. This allows the
504 // user to, for example, add functions to the built-in math
505 // module. Make a new one if necessary.
507 naRef modname = naNewString(_context);
508 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
509 if(!naHash_get(_globals, modname, &locals))
510 locals = naNewHash(_context);
512 _cmdArg = (SGPropertyNode*)arg;
514 naCall(_context, code, 0, 0, naNil(), locals);
515 if(naGetError(_context)) {
519 hashset(_globals, moduleName, locals);
522 void FGNasalSys::deleteModule(const char* moduleName)
524 naRef modname = naNewString(_context);
525 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
527 naHash_delete(_globals, modname);
531 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
534 naRef srcfile = naNewString(_context);
535 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
536 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
538 SG_LOG(SG_NASAL, SG_ALERT,
539 "Nasal parse error: " << naGetError(_context) <<
540 " in "<< filename <<", line " << errLine);
544 // Bind to the global namespace before returning
545 return naBindFunction(_context, code, _globals);
548 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
550 const char* nasal = arg->getStringValue("script");
551 const char* moduleName = arg->getStringValue("module");
552 naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
553 if(naIsNil(code)) return false;
555 naContext c = naNewContext();
556 naRef locals = naNil();
558 naRef modname = naNewString(c);
559 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
560 if(!naHash_get(_globals, modname, &locals))
561 locals = naNewHash(c);
563 // Cache the command argument for inspection via cmdarg(). For
564 // performance reasons, we won't bother with it if the invoked
565 // code doesn't need it.
566 _cmdArg = (SGPropertyNode*)arg;
570 naRef result = naCall(c, code, 0, 0, naNil(), locals);
572 bool error = naGetError(c);
580 // settimer(func, dt, simtime) extension function. The first argument
581 // is a Nasal function to call, the second is a delta time (from now),
582 // in seconds. The third, if present, is a boolean value indicating
583 // that "real world" time (rather than simulator time) is to be used.
585 // Implementation note: the FGTimer objects don't live inside the
586 // garbage collector, so the Nasal handler functions have to be
587 // "saved" somehow lest they be inadvertently cleaned. In this case,
588 // they are inserted into a globals.__gcsave hash and removed on
590 void FGNasalSys::setTimer(int argc, naRef* args)
592 // Extract the handler, delta, and simtime arguments:
593 naRef handler = argc > 0 ? args[0] : naNil();
594 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
597 naRef delta = argc > 1 ? args[1] : naNil();
598 if(naIsNil(delta)) return;
600 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
602 // Generate and register a C++ timer handler
603 NasalTimer* t = new NasalTimer;
604 t->handler = handler;
605 t->gcKey = gcSave(handler);
608 globals->get_event_mgr()->addEvent("NasalTimer",
609 t, &NasalTimer::timerExpired,
613 void FGNasalSys::handleTimer(NasalTimer* t)
615 naCall(_context, t->handler, 0, 0, naNil(), naNil());
616 if(naGetError(_context))
621 int FGNasalSys::gcSave(naRef r)
623 int key = _nextGCKey++;
624 naHash_set(_gcHash, naNum(key), r);
628 void FGNasalSys::gcRelease(int key)
630 naHash_delete(_gcHash, naNum(key));
633 void FGNasalSys::NasalTimer::timerExpired()
635 nasal->handleTimer(this);
639 int FGNasalSys::_listenerId = 0;
641 // setlistener(property, func, bool) extension function. The first argument
642 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
643 // path), the second is a Nasal function, the optional third one a bool.
644 // If the bool is true, then the listener is executed initially. The
645 // setlistener() function returns a unique id number, that can be used
646 // as argument to the removelistener() function.
647 naRef FGNasalSys::setListener(int argc, naRef* args)
649 SGPropertyNode_ptr node;
650 naRef prop = argc > 0 ? args[0] : naNil();
651 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
652 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
655 naRef handler = argc > 1 ? args[1] : naNil();
656 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
659 bool initial = argc > 2 && naTrue(args[2]);
661 FGNasalListener *nl = new FGNasalListener(node, handler, this,
663 node->addChangeListener(nl, initial);
665 _listener[_listenerId] = nl;
666 return naNum(_listenerId++);
669 // removelistener(int) extension function. The argument is the id of
670 // a listener as returned by the setlistener() function.
671 naRef FGNasalSys::removeListener(int argc, naRef* args)
673 naRef id = argc > 0 ? args[0] : naNil();
678 if (_listener.find(i) == _listener.end())
681 FGNasalListener *nl = _listener[i];
682 nl->_node->removeChangeListener(nl);
685 return naNum(_listener.size());
690 // FGNasalListener class.
692 FGNasalListener::FGNasalListener(SGPropertyNode_ptr node, naRef handler,
693 FGNasalSys* nasal, int key) :
702 FGNasalListener::~FGNasalListener()
704 _nas->gcRelease(_gcKey);
707 void FGNasalListener::valueChanged(SGPropertyNode* node)
710 SG_LOG(SG_NASAL, SG_ALERT, "Recursive listener call "
711 "on property " << node->getPath());
715 _nas->_cmdArg = node;
716 naContext c = naNewContext();
718 naCall(c, _handler, 0, 0, naNil(), naNil());
729 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
730 // such a class, then it lets modelLoaded() run the <load> script, and the
731 // destructor the <unload> script. The latter happens when the model branch
732 // is removed from the scene graph.
734 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
737 SGPropertyNode *n = prop->getNode("nasal"), *load;
741 load = n->getNode("load");
742 _unload = n->getNode("unload");
743 if (!load && !_unload)
747 const char *s = load ? load->getStringValue() : "";
748 FGNasalSys *nas = (FGNasalSys *)globals->get_subsystem("nasal");
749 nas->createModule(_module.c_str(), _module.c_str(), s, strlen(s));
752 FGNasalModelData::~FGNasalModelData()
757 FGNasalSys *nas = (FGNasalSys *)globals->get_subsystem("nasal");
759 SG_LOG(SG_NASAL, SG_ALERT, "Trying to run an <unload> script "
760 "without Nasal subsystem present.");
765 const char *s = _unload->getStringValue();
766 nas->createModule(_module.c_str(), _module.c_str(), s, strlen(s));
768 nas->deleteModule(_module.c_str());