7 # include <sys/time.h> // gettimeofday
12 #include <sys/types.h>
18 #include <simgear/nasal/nasal.h>
19 #include <simgear/props/props.hxx>
20 #include <simgear/math/sg_random.h>
21 #include <simgear/misc/sg_path.hxx>
22 #include <simgear/misc/interpolator.hxx>
23 #include <simgear/scene/material/mat.hxx>
24 #include <simgear/structure/commands.hxx>
25 #include <simgear/math/sg_geodesy.hxx>
27 #include <Main/globals.hxx>
28 #include <Main/fg_props.hxx>
29 #include <Scenery/scenery.hxx>
31 #include "NasalSys.hxx"
33 static FGNasalSys* nasalSys = 0;
36 // Read and return file contents in a single buffer. Note use of
37 // stat() to get the file size. This is a win32 function, believe it
38 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
39 // Text mode brain damage will kill us if we're trying to do bytewise
41 static char* readfile(const char* file, int* lenOut)
44 if(stat(file, &data) != 0) return 0;
45 FILE* f = fopen(file, "rb");
47 char* buf = new char[data.st_size];
48 *lenOut = fread(buf, 1, data.st_size, f);
50 if(*lenOut != data.st_size) {
51 // Shouldn't happen, but warn anyway since it represents a
52 // platform bug and not a typical runtime error (missing file,
54 SG_LOG(SG_NASAL, SG_ALERT,
55 "ERROR in Nasal initialization: " <<
56 "short count returned from fread() of " << file <<
57 ". Check your C library!");
64 FGNasalSys::FGNasalSys()
70 _nextGCKey = 0; // Any value will do
72 _purgeListeners = false;
75 // Does a naCall() in a new context. Wrapped here to make lock
76 // tracking easier. Extension functions are called with the lock, but
77 // we have to release it before making a new naCall(). So rather than
78 // drop the lock in every extension function that might call back into
79 // Nasal, we keep a stack depth counter here and only unlock/lock
80 // around the naCall if it isn't the first one.
81 naRef FGNasalSys::call(naRef code, naRef locals)
83 naContext ctx = naNewContext();
84 if(_callCount) naModUnlock();
86 naRef result = naCall(ctx, code, 0, 0, naNil(), locals);
90 if(_callCount) naModLock();
95 FGNasalSys::~FGNasalSys()
98 map<int, FGNasalListener *>::iterator it, end = _listener.end();
99 for(it = _listener.begin(); it != end; ++it)
102 naFreeContext(_context);
106 bool FGNasalSys::parseAndRun(const char* sourceCode)
108 naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
116 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
118 FGNasalScript* script = new FGNasalScript();
119 script->_gcKey = -1; // important, if we delete it on a parse
120 script->_nas = this; // error, don't clobber a real handle!
124 sprintf(buf, "FGNasalScript@%p", (void *)script);
128 script->_code = parse(name, src, strlen(src));
129 if(naIsNil(script->_code)) {
134 script->_gcKey = gcSave(script->_code);
138 // Utility. Sets a named key in a hash by C string, rather than nasal
140 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
142 naRef s = naNewString(_context);
143 naStr_fromdata(s, (char*)key, strlen(key));
144 naHash_set(hash, s, val);
147 // The get/setprop functions accept a *list* of strings and walk
148 // through the property tree with them to find the appropriate node.
149 // This allows a Nasal object to hold onto a property path and use it
150 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This
151 // is the utility function that walks the property tree.
152 // Future enhancement: support integer arguments to specify array
154 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
156 SGPropertyNode* p = globals->get_props();
158 for(int i=0; i<len; i++) {
160 if(!naIsString(a)) return 0;
161 p = p->getNode(naStr_data(a));
164 } catch (const string& err) {
165 naRuntimeError(c, (char *)err.c_str());
171 // getprop() extension function. Concatenates its string arguments as
172 // property names and returns the value of the specified property. Or
173 // nil if it doesn't exist.
174 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
176 const SGPropertyNode* p = findnode(c, args, argc);
177 if(!p) return naNil();
179 switch(p->getType()) {
180 case SGPropertyNode::BOOL: case SGPropertyNode::INT:
181 case SGPropertyNode::LONG: case SGPropertyNode::FLOAT:
182 case SGPropertyNode::DOUBLE:
183 return naNum(p->getDoubleValue());
185 case SGPropertyNode::STRING:
186 case SGPropertyNode::UNSPECIFIED:
188 naRef nastr = naNewString(c);
189 const char* val = p->getStringValue();
190 naStr_fromdata(nastr, (char*)val, strlen(val));
193 case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
199 // setprop() extension function. Concatenates its string arguments as
200 // property names and sets the value of the specified property to the
202 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
205 char buf[BUFLEN + 1];
209 for(int i=0; i<argc-1; i++) {
210 naRef s = naStringValue(c, args[i]);
211 if(naIsNil(s)) return naNil();
212 strncpy(p, naStr_data(s), buflen);
214 buflen = BUFLEN - (p - buf);
215 if(i < (argc-2) && buflen > 0) {
221 SGPropertyNode* props = globals->get_props();
222 naRef val = args[argc-1];
224 if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
226 naRef n = naNumValue(val);
228 naRuntimeError(c, "setprop() value is not string or number");
229 props->setDoubleValue(buf, n.num);
231 } catch (const string& err) {
232 naRuntimeError(c, (char *)err.c_str());
238 // print() extension function. Concatenates and prints its arguments
239 // to the FlightGear log. Uses the highest log level (SG_ALERT), to
240 // make sure it appears. Is there better way to do this?
241 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
245 for(int i=0; i<n; i++) {
246 naRef s = naStringValue(c, args[i]);
247 if(naIsNil(s)) continue;
248 buf += naStr_data(s);
250 SG_LOG(SG_GENERAL, SG_ALERT, buf);
251 return naNum(buf.length());
254 // fgcommand() extension function. Executes a named command via the
255 // FlightGear command manager. Takes a single property node name as
257 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
259 naRef cmd = argc > 0 ? args[0] : naNil();
260 naRef props = argc > 1 ? args[1] : naNil();
261 if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
262 naRuntimeError(c, "bad arguments to fgcommand()");
263 SGPropertyNode_ptr tmp, *node;
265 node = (SGPropertyNode_ptr*)naGhost_ptr(props);
267 tmp = new SGPropertyNode();
270 return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
273 // settimer(func, dt, simtime) extension function. Falls through to
274 // FGNasalSys::setTimer(). See there for docs.
275 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
277 nasalSys->setTimer(c, argc, args);
281 // setlistener(func, property, bool) extension function. Falls through to
282 // FGNasalSys::setListener(). See there for docs.
283 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
285 return nasalSys->setListener(c, argc, args);
288 // removelistener(int) extension function. Falls through to
289 // FGNasalSys::removeListener(). See there for docs.
290 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
292 return nasalSys->removeListener(c, argc, args);
295 // Returns a ghost handle to the argument to the currently executing
297 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
299 return nasalSys->cmdArgGhost();
302 // Sets up a property interpolation. The first argument is either a
303 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
304 // interpolate. The second argument is a vector of pairs of
305 // value/delta numbers.
306 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
308 SGPropertyNode* node;
309 naRef prop = argc > 0 ? args[0] : naNil();
310 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
311 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
314 naRef curve = argc > 1 ? args[1] : naNil();
315 if(!naIsVector(curve)) return naNil();
316 int nPoints = naVec_size(curve) / 2;
317 double* values = new double[nPoints];
318 double* deltas = new double[nPoints];
319 for(int i=0; i<nPoints; i++) {
320 values[i] = naNumValue(naVec_get(curve, 2*i)).num;
321 deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
324 ((SGInterpolator*)globals->get_subsystem_mgr()
325 ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
326 ->interpolate(node, nPoints, values, deltas);
331 // This is a better RNG than the one in the default Nasal distribution
332 // (which is based on the C library rand() implementation). It will
334 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
336 return naNum(sg_random());
339 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
345 // Return an array listing of all files in a directory
346 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
348 if(argc != 1 || !naIsString(args[0]))
349 naRuntimeError(c, "bad arguments to directory()");
350 naRef ldir = args[0];
351 ulDir* dir = ulOpenDir(naStr_data(args[0]));
352 if(!dir) return naNil();
353 naRef result = naNewVector(c);
355 while((dent = ulReadDir(dir)))
356 naVec_append(result, naStr_fromdata(naNewString(c), dent->d_name,
357 strlen(dent->d_name)));
363 // parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
365 // <path> ... absolute path to an XML file
366 // <start-tag> ... callback function with two args: tag name, attribute hash
367 // <end-tag> ... callback function with one arg: tag name
368 // <data> ... callback function with one arg: data
369 // <pi> ... callback function with two args: target, data
370 // (pi = "processing instruction")
371 // All four callback functions are optional and default to nil.
372 // The function returns nil on error, and the file name otherwise.
373 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
375 if(argc < 1 || !naIsString(args[0]))
376 naRuntimeError(c, "parsexml(): path argument missing or not a string");
377 if(argc > 5) argc = 5;
378 for(int i=1; i<argc; i++)
379 if(!(naIsNil(args[i]) || naIsFunc(args[i])))
380 naRuntimeError(c, "parsexml(): callback argument not a function");
382 const char* file = naStr_data(args[0]);
383 std::ifstream input(file);
384 NasalXMLVisitor visitor(c, argc, args);
386 readXML(input, visitor);
387 } catch (const sg_exception& e) {
388 string msg = string("parsexml(): file '") + file + "' "
389 + e.getFormattedMessage();
390 naRuntimeError(c, msg.c_str());
396 // Return UNIX epoch time in seconds.
397 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
401 GetSystemTimeAsFileTime(&ft);
402 double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
403 // Converts from 100ns units in 1601 epoch to unix epoch in sec
404 return naNum((t * 1e-7) - 11644473600.0);
408 do { t = time(0); gettimeofday(&td, 0); } while(t != time(0));
409 return naNum(t + 1e-6 * td.tv_usec);
414 // Convert a cartesian point to a geodetic lat/lon/altitude.
415 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
417 double lat, lon, alt, xyz[3];
418 if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
419 for(int i=0; i<3; i++)
420 xyz[i] = naNumValue(args[i]).num;
421 sgCartToGeod(xyz, &lat, &lon, &alt);
422 lat *= SG_RADIANS_TO_DEGREES;
423 lon *= SG_RADIANS_TO_DEGREES;
424 naRef vec = naNewVector(c);
425 naVec_append(vec, naNum(lat));
426 naVec_append(vec, naNum(lon));
427 naVec_append(vec, naNum(alt));
431 // Convert a geodetic lat/lon/altitude to a cartesian point.
432 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
434 if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
435 double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
436 double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
437 double alt = naNumValue(args[2]).num;
439 sgGeodToCart(lat, lon, alt, xyz);
440 naRef vec = naNewVector(c);
441 naVec_append(vec, naNum(xyz[0]));
442 naVec_append(vec, naNum(xyz[1]));
443 naVec_append(vec, naNum(xyz[2]));
447 // For given geodetic point return array with elevation, and a material data
448 // hash, or nil if there's no information available (tile not loaded). If
449 // information about the material isn't available, then nil is returned instead
451 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
453 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
454 if(argc != 2) naRuntimeError(c, "geodinfo() expects 2 arguments: lat, lon");
455 double lat = naNumValue(args[0]).num;
456 double lon = naNumValue(args[1]).num;
458 const SGMaterial *mat;
459 if(!globals->get_scenery()->get_elevation_m(lat, lon, 10000.0, elev, &mat))
461 naRef vec = naNewVector(c);
462 naVec_append(vec, naNum(elev));
463 naRef matdata = naNil();
465 matdata = naNewHash(c);
466 naRef names = naNewVector(c);
467 const vector<string> n = mat->get_names();
468 for(unsigned int i=0; i<n.size(); i++)
469 naVec_append(names, naStr_fromdata(naNewString(c),
470 const_cast<char*>(n[i].c_str()), n[i].size()));
471 HASHSET("names", 5, names);
472 HASHSET("solid", 5, naNum(mat->get_solid()));
473 HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
474 HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
475 HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
476 HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
477 HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
479 naVec_append(vec, matdata);
484 // Table of extension functions. Terminate with zeros.
485 static struct { char* name; naCFunction func; } funcs[] = {
486 { "getprop", f_getprop },
487 { "setprop", f_setprop },
488 { "print", f_print },
489 { "_fgcommand", f_fgcommand },
490 { "settimer", f_settimer },
491 { "_setlistener", f_setlistener },
492 { "removelistener", f_removelistener },
493 { "_cmdarg", f_cmdarg },
494 { "_interpolate", f_interpolate },
496 { "srand", f_srand },
497 { "directory", f_directory },
498 { "parsexml", f_parsexml },
499 { "systime", f_systime },
500 { "carttogeod", f_carttogeod },
501 { "geodtocart", f_geodtocart },
502 { "geodinfo", f_geodinfo },
506 naRef FGNasalSys::cmdArgGhost()
508 return propNodeGhost(_cmdArg);
511 void FGNasalSys::init()
515 _context = naNewContext();
517 // Start with globals. Add it to itself as a recursive
518 // sub-reference under the name "globals". This gives client-code
519 // write access to the namespace if someone wants to do something
521 _globals = naInit_std(_context);
522 naSave(_context, _globals);
523 hashset(_globals, "globals", _globals);
525 hashset(_globals, "math", naInit_math(_context));
526 hashset(_globals, "bits", naInit_bits(_context));
527 hashset(_globals, "io", naInit_io(_context));
528 hashset(_globals, "thread", naInit_thread(_context));
529 hashset(_globals, "utf8", naInit_utf8(_context));
531 // Add our custom extension functions:
532 for(i=0; funcs[i].name; i++)
533 hashset(_globals, funcs[i].name,
534 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
536 // And our SGPropertyNode wrapper
537 hashset(_globals, "props", genPropsModule());
539 // Make a "__gcsave" hash to hold the naRef objects which get
540 // passed to handles outside the interpreter (to protect them from
541 // begin garbage-collected).
542 _gcHash = naNewHash(_context);
543 hashset(_globals, "__gcsave", _gcHash);
545 // Now load the various source files in the Nasal directory
546 SGPath p(globals->get_fg_root());
549 ulDir* dir = ulOpenDir(p.c_str());
550 while(dir && (dent = ulReadDir(dir)) != 0) {
552 fullpath.append(dent->d_name);
553 SGPath file(dent->d_name);
554 if(file.extension() != "nas") continue;
555 loadModule(fullpath, file.base().c_str());
559 // set signal and remove node to avoid restoring at reinit
560 const char *s = "nasal-dir-initialized";
561 SGPropertyNode *signal = fgGetNode("/sim/signals", true);
562 signal->setBoolValue(s, true);
563 signal->removeChildren(s);
565 // Pull scripts out of the property tree, too
566 loadPropertyScripts();
569 void FGNasalSys::update(double)
571 if(_purgeListeners) {
572 _purgeListeners = false;
573 map<int, FGNasalListener *>::iterator it;
574 for(it = _listener.begin(); it != _listener.end();) {
575 FGNasalListener *nl = it->second;
577 _listener.erase(it++);
586 // Loads the scripts found under /nasal in the global tree
587 void FGNasalSys::loadPropertyScripts()
589 SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
592 for(int i=0; i<nasal->nChildren(); i++) {
593 SGPropertyNode* n = nasal->getChild(i);
595 const char* module = n->getName();
596 if(n->hasChild("module"))
597 module = n->getStringValue("module");
599 // allow multiple files to be specified within in a single
603 bool file_specified = false;
604 while ( (fn = n->getChild("file", j)) != NULL ) {
605 file_specified = true;
606 const char* file = fn->getStringValue();
607 SGPath p(globals->get_fg_root());
609 loadModule(p, module);
613 // Old code which only allowed a single file to be specified per module
615 const char* file = n->getStringValue("file");
616 if(!n->hasChild("file")) file = 0; // Hrm...
618 SGPath p(globals->get_fg_root());
620 loadModule(p, module);
624 const char* src = n->getStringValue("script");
625 if(!n->hasChild("script")) src = 0; // Hrm...
627 createModule(module, n->getPath(), src, strlen(src));
629 if(!file_specified && !src)
630 SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
631 "no <file> or <script> defined in " <<
632 "/nasal/" << module);
636 // Logs a runtime error, with stack trace, to the FlightGear log stream
637 void FGNasalSys::logError(naContext context)
639 SG_LOG(SG_NASAL, SG_ALERT,
640 "Nasal runtime error: " << naGetError(context));
641 SG_LOG(SG_NASAL, SG_ALERT,
642 " at " << naStr_data(naGetSourceFile(context, 0)) <<
643 ", line " << naGetLine(context, 0));
644 for(int i=1; i<naStackDepth(context); i++)
645 SG_LOG(SG_NASAL, SG_ALERT,
646 " called from: " << naStr_data(naGetSourceFile(context, i)) <<
647 ", line " << naGetLine(context, i));
650 // Reads a script file, executes it, and places the resulting
651 // namespace into the global namespace under the specified module
653 void FGNasalSys::loadModule(SGPath file, const char* module)
656 char* buf = readfile(file.c_str(), &len);
658 SG_LOG(SG_NASAL, SG_ALERT,
659 "Nasal error: could not read script file " << file.c_str()
660 << " into module " << module);
664 createModule(module, file.c_str(), buf, len);
668 // Parse and run. Save the local variables namespace, as it will
669 // become a sub-object of globals. The optional "arg" argument can be
670 // used to pass an associated property node to the module, which can then
671 // be accessed via cmdarg(). (This is, for example, used by XML dialogs.)
672 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
673 const char* src, int len, const SGPropertyNode* arg)
675 naRef code = parse(fileName, src, len);
679 // See if we already have a module hash to use. This allows the
680 // user to, for example, add functions to the built-in math
681 // module. Make a new one if necessary.
683 naRef modname = naNewString(_context);
684 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
685 if(!naHash_get(_globals, modname, &locals))
686 locals = naNewHash(_context);
688 _cmdArg = (SGPropertyNode*)arg;
691 hashset(_globals, moduleName, locals);
694 void FGNasalSys::deleteModule(const char* moduleName)
696 naRef modname = naNewString(_context);
697 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
698 naHash_delete(_globals, modname);
701 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
704 naRef srcfile = naNewString(_context);
705 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
706 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
708 SG_LOG(SG_NASAL, SG_ALERT,
709 "Nasal parse error: " << naGetError(_context) <<
710 " in "<< filename <<", line " << errLine);
714 // Bind to the global namespace before returning
715 return naBindFunction(_context, code, _globals);
718 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
720 const char* nasal = arg->getStringValue("script");
721 const char* moduleName = arg->getStringValue("module");
722 naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
723 if(naIsNil(code)) return false;
725 // Commands can be run "in" a module. Make sure that module
726 // exists, and set it up as the local variables hash for the
728 naRef locals = naNil();
730 naRef modname = naNewString(_context);
731 naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
732 if(!naHash_get(_globals, modname, &locals)) {
733 locals = naNewHash(_context);
734 naHash_set(_globals, modname, locals);
738 // Cache this command's argument for inspection via cmdarg(). For
739 // performance reasons, we won't bother with it if the invoked
740 // code doesn't need it.
741 _cmdArg = (SGPropertyNode*)arg;
747 // settimer(func, dt, simtime) extension function. The first argument
748 // is a Nasal function to call, the second is a delta time (from now),
749 // in seconds. The third, if present, is a boolean value indicating
750 // that "real world" time (rather than simulator time) is to be used.
752 // Implementation note: the FGTimer objects don't live inside the
753 // garbage collector, so the Nasal handler functions have to be
754 // "saved" somehow lest they be inadvertently cleaned. In this case,
755 // they are inserted into a globals.__gcsave hash and removed on
757 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
759 // Extract the handler, delta, and simtime arguments:
760 naRef handler = argc > 0 ? args[0] : naNil();
761 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
762 naRuntimeError(c, "settimer() with invalid function argument");
766 naRef delta = argc > 1 ? args[1] : naNil();
768 naRuntimeError(c, "settimer() with invalid time argument");
772 bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
774 // Generate and register a C++ timer handler
775 NasalTimer* t = new NasalTimer;
776 t->handler = handler;
777 t->gcKey = gcSave(handler);
780 globals->get_event_mgr()->addEvent("NasalTimer",
781 t, &NasalTimer::timerExpired,
785 void FGNasalSys::handleTimer(NasalTimer* t)
787 call(t->handler, naNil());
791 int FGNasalSys::gcSave(naRef r)
793 int key = _nextGCKey++;
794 naHash_set(_gcHash, naNum(key), r);
798 void FGNasalSys::gcRelease(int key)
800 naHash_delete(_gcHash, naNum(key));
803 void FGNasalSys::NasalTimer::timerExpired()
805 nasal->handleTimer(this);
809 int FGNasalSys::_listenerId = 0;
811 // setlistener(property, func, bool) extension function. The first argument
812 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
813 // path), the second is a Nasal function, the optional third one a bool.
814 // If the bool is true, then the listener is executed initially. The
815 // setlistener() function returns a unique id number, that can be used
816 // as argument to the removelistener() function.
817 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
819 SGPropertyNode_ptr node;
820 naRef prop = argc > 0 ? args[0] : naNil();
821 if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
822 else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
824 naRuntimeError(c, "setlistener() with invalid property argument");
829 SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
832 naRef handler = argc > 1 ? args[1] : naNil();
833 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
834 naRuntimeError(c, "setlistener() with invalid function argument");
838 bool initial = argc > 2 && naTrue(args[2]);
840 FGNasalListener *nl = new FGNasalListener(node, handler, this,
841 gcSave(handler), _listenerId);
842 node->addChangeListener(nl, initial);
844 _listener[_listenerId] = nl;
845 return naNum(_listenerId++);
848 // removelistener(int) extension function. The argument is the id of
849 // a listener as returned by the setlistener() function.
850 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
852 naRef id = argc > 0 ? args[0] : naNil();
853 map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
855 if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
856 naRuntimeError(c, "removelistener() with invalid listener id");
860 FGNasalListener *nl = it->second;
863 _purgeListeners = true;
869 return naNum(_listener.size());
874 // FGNasalListener class.
876 FGNasalListener::FGNasalListener(SGPropertyNode_ptr node, naRef handler,
877 FGNasalSys* nasal, int key, int id) :
888 FGNasalListener::~FGNasalListener()
890 _node->removeChangeListener(this);
891 _nas->gcRelease(_gcKey);
894 void FGNasalListener::valueChanged(SGPropertyNode* node)
896 // drop recursive listener calls
900 SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
902 _nas->_cmdArg = node;
903 _nas->call(_handler, naNil());
910 // FGNasalModelData class. If sgLoad3DModel() is called with a pointer to
911 // such a class, then it lets modelLoaded() run the <load> script, and the
912 // destructor the <unload> script. The latter happens when the model branch
913 // is removed from the scene graph.
915 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
918 SGPropertyNode *n = prop->getNode("nasal"), *load;
922 load = n->getNode("load");
923 _unload = n->getNode("unload");
924 if(!load && !_unload)
929 _module += ':' + _props->getPath();
930 const char *s = load ? load->getStringValue() : "";
931 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
934 FGNasalModelData::~FGNasalModelData()
940 SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
941 "without Nasal subsystem present.");
946 const char *s = _unload->getStringValue();
947 nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _props);
949 nasalSys->deleteModule(_module.c_str());
954 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
956 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
958 _start_element(argc > 1 ? args[1] : naNil()),
959 _end_element(argc > 2 ? args[2] : naNil()),
960 _data(argc > 3 ? args[3] : naNil()),
961 _pi(argc > 4 ? args[4] : naNil())
965 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
967 if(naIsNil(_start_element)) return;
968 naRef attr = naNewHash(_c);
969 for(int i=0; i<a.size(); i++) {
970 naRef name = make_string(a.getName(i));
971 naRef value = make_string(a.getValue(i));
972 naHash_set(attr, name, value);
974 call(_start_element, 2, make_string(tag), attr);
977 void NasalXMLVisitor::endElement(const char* tag)
979 if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
982 void NasalXMLVisitor::data(const char* str, int len)
984 if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
987 void NasalXMLVisitor::pi(const char* target, const char* data)
989 if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
992 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
997 naCall(_c, func, num, args, naNil(), naNil());
1002 naRef NasalXMLVisitor::make_string(const char* s, int n)
1004 return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1005 n < 0 ? strlen(s) : n);