]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
Expose a radio function (receiveBeacon) to the Nasal subsystem
[flightgear.git] / src / Scripting / NasalSys.cxx
1
2 #ifdef HAVE_CONFIG_H
3 #  include "config.h"
4 #endif
5
6 #ifdef HAVE_SYS_TIME_H
7 #  include <sys/time.h>  // gettimeofday
8 #endif
9
10 #include <string.h>
11 #include <stdio.h>
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <fstream>
15 #include <sstream>
16
17 #include <simgear/nasal/nasal.h>
18 #include <simgear/props/props.hxx>
19 #include <simgear/math/sg_random.h>
20 #include <simgear/misc/sg_path.hxx>
21 #include <simgear/misc/sg_dir.hxx>
22 #include <simgear/misc/interpolator.hxx>
23 #include <simgear/scene/material/mat.hxx>
24 #include <simgear/structure/commands.hxx>
25 #include <simgear/math/sg_geodesy.hxx>
26 #include <simgear/structure/event_mgr.hxx>
27
28 #include <Airports/runways.hxx>
29 #include <Airports/simple.hxx>
30 #include <Main/globals.hxx>
31 #include <Main/fg_props.hxx>
32 #include <Main/util.hxx>
33 #include <Scenery/scenery.hxx>
34 #include <Navaids/navlist.hxx>
35 #include <Navaids/procedure.hxx>
36 #include <Radio/radio.hxx>
37
38
39 #include "NasalSys.hxx"
40
41 static FGNasalSys* nasalSys = 0;
42
43 // Listener class for loading Nasal modules on demand
44 class FGNasalModuleListener : public SGPropertyChangeListener
45 {
46 public:
47     FGNasalModuleListener(SGPropertyNode* node);
48
49     virtual void valueChanged(SGPropertyNode* node);
50
51 private:
52     SGPropertyNode_ptr _node;
53 };
54
55 FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node)
56 {
57 }
58
59 void FGNasalModuleListener::valueChanged(SGPropertyNode*)
60 {
61     if (_node->getBoolValue("enabled",false)&&
62         !_node->getBoolValue("loaded",true))
63     {
64         nasalSys->loadPropertyScripts(_node);
65     }
66 }
67
68
69 // Read and return file contents in a single buffer.  Note use of
70 // stat() to get the file size.  This is a win32 function, believe it
71 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
72 // Text mode brain damage will kill us if we're trying to do bytewise
73 // I/O.
74 static char* readfile(const char* file, int* lenOut)
75 {
76     struct stat data;
77     if(stat(file, &data) != 0) return 0;
78     FILE* f = fopen(file, "rb");
79     if(!f) return 0;
80     char* buf = new char[data.st_size];
81     *lenOut = fread(buf, 1, data.st_size, f);
82     fclose(f);
83     if(*lenOut != data.st_size) {
84         // Shouldn't happen, but warn anyway since it represents a
85         // platform bug and not a typical runtime error (missing file,
86         // etc...)
87         SG_LOG(SG_NASAL, SG_ALERT,
88                "ERROR in Nasal initialization: " <<
89                "short count returned from fread() of " << file <<
90                ".  Check your C library!");
91         delete[] buf;
92         return 0;
93     }
94     return buf;
95 }
96
97 FGNasalSys::FGNasalSys()
98 {
99     nasalSys = this;
100     _context = 0;
101     _globals = naNil();
102     _gcHash = naNil();
103     _nextGCKey = 0; // Any value will do
104     _callCount = 0;
105 }
106
107 // Does a naCall() in a new context.  Wrapped here to make lock
108 // tracking easier.  Extension functions are called with the lock, but
109 // we have to release it before making a new naCall().  So rather than
110 // drop the lock in every extension function that might call back into
111 // Nasal, we keep a stack depth counter here and only unlock/lock
112 // around the naCall if it isn't the first one.
113 naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals)
114 {
115     naContext ctx = naNewContext();
116     if(_callCount) naModUnlock();
117     _callCount++;
118     naRef result = naCall(ctx, code, argc, args, naNil(), locals);
119     if(naGetError(ctx))
120         logError(ctx);
121     _callCount--;
122     if(_callCount) naModLock();
123     naFreeContext(ctx);
124     return result;
125 }
126
127 FGNasalSys::~FGNasalSys()
128 {
129     nasalSys = 0;
130     map<int, FGNasalListener *>::iterator it, end = _listener.end();
131     for(it = _listener.begin(); it != end; ++it)
132         delete it->second;
133
134     naFreeContext(_context);
135     _globals = naNil();
136 }
137
138 bool FGNasalSys::parseAndRun(const char* sourceCode)
139 {
140     naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
141                        strlen(sourceCode));
142     if(naIsNil(code))
143         return false;
144     call(code, 0, 0, naNil());
145     return true;
146 }
147
148 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
149 {
150     FGNasalScript* script = new FGNasalScript();
151     script->_gcKey = -1; // important, if we delete it on a parse
152     script->_nas = this; // error, don't clobber a real handle!
153
154     char buf[256];
155     if(!name) {
156         sprintf(buf, "FGNasalScript@%p", (void *)script);
157         name = buf;
158     }
159
160     script->_code = parse(name, src, strlen(src));
161     if(naIsNil(script->_code)) {
162         delete script;
163         return 0;
164     }
165
166     script->_gcKey = gcSave(script->_code);
167     return script;
168 }
169
170 // Utility.  Sets a named key in a hash by C string, rather than nasal
171 // string object.
172 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
173 {
174     naRef s = naNewString(_context);
175     naStr_fromdata(s, (char*)key, strlen(key));
176     naHash_set(hash, s, val);
177 }
178
179 // The get/setprop functions accept a *list* of strings and walk
180 // through the property tree with them to find the appropriate node.
181 // This allows a Nasal object to hold onto a property path and use it
182 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02).  This
183 // is the utility function that walks the property tree.
184 // Future enhancement: support integer arguments to specify array
185 // elements.
186 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
187 {
188     SGPropertyNode* p = globals->get_props();
189     try {
190         for(int i=0; i<len; i++) {
191             naRef a = vec[i];
192             if(!naIsString(a)) return 0;
193             p = p->getNode(naStr_data(a));
194             if(p == 0) return 0;
195         }
196     } catch (const string& err) {
197         naRuntimeError(c, (char *)err.c_str());
198         return 0;
199     }
200     return p;
201 }
202
203 // getprop() extension function.  Concatenates its string arguments as
204 // property names and returns the value of the specified property.  Or
205 // nil if it doesn't exist.
206 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
207 {
208     using namespace simgear;
209     const SGPropertyNode* p = findnode(c, args, argc);
210     if(!p) return naNil();
211
212     switch(p->getType()) {
213     case props::BOOL:   case props::INT:
214     case props::LONG:   case props::FLOAT:
215     case props::DOUBLE:
216         {
217         double dv = p->getDoubleValue();
218         if (osg::isNaN(dv)) {
219           SG_LOG(SG_GENERAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN");
220           return naNil();
221         }
222         
223         return naNum(dv);
224         }
225         
226     case props::STRING:
227     case props::UNSPECIFIED:
228         {
229             naRef nastr = naNewString(c);
230             const char* val = p->getStringValue();
231             naStr_fromdata(nastr, (char*)val, strlen(val));
232             return nastr;
233         }
234     case props::ALIAS: // <--- FIXME, recurse?
235     default:
236         return naNil();
237     }
238 }
239
240 // setprop() extension function.  Concatenates its string arguments as
241 // property names and sets the value of the specified property to the
242 // final argument.
243 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
244 {
245 #define BUFLEN 1024
246     char buf[BUFLEN + 1];
247     buf[BUFLEN] = 0;
248     char* p = buf;
249     int buflen = BUFLEN;
250     if(argc < 2) naRuntimeError(c, "setprop() expects at least 2 arguments");
251     for(int i=0; i<argc-1; i++) {
252         naRef s = naStringValue(c, args[i]);
253         if(naIsNil(s)) return naNil();
254         strncpy(p, naStr_data(s), buflen);
255         p += naStr_len(s);
256         buflen = BUFLEN - (p - buf);
257         if(i < (argc-2) && buflen > 0) {
258             *p++ = '/';
259             buflen--;
260         }
261     }
262
263     SGPropertyNode* props = globals->get_props();
264     naRef val = args[argc-1];
265     bool result = false;
266     try {
267         if(naIsString(val)) result = props->setStringValue(buf, naStr_data(val));
268         else {
269             naRef n = naNumValue(val);
270             if(naIsNil(n))
271                 naRuntimeError(c, "setprop() value is not string or number");
272                 
273             if (osg::isNaN(n.num)) {
274                 naRuntimeError(c, "setprop() passed a NaN");
275             }
276             
277             result = props->setDoubleValue(buf, n.num);
278         }
279     } catch (const string& err) {
280         naRuntimeError(c, (char *)err.c_str());
281     }
282     return naNum(result);
283 #undef BUFLEN
284 }
285
286 // print() extension function.  Concatenates and prints its arguments
287 // to the FlightGear log.  Uses the highest log level (SG_ALERT), to
288 // make sure it appears.  Is there better way to do this?
289 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
290 {
291     string buf;
292     int n = argc;
293     for(int i=0; i<n; i++) {
294         naRef s = naStringValue(c, args[i]);
295         if(naIsNil(s)) continue;
296         buf += naStr_data(s);
297     }
298     SG_LOG(SG_GENERAL, SG_ALERT, buf);
299     return naNum(buf.length());
300 }
301
302 // fgcommand() extension function.  Executes a named command via the
303 // FlightGear command manager.  Takes a single property node name as
304 // an argument.
305 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
306 {
307     naRef cmd = argc > 0 ? args[0] : naNil();
308     naRef props = argc > 1 ? args[1] : naNil();
309     if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props)))
310         naRuntimeError(c, "bad arguments to fgcommand()");
311     SGPropertyNode_ptr tmp, *node;
312     if(!naIsNil(props))
313         node = (SGPropertyNode_ptr*)naGhost_ptr(props);
314     else {
315         tmp = new SGPropertyNode();
316         node = &tmp;
317     }
318     return naNum(globals->get_commands()->execute(naStr_data(cmd), *node));
319 }
320
321 // settimer(func, dt, simtime) extension function.  Falls through to
322 // FGNasalSys::setTimer().  See there for docs.
323 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
324 {
325     nasalSys->setTimer(c, argc, args);
326     return naNil();
327 }
328
329 // setlistener(func, property, bool) extension function.  Falls through to
330 // FGNasalSys::setListener().  See there for docs.
331 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
332 {
333     return nasalSys->setListener(c, argc, args);
334 }
335
336 // removelistener(int) extension function. Falls through to
337 // FGNasalSys::removeListener(). See there for docs.
338 static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args)
339 {
340     return nasalSys->removeListener(c, argc, args);
341 }
342
343 // Returns a ghost handle to the argument to the currently executing
344 // command
345 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
346 {
347     return nasalSys->cmdArgGhost();
348 }
349
350 // Sets up a property interpolation.  The first argument is either a
351 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
352 // interpolate.  The second argument is a vector of pairs of
353 // value/delta numbers.
354 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
355 {
356     SGPropertyNode* node;
357     naRef prop = argc > 0 ? args[0] : naNil();
358     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
359     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
360     else return naNil();
361
362     naRef curve = argc > 1 ? args[1] : naNil();
363     if(!naIsVector(curve)) return naNil();
364     int nPoints = naVec_size(curve) / 2;
365     double* values = new double[nPoints];
366     double* deltas = new double[nPoints];
367     for(int i=0; i<nPoints; i++) {
368         values[i] = naNumValue(naVec_get(curve, 2*i)).num;
369         deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
370     }
371
372     ((SGInterpolator*)globals->get_subsystem_mgr()
373         ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
374         ->interpolate(node, nPoints, values, deltas);
375
376     delete[] values;
377     delete[] deltas;
378     return naNil();
379 }
380
381 // This is a better RNG than the one in the default Nasal distribution
382 // (which is based on the C library rand() implementation). It will
383 // override.
384 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
385 {
386     return naNum(sg_random());
387 }
388
389 static naRef f_srand(naContext c, naRef me, int argc, naRef* args)
390 {
391     sg_srandom_time();
392     return naNum(0);
393 }
394
395 static naRef f_abort(naContext c, naRef me, int argc, naRef* args)
396 {
397     abort();
398     return naNil();
399 }
400
401 // Return an array listing of all files in a directory
402 static naRef f_directory(naContext c, naRef me, int argc, naRef* args)
403 {
404     if(argc != 1 || !naIsString(args[0]))
405         naRuntimeError(c, "bad arguments to directory()");
406     
407     simgear::Dir d(SGPath(naStr_data(args[0])));
408     if(!d.exists()) return naNil();
409     naRef result = naNewVector(c);
410
411     simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR);
412     for (unsigned int i=0; i<paths.size(); ++i) {
413       std::string p = paths[i].file();
414       naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size()));
415     }
416     
417     return result;
418 }
419
420 /**
421  * Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory
422  */
423 static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
424 {
425     if(argc != 1 || !naIsString(args[0]))
426         naRuntimeError(c, "bad arguments to resolveDataPath()");
427
428     SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0]));
429     const char* pdata = p.c_str();
430     return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
431 }
432
433 // Parse XML file.
434 //     parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
435 //
436 // <path>      ... absolute path to an XML file
437 // <start-tag> ... callback function with two args: tag name, attribute hash
438 // <end-tag>   ... callback function with one arg:  tag name
439 // <data>      ... callback function with one arg:  data
440 // <pi>        ... callback function with two args: target, data
441 //                 (pi = "processing instruction")
442 // All four callback functions are optional and default to nil.
443 // The function returns nil on error, or the validated file name otherwise.
444 static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args)
445 {
446     if(argc < 1 || !naIsString(args[0]))
447         naRuntimeError(c, "parsexml(): path argument missing or not a string");
448     if(argc > 5) argc = 5;
449     for(int i=1; i<argc; i++)
450         if(!(naIsNil(args[i]) || naIsFunc(args[i])))
451             naRuntimeError(c, "parsexml(): callback argument not a function");
452
453     const char* file = fgValidatePath(naStr_data(args[0]), false);
454     if(!file) {
455         naRuntimeError(c, "parsexml(): reading '%s' denied "
456                 "(unauthorized access)", naStr_data(args[0]));
457         return naNil();
458     }
459     std::ifstream input(file);
460     NasalXMLVisitor visitor(c, argc, args);
461     try {
462         readXML(input, visitor);
463     } catch (const sg_exception& e) {
464         naRuntimeError(c, "parsexml(): file '%s' %s",
465                 file, e.getFormattedMessage().c_str());
466         return naNil();
467     }
468     return naStr_fromdata(naNewString(c), const_cast<char*>(file), strlen(file));
469 }
470
471 // Return UNIX epoch time in seconds.
472 static naRef f_systime(naContext c, naRef me, int argc, naRef* args)
473 {
474 #ifdef _WIN32
475     FILETIME ft;
476     GetSystemTimeAsFileTime(&ft);
477     double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime);
478     // Converts from 100ns units in 1601 epoch to unix epoch in sec
479     return naNum((t * 1e-7) - 11644473600.0);
480 #else
481     struct timeval td;
482     gettimeofday(&td, 0);
483     return naNum(td.tv_sec + 1e-6 * td.tv_usec);
484 #endif
485 }
486
487 // Convert a cartesian point to a geodetic lat/lon/altitude.
488 static naRef f_carttogeod(naContext c, naRef me, int argc, naRef* args)
489 {
490     double lat, lon, alt, xyz[3];
491     if(argc != 3) naRuntimeError(c, "carttogeod() expects 3 arguments");
492     for(int i=0; i<3; i++)
493         xyz[i] = naNumValue(args[i]).num;
494     sgCartToGeod(xyz, &lat, &lon, &alt);
495     lat *= SG_RADIANS_TO_DEGREES;
496     lon *= SG_RADIANS_TO_DEGREES;
497     naRef vec = naNewVector(c);
498     naVec_append(vec, naNum(lat));
499     naVec_append(vec, naNum(lon));
500     naVec_append(vec, naNum(alt));
501     return vec;
502 }
503
504 // Convert a cartesian point to a geodetic lat/lon/altitude.
505 static naRef f_radioTransmission(naContext c, naRef me, int argc, naRef* args)
506 {
507     double lat, lon, elev, heading, pitch;
508     if(argc != 5) naRuntimeError(c, "radioTransmission() expects 5 arguments");
509     for(int i=0; i<argc; i++) {
510         if(naIsNil(args[i]))
511                 return naNil();
512     }
513     lat = naNumValue(args[0]).num;
514     lon = naNumValue(args[1]).num;
515     elev = naNumValue(args[2]).num;
516     heading = naNumValue(args[3]).num;
517     pitch = naNumValue(args[4]).num;
518     FGRadioTransmission *radio = new FGRadioTransmission;
519     double signal = radio->receiveBeacon(lat,lon,elev,heading,pitch);
520     delete radio;
521     return naNum(signal);
522 }
523
524 // Convert a geodetic lat/lon/altitude to a cartesian point.
525 static naRef f_geodtocart(naContext c, naRef me, int argc, naRef* args)
526 {
527     if(argc != 3) naRuntimeError(c, "geodtocart() expects 3 arguments");
528     double lat = naNumValue(args[0]).num * SG_DEGREES_TO_RADIANS;
529     double lon = naNumValue(args[1]).num * SG_DEGREES_TO_RADIANS;
530     double alt = naNumValue(args[2]).num;
531     double xyz[3];
532     sgGeodToCart(lat, lon, alt, xyz);
533     naRef vec = naNewVector(c);
534     naVec_append(vec, naNum(xyz[0]));
535     naVec_append(vec, naNum(xyz[1]));
536     naVec_append(vec, naNum(xyz[2]));
537     return vec;
538 }
539
540 // For given geodetic point return array with elevation, and a material data
541 // hash, or nil if there's no information available (tile not loaded). If
542 // information about the material isn't available, then nil is returned instead
543 // of the hash.
544 static naRef f_geodinfo(naContext c, naRef me, int argc, naRef* args)
545 {
546 #define HASHSET(s,l,n) naHash_set(matdata, naStr_fromdata(naNewString(c),s,l),n)
547     if(argc < 2 || argc > 3)
548         naRuntimeError(c, "geodinfo() expects 2 or 3 arguments: lat, lon [, maxalt]");
549     double lat = naNumValue(args[0]).num;
550     double lon = naNumValue(args[1]).num;
551     double elev = argc == 3 ? naNumValue(args[2]).num : 10000;
552     const SGMaterial *mat;
553     SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
554     if(!globals->get_scenery()->get_elevation_m(geod, elev, &mat))
555         return naNil();
556     naRef vec = naNewVector(c);
557     naVec_append(vec, naNum(elev));
558     naRef matdata = naNil();
559     if(mat) {
560         matdata = naNewHash(c);
561         naRef names = naNewVector(c);
562         const vector<string> n = mat->get_names();
563         for(unsigned int i=0; i<n.size(); i++)
564             naVec_append(names, naStr_fromdata(naNewString(c),
565                     const_cast<char*>(n[i].c_str()), n[i].size()));
566         HASHSET("names", 5, names);
567         HASHSET("solid", 5, naNum(mat->get_solid()));
568         HASHSET("friction_factor", 15, naNum(mat->get_friction_factor()));
569         HASHSET("rolling_friction", 16, naNum(mat->get_rolling_friction()));
570         HASHSET("load_resistance", 15, naNum(mat->get_load_resistance()));
571         HASHSET("bumpiness", 9, naNum(mat->get_bumpiness()));
572         HASHSET("light_coverage", 14, naNum(mat->get_light_coverage()));
573     }
574     naVec_append(vec, matdata);
575     return vec;
576 #undef HASHSET
577 }
578
579
580 class AirportInfoFilter : public FGAirport::AirportFilter
581 {
582 public:
583     AirportInfoFilter() : type(FGPositioned::AIRPORT) {
584     }
585
586     virtual FGPositioned::Type minType() const {
587         return type;
588     }
589
590     virtual FGPositioned::Type maxType() const {
591         return type;
592     }
593
594     FGPositioned::Type type;
595 };
596
597 // Returns data hash for particular or nearest airport of a <type>, or nil
598 // on error.
599 //
600 // airportinfo(<id>);                   e.g. "KSFO"
601 // airportinfo(<type>);                 type := ("airport"|"seaport"|"heliport")
602 // airportinfo()                        same as  airportinfo("airport")
603 // airportinfo(<lat>, <lon> [, <type>]);
604 static naRef f_airportinfo(naContext c, naRef me, int argc, naRef* args)
605 {
606     static SGConstPropertyNode_ptr latn = fgGetNode("/position/latitude-deg", true);
607     static SGConstPropertyNode_ptr lonn = fgGetNode("/position/longitude-deg", true);
608     SGGeod pos;
609     FGAirport* apt = NULL;
610
611     if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
612         pos = SGGeod::fromDeg(args[1].num, args[0].num);
613         args += 2;
614         argc -= 2;
615     } else {
616         pos = SGGeod::fromDeg(lonn->getDoubleValue(), latn->getDoubleValue());
617     }
618
619     double maxRange = 10000.0; // expose this? or pick a smaller value?
620
621     AirportInfoFilter filter; // defaults to airports only
622
623     if(argc == 0) {
624         // fall through and use AIRPORT
625     } else if(argc == 1 && naIsString(args[0])) {
626         const char *s = naStr_data(args[0]);
627         if(!strcmp(s, "airport")) filter.type = FGPositioned::AIRPORT;
628         else if(!strcmp(s, "seaport")) filter.type = FGPositioned::SEAPORT;
629         else if(!strcmp(s, "heliport")) filter.type = FGPositioned::HELIPORT;
630         else {
631             // user provided an <id>, hopefully
632             apt = FGAirport::findByIdent(s);
633             if (!apt) {
634                 // return nil here, but don't raise a runtime error; this is a
635                 // legitamate way to validate an ICAO code, for example in a
636                 // dialog box or similar.
637                 return naNil();
638             }
639         }
640     } else {
641         naRuntimeError(c, "airportinfo() with invalid function arguments");
642         return naNil();
643     }
644
645     if(!apt) {
646         apt = FGAirport::findClosest(pos, maxRange, &filter);
647         if(!apt) return naNil();
648     }
649
650     string id = apt->ident();
651     string name = apt->name();
652
653     // set runway hash
654     naRef rwys = naNewHash(c);
655     for(unsigned int r=0; r<apt->numRunways(); ++r) {
656         FGRunway* rwy(apt->getRunwayByIndex(r));
657
658         naRef rwyid = naStr_fromdata(naNewString(c),
659                       const_cast<char *>(rwy->ident().c_str()),
660                       rwy->ident().length());
661
662         naRef rwydata = naNewHash(c);
663 #define HASHSET(s,l,n) naHash_set(rwydata, naStr_fromdata(naNewString(c),s,l),n)
664         HASHSET("id", 2, rwyid);
665         HASHSET("lat", 3, naNum(rwy->latitude()));
666         HASHSET("lon", 3, naNum(rwy->longitude()));
667         HASHSET("heading", 7, naNum(rwy->headingDeg()));
668         HASHSET("length", 6, naNum(rwy->lengthM()));
669         HASHSET("width", 5, naNum(rwy->widthM()));
670         HASHSET("threshold", 9, naNum(rwy->displacedThresholdM()));
671         HASHSET("stopway", 7, naNum(rwy->stopwayM()));
672         
673         if (rwy->ILS()) {
674           HASHSET("ils_frequency_mhz", 17, naNum(rwy->ILS()->get_freq() / 100.0));
675         }
676         
677         std::vector<flightgear::SID*> sids(rwy->getSIDs());
678         naRef sidVec = naNewVector(c);
679         
680         for (unsigned int s=0; s < sids.size(); ++s) {
681           naRef procId = naStr_fromdata(naNewString(c),
682                     const_cast<char *>(sids[s]->ident().c_str()),
683                     sids[s]->ident().length());
684           naVec_append(sidVec, procId);
685         }
686         HASHSET("sids", 4, sidVec); 
687         
688         std::vector<flightgear::STAR*> stars(rwy->getSTARs());
689         naRef starVec = naNewVector(c);
690       
691         for (unsigned int s=0; s < stars.size(); ++s) {
692           naRef procId = naStr_fromdata(naNewString(c),
693                     const_cast<char *>(stars[s]->ident().c_str()),
694                     stars[s]->ident().length());
695           naVec_append(starVec, procId);
696         }
697         HASHSET("stars", 5, starVec); 
698
699 #undef HASHSET
700         naHash_set(rwys, rwyid, rwydata);
701     }
702
703     // set airport hash
704     naRef aptdata = naNewHash(c);
705 #define HASHSET(s,l,n) naHash_set(aptdata, naStr_fromdata(naNewString(c),s,l),n)
706     HASHSET("id", 2, naStr_fromdata(naNewString(c),
707             const_cast<char *>(id.c_str()), id.length()));
708     HASHSET("name", 4, naStr_fromdata(naNewString(c),
709             const_cast<char *>(name.c_str()), name.length()));
710     HASHSET("lat", 3, naNum(apt->getLatitude()));
711     HASHSET("lon", 3, naNum(apt->getLongitude()));
712     HASHSET("elevation", 9, naNum(apt->getElevation() * SG_FEET_TO_METER));
713     HASHSET("has_metar", 9, naNum(apt->getMetar()));
714     HASHSET("runways", 7, rwys);
715 #undef HASHSET
716     return aptdata;
717 }
718
719
720 // Returns vector of data hash for navaid of a <type>, nil on error
721 // navaids sorted by ascending distance 
722 // navinfo([<lat>,<lon>],[<type>],[<id>])
723 // lat/lon (numeric): use latitude/longitude instead of ac position
724 // type:              ("fix"|"vor"|"ndb"|"ils"|"dme"|"tacan"|"any")
725 // id:                (partial) id of the fix
726 // examples:
727 // navinfo("vor")     returns all vors
728 // navinfo("HAM")     return all navaids who's name start with "HAM"
729 // navinfo("vor", "HAM") return all vor who's name start with "HAM"
730 //navinfo(34,48,"vor","HAM") return all vor who's name start with "HAM" 
731 //                           sorted by distance relative to lat=34, lon=48
732 static naRef f_navinfo(naContext c, naRef me, int argc, naRef* args)
733 {
734     static SGConstPropertyNode_ptr latn = fgGetNode("/position/latitude-deg", true);
735     static SGConstPropertyNode_ptr lonn = fgGetNode("/position/longitude-deg", true);
736     SGGeod pos;
737
738     if(argc >= 2 && naIsNum(args[0]) && naIsNum(args[1])) {
739         pos = SGGeod::fromDeg(args[1].num, args[0].num);
740         args += 2;
741         argc -= 2;
742     } else {
743         pos = SGGeod::fromDeg(lonn->getDoubleValue(), latn->getDoubleValue());
744     }
745
746     FGPositioned::Type type = FGPositioned::INVALID;
747     nav_list_type navlist;
748     const char * id = "";
749
750     if(argc > 0 && naIsString(args[0])) {
751         const char *s = naStr_data(args[0]);
752         if(!strcmp(s, "any")) type = FGPositioned::INVALID;
753         else if(!strcmp(s, "fix")) type = FGPositioned::FIX;
754         else if(!strcmp(s, "vor")) type = FGPositioned::VOR;
755         else if(!strcmp(s, "ndb")) type = FGPositioned::NDB;
756         else if(!strcmp(s, "ils")) type = FGPositioned::ILS;
757         else if(!strcmp(s, "dme")) type = FGPositioned::DME;
758         else if(!strcmp(s, "tacan")) type = FGPositioned::TACAN;
759         else id = s; // this is an id
760         ++args;
761         --argc;
762     } 
763
764     if(argc > 0 && naIsString(args[0])) {
765         if( *id != 0 ) {
766             naRuntimeError(c, "navinfo() called with navaid id");
767             return naNil();
768         }
769         id = naStr_data(args[0]);
770         ++args;
771         --argc;
772     }
773
774     if( argc > 0 ) {
775         naRuntimeError(c, "navinfo() called with too many arguments");
776         return naNil();
777     }
778
779     navlist = globals->get_navlist()->findByIdentAndFreq( pos, id, 0.0, type );
780
781     naRef reply = naNewVector(c);
782     for( nav_list_type::const_iterator it = navlist.begin(); it != navlist.end(); ++it ) {
783         const FGNavRecord * nav = *it;
784
785         // set navdata hash
786         naRef navdata = naNewHash(c);
787 #define HASHSET(s,l,n) naHash_set(navdata, naStr_fromdata(naNewString(c),s,l),n)
788         HASHSET("id", 2, naStr_fromdata(naNewString(c),
789             const_cast<char *>(nav->ident().c_str()), nav->ident().length()));
790         HASHSET("name", 4, naStr_fromdata(naNewString(c),
791             const_cast<char *>(nav->name().c_str()), nav->name().length()));
792         HASHSET("frequency", 9, naNum(nav->get_freq()));
793         HASHSET("lat", 3, naNum(nav->get_lat()));
794         HASHSET("lon", 3, naNum(nav->get_lon()));
795         HASHSET("elevation", 9, naNum(nav->get_elev_ft() * SG_FEET_TO_METER));
796         HASHSET("type", 4, naStr_fromdata(naNewString(c),
797             const_cast<char *>(nav->nameForType(nav->type())), strlen(nav->nameForType(nav->type()))));
798         HASHSET("distance", 8, naNum(SGGeodesy::distanceNm( pos, nav->geod() ) * SG_NM_TO_METER ) );
799         HASHSET("bearing", 7, naNum(SGGeodesy::courseDeg( pos, nav->geod() ) ) );
800 #undef HASHSET
801         naVec_append( reply, navdata );
802     }
803     return reply;
804 }
805
806 // Table of extension functions.  Terminate with zeros.
807 static struct { const char* name; naCFunction func; } funcs[] = {
808     { "getprop",   f_getprop },
809     { "setprop",   f_setprop },
810     { "print",     f_print },
811     { "_fgcommand", f_fgcommand },
812     { "settimer",  f_settimer },
813     { "_setlistener", f_setlistener },
814     { "removelistener", f_removelistener },
815     { "_cmdarg",  f_cmdarg },
816     { "_interpolate",  f_interpolate },
817     { "rand",  f_rand },
818     { "srand",  f_srand },
819     { "abort", f_abort },
820     { "directory", f_directory },
821     { "resolvepath", f_resolveDataPath },
822     { "parsexml", f_parsexml },
823     { "systime", f_systime },
824     { "carttogeod", f_carttogeod },
825     { "geodtocart", f_geodtocart },
826     { "geodinfo", f_geodinfo },
827     { "airportinfo", f_airportinfo },
828     { "navinfo", f_navinfo },
829     { "radioTransmission", f_radioTransmission },
830     { 0, 0 }
831 };
832
833 naRef FGNasalSys::cmdArgGhost()
834 {
835     return propNodeGhost(_cmdArg);
836 }
837
838 void FGNasalSys::init()
839 {
840     int i;
841
842     _context = naNewContext();
843
844     // Start with globals.  Add it to itself as a recursive
845     // sub-reference under the name "globals".  This gives client-code
846     // write access to the namespace if someone wants to do something
847     // fancy.
848     _globals = naInit_std(_context);
849     naSave(_context, _globals);
850     hashset(_globals, "globals", _globals);
851
852     hashset(_globals, "math", naInit_math(_context));
853     hashset(_globals, "bits", naInit_bits(_context));
854     hashset(_globals, "io", naInit_io(_context));
855     hashset(_globals, "thread", naInit_thread(_context));
856     hashset(_globals, "utf8", naInit_utf8(_context));
857
858     // Add our custom extension functions:
859     for(i=0; funcs[i].name; i++)
860         hashset(_globals, funcs[i].name,
861                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
862
863     // And our SGPropertyNode wrapper
864     hashset(_globals, "props", genPropsModule());
865
866     // Make a "__gcsave" hash to hold the naRef objects which get
867     // passed to handles outside the interpreter (to protect them from
868     // begin garbage-collected).
869     _gcHash = naNewHash(_context);
870     hashset(_globals, "__gcsave", _gcHash);
871
872     // Now load the various source files in the Nasal directory
873     simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
874     loadScriptDirectory(nasalDir);
875
876     // Add modules in Nasal subdirectories to property tree
877     simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
878             simgear::Dir::NO_DOT_OR_DOTDOT, "");
879     for (unsigned int i=0; i<directories.size(); ++i) {
880         simgear::Dir dir(directories[i]);
881         simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas");
882         addModule(directories[i].file(), scripts);
883     }
884
885     // set signal and remove node to avoid restoring at reinit
886     const char *s = "nasal-dir-initialized";
887     SGPropertyNode *signal = fgGetNode("/sim/signals", true);
888     signal->setBoolValue(s, true);
889     signal->removeChildren(s, false);
890
891     // Pull scripts out of the property tree, too
892     loadPropertyScripts();
893 }
894
895 void FGNasalSys::update(double)
896 {
897     if(!_dead_listener.empty()) {
898         vector<FGNasalListener *>::iterator it, end = _dead_listener.end();
899         for(it = _dead_listener.begin(); it != end; ++it) delete *it;
900         _dead_listener.clear();
901     }
902
903     // The global context is a legacy thing.  We use dynamically
904     // created contexts for naCall() now, so that we can call them
905     // recursively.  But there are still spots that want to use it for
906     // naNew*() calls, which end up leaking memory because the context
907     // only clears out its temporary vector when it's *used*.  So just
908     // junk it and fetch a new/reinitialized one every frame.  This is
909     // clumsy: the right solution would use the dynamic context in all
910     // cases and eliminate _context entirely.  But that's more work,
911     // and this works fine (yes, they say "New" and "Free", but
912     // they're very fast, just trust me). -Andy
913     naFreeContext(_context);
914     _context = naNewContext();
915 }
916
917 bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
918 {
919   return p1.file() < p2.file();
920 }
921
922 // Loads all scripts in given directory 
923 void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir)
924 {
925     simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas");
926     // sort scripts, avoid loading sequence effects due to file system's
927     // random directory order
928     std::sort(scripts.begin(), scripts.end(), pathSortPredicate);
929
930     for (unsigned int i=0; i<scripts.size(); ++i) {
931       SGPath fullpath(scripts[i]);
932       SGPath file = fullpath.file();
933       loadModule(fullpath, file.base().c_str());
934     }
935 }
936
937 // Create module with list of scripts
938 void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
939 {
940     if (scripts.size()>0)
941     {
942         SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
943         SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
944         for (unsigned int i=0; i<scripts.size(); ++i) {
945             SGPropertyNode* pFileNode = module_node->getChild("file",i,true);
946             pFileNode->setStringValue(scripts[i].c_str());
947         }
948         if (!module_node->hasChild("enabled",0))
949         {
950             SGPropertyNode* node = module_node->getChild("enabled",0,true);
951             node->setBoolValue(true);
952             node->setAttribute(SGPropertyNode::USERARCHIVE,true);
953         }
954     }
955 }
956
957 // Loads the scripts found under /nasal in the global tree
958 void FGNasalSys::loadPropertyScripts()
959 {
960     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
961     if(!nasal) return;
962
963     for(int i=0; i<nasal->nChildren(); i++)
964     {
965         SGPropertyNode* n = nasal->getChild(i);
966         loadPropertyScripts(n);
967     }
968 }
969
970 // Loads the scripts found under /nasal in the global tree
971 void FGNasalSys::loadPropertyScripts(SGPropertyNode* n)
972 {
973     bool is_loaded = false;
974
975     const char* module = n->getName();
976     if(n->hasChild("module"))
977         module = n->getStringValue("module");
978     if (n->getBoolValue("enabled",true))
979     {
980         // allow multiple files to be specified within a single
981         // Nasal module tag
982         int j = 0;
983         SGPropertyNode *fn;
984         bool file_specified = false;
985         bool ok=true;
986         while((fn = n->getChild("file", j)) != NULL) {
987             file_specified = true;
988             const char* file = fn->getStringValue();
989             SGPath p(file);
990             if (!p.isAbsolute() || !p.exists())
991             {
992                 p = globals->resolve_maybe_aircraft_path(file);
993                 if (p.isNull())
994                 {
995                     SG_LOG(SG_NASAL, SG_ALERT, "Cannot find Nasal script '" <<
996                             file << "' for module '" << module << "'.");
997                 }
998             }
999             ok &= p.isNull() ? false : loadModule(p, module);
1000             j++;
1001         }
1002
1003         const char* src = n->getStringValue("script");
1004         if(!n->hasChild("script")) src = 0; // Hrm...
1005         if(src)
1006             createModule(module, n->getPath().c_str(), src, strlen(src));
1007
1008         if(!file_specified && !src)
1009         {
1010             // module no longer exists - clear the archived "enable" flag
1011             n->setAttribute(SGPropertyNode::USERARCHIVE,false);
1012             SGPropertyNode* node = n->getChild("enabled",0,false);
1013             if (node)
1014                 node->setAttribute(SGPropertyNode::USERARCHIVE,false);
1015
1016             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
1017                     "no <file> or <script> defined in " <<
1018                     "/nasal/" << module);
1019         }
1020         else
1021             is_loaded = ok;
1022     }
1023     else
1024     {
1025         SGPropertyNode* enable = n->getChild("enabled");
1026         if (enable)
1027         {
1028             FGNasalModuleListener* listener = new FGNasalModuleListener(n);
1029             enable->addChangeListener(listener, false);
1030         }
1031     }
1032     SGPropertyNode* loaded = n->getChild("loaded",0,true);
1033     loaded->setAttribute(SGPropertyNode::PRESERVE,true);
1034     loaded->setBoolValue(is_loaded);
1035 }
1036
1037 // Logs a runtime error, with stack trace, to the FlightGear log stream
1038 void FGNasalSys::logError(naContext context)
1039 {
1040     SG_LOG(SG_NASAL, SG_ALERT,
1041            "Nasal runtime error: " << naGetError(context));
1042     SG_LOG(SG_NASAL, SG_ALERT,
1043            "  at " << naStr_data(naGetSourceFile(context, 0)) <<
1044            ", line " << naGetLine(context, 0));
1045     for(int i=1; i<naStackDepth(context); i++)
1046         SG_LOG(SG_NASAL, SG_ALERT,
1047                "  called from: " << naStr_data(naGetSourceFile(context, i)) <<
1048                ", line " << naGetLine(context, i));
1049 }
1050
1051 // Reads a script file, executes it, and places the resulting
1052 // namespace into the global namespace under the specified module
1053 // name.
1054 bool FGNasalSys::loadModule(SGPath file, const char* module)
1055 {
1056     int len = 0;
1057     char* buf = readfile(file.c_str(), &len);
1058     if(!buf) {
1059         SG_LOG(SG_NASAL, SG_ALERT,
1060                "Nasal error: could not read script file " << file.c_str()
1061                << " into module " << module);
1062         return false;
1063     }
1064
1065     bool ok = createModule(module, file.c_str(), buf, len);
1066     delete[] buf;
1067     return ok;
1068 }
1069
1070 // Parse and run.  Save the local variables namespace, as it will
1071 // become a sub-object of globals.  The optional "arg" argument can be
1072 // used to pass an associated property node to the module, which can then
1073 // be accessed via cmdarg().  (This is, for example, used by XML dialogs.)
1074 bool FGNasalSys::createModule(const char* moduleName, const char* fileName,
1075                               const char* src, int len,
1076                               const SGPropertyNode* cmdarg,
1077                               int argc, naRef* args)
1078 {
1079     naRef code = parse(fileName, src, len);
1080     if(naIsNil(code))
1081         return false;
1082
1083     // See if we already have a module hash to use.  This allows the
1084     // user to, for example, add functions to the built-in math
1085     // module.  Make a new one if necessary.
1086     naRef locals;
1087     naRef modname = naNewString(_context);
1088     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1089     if(!naHash_get(_globals, modname, &locals))
1090         locals = naNewHash(_context);
1091
1092     _cmdArg = (SGPropertyNode*)cmdarg;
1093
1094     call(code, argc, args, locals);
1095     hashset(_globals, moduleName, locals);
1096     return true;
1097 }
1098
1099 void FGNasalSys::deleteModule(const char* moduleName)
1100 {
1101     naRef modname = naNewString(_context);
1102     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1103     naHash_delete(_globals, modname);
1104 }
1105
1106 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
1107 {
1108     int errLine = -1;
1109     naRef srcfile = naNewString(_context);
1110     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
1111     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
1112     if(naIsNil(code)) {
1113         SG_LOG(SG_NASAL, SG_ALERT,
1114                "Nasal parse error: " << naGetError(_context) <<
1115                " in "<< filename <<", line " << errLine);
1116         return naNil();
1117     }
1118
1119     // Bind to the global namespace before returning
1120     return naBindFunction(_context, code, _globals);
1121 }
1122
1123 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
1124 {
1125     const char* nasal = arg->getStringValue("script");
1126     const char* moduleName = arg->getStringValue("module");
1127     naRef code = parse(arg->getPath(true).c_str(), nasal, strlen(nasal));
1128     if(naIsNil(code)) return false;
1129
1130     // Commands can be run "in" a module.  Make sure that module
1131     // exists, and set it up as the local variables hash for the
1132     // command.
1133     naRef locals = naNil();
1134     if(moduleName[0]) {
1135         naRef modname = naNewString(_context);
1136         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
1137         if(!naHash_get(_globals, modname, &locals)) {
1138             locals = naNewHash(_context);
1139             naHash_set(_globals, modname, locals);
1140         }
1141     }
1142
1143     // Cache this command's argument for inspection via cmdarg().  For
1144     // performance reasons, we won't bother with it if the invoked
1145     // code doesn't need it.
1146     _cmdArg = (SGPropertyNode*)arg;
1147
1148     call(code, 0, 0, locals);
1149     return true;
1150 }
1151
1152 // settimer(func, dt, simtime) extension function.  The first argument
1153 // is a Nasal function to call, the second is a delta time (from now),
1154 // in seconds.  The third, if present, is a boolean value indicating
1155 // that "real world" time (rather than simulator time) is to be used.
1156 //
1157 // Implementation note: the FGTimer objects don't live inside the
1158 // garbage collector, so the Nasal handler functions have to be
1159 // "saved" somehow lest they be inadvertently cleaned.  In this case,
1160 // they are inserted into a globals.__gcsave hash and removed on
1161 // expiration.
1162 void FGNasalSys::setTimer(naContext c, int argc, naRef* args)
1163 {
1164     // Extract the handler, delta, and simtime arguments:
1165     naRef handler = argc > 0 ? args[0] : naNil();
1166     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) {
1167         naRuntimeError(c, "settimer() with invalid function argument");
1168         return;
1169     }
1170
1171     naRef delta = argc > 1 ? args[1] : naNil();
1172     if(naIsNil(delta)) {
1173         naRuntimeError(c, "settimer() with invalid time argument");
1174         return;
1175     }
1176
1177     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
1178
1179     // Generate and register a C++ timer handler
1180     NasalTimer* t = new NasalTimer;
1181     t->handler = handler;
1182     t->gcKey = gcSave(handler);
1183     t->nasal = this;
1184
1185     globals->get_event_mgr()->addEvent("NasalTimer",
1186                                        t, &NasalTimer::timerExpired,
1187                                        delta.num, simtime);
1188 }
1189
1190 void FGNasalSys::handleTimer(NasalTimer* t)
1191 {
1192     call(t->handler, 0, 0, naNil());
1193     gcRelease(t->gcKey);
1194 }
1195
1196 int FGNasalSys::gcSave(naRef r)
1197 {
1198     int key = _nextGCKey++;
1199     naHash_set(_gcHash, naNum(key), r);
1200     return key;
1201 }
1202
1203 void FGNasalSys::gcRelease(int key)
1204 {
1205     naHash_delete(_gcHash, naNum(key));
1206 }
1207
1208 void FGNasalSys::NasalTimer::timerExpired()
1209 {
1210     nasal->handleTimer(this);
1211     delete this;
1212 }
1213
1214 int FGNasalSys::_listenerId = 0;
1215
1216 // setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]])
1217 // Attaches a callback function to a property (specified as a global
1218 // property path string or a SGPropertyNode_ptr* ghost). If the third,
1219 // optional argument (default=0) is set to 1, then the function is also
1220 // called initially. If the fourth, optional argument is set to 0, then the
1221 // function is only called when the property node value actually changes.
1222 // Otherwise it's called independent of the value whenever the node is
1223 // written to (default). The setlistener() function returns a unique
1224 // id number, which is to be used as argument to the removelistener()
1225 // function.
1226 naRef FGNasalSys::setListener(naContext c, int argc, naRef* args)
1227 {
1228     SGPropertyNode_ptr node;
1229     naRef prop = argc > 0 ? args[0] : naNil();
1230     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
1231     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
1232     else {
1233         naRuntimeError(c, "setlistener() with invalid property argument");
1234         return naNil();
1235     }
1236
1237     if(node->isTied())
1238         SG_LOG(SG_NASAL, SG_DEBUG, "Attaching listener to tied property " <<
1239                 node->getPath());
1240
1241     naRef code = argc > 1 ? args[1] : naNil();
1242     if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) {
1243         naRuntimeError(c, "setlistener() with invalid function argument");
1244         return naNil();
1245     }
1246
1247     int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0;
1248     int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1;
1249     FGNasalListener *nl = new FGNasalListener(node, code, this,
1250             gcSave(code), _listenerId, init, type);
1251
1252     node->addChangeListener(nl, init != 0);
1253
1254     _listener[_listenerId] = nl;
1255     return naNum(_listenerId++);
1256 }
1257
1258 // removelistener(int) extension function. The argument is the id of
1259 // a listener as returned by the setlistener() function.
1260 naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
1261 {
1262     naRef id = argc > 0 ? args[0] : naNil();
1263     map<int, FGNasalListener *>::iterator it = _listener.find(int(id.num));
1264
1265     if(!naIsNum(id) || it == _listener.end() || it->second->_dead) {
1266         naRuntimeError(c, "removelistener() with invalid listener id");
1267         return naNil();
1268     }
1269
1270     it->second->_dead = true;
1271     _dead_listener.push_back(it->second);
1272     _listener.erase(it);
1273     return naNum(_listener.size());
1274 }
1275
1276
1277
1278 // FGNasalListener class.
1279
1280 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
1281                                  FGNasalSys* nasal, int key, int id,
1282                                  int init, int type) :
1283     _node(node),
1284     _code(code),
1285     _gcKey(key),
1286     _id(id),
1287     _nas(nasal),
1288     _init(init),
1289     _type(type),
1290     _active(0),
1291     _dead(false),
1292     _last_int(0L),
1293     _last_float(0.0)
1294 {
1295     if(_type == 0 && !_init)
1296         changed(node);
1297 }
1298
1299 FGNasalListener::~FGNasalListener()
1300 {
1301     _node->removeChangeListener(this);
1302     _nas->gcRelease(_gcKey);
1303 }
1304
1305 void FGNasalListener::call(SGPropertyNode* which, naRef mode)
1306 {
1307     if(_active || _dead) return;
1308     SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
1309     _active++;
1310     naRef arg[4];
1311     arg[0] = _nas->propNodeGhost(which);
1312     arg[1] = _nas->propNodeGhost(_node);
1313     arg[2] = mode;                  // value changed, child added/removed
1314     arg[3] = naNum(_node != which); // child event?
1315     _nas->call(_code, 4, arg, naNil());
1316     _active--;
1317 }
1318
1319 void FGNasalListener::valueChanged(SGPropertyNode* node)
1320 {
1321     if(_type < 2 && node != _node) return;   // skip child events
1322     if(_type > 0 || changed(_node) || _init)
1323         call(node, naNum(0));
1324
1325     _init = 0;
1326 }
1327
1328 void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child)
1329 {
1330     if(_type == 2) call(child, naNum(1));
1331 }
1332
1333 void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child)
1334 {
1335     if(_type == 2) call(child, naNum(-1));
1336 }
1337
1338 bool FGNasalListener::changed(SGPropertyNode* node)
1339 {
1340     using namespace simgear;
1341     props::Type type = node->getType();
1342     if(type == props::NONE) return false;
1343     if(type == props::UNSPECIFIED) return true;
1344
1345     bool result;
1346     switch(type) {
1347     case props::BOOL:
1348     case props::INT:
1349     case props::LONG:
1350         {
1351             long l = node->getLongValue();
1352             result = l != _last_int;
1353             _last_int = l;
1354             return result;
1355         }
1356     case props::FLOAT:
1357     case props::DOUBLE:
1358         {
1359             double d = node->getDoubleValue();
1360             result = d != _last_float;
1361             _last_float = d;
1362             return result;
1363         }
1364     default:
1365         {
1366             string s = node->getStringValue();
1367             result = s != _last_string;
1368             _last_string = s;
1369             return result;
1370         }
1371     }
1372 }
1373
1374
1375
1376 // FGNasalModelData class.  If sgLoad3DModel() is called with a pointer to
1377 // such a class, then it lets modelLoaded() run the <load> script, and the
1378 // destructor the <unload> script. The latter happens when the model branch
1379 // is removed from the scene graph.
1380
1381 unsigned int FGNasalModelData::_module_id = 0;
1382
1383 void FGNasalModelData::modelLoaded(const string& path, SGPropertyNode *prop,
1384                                    osg::Node *)
1385 {
1386     if(!prop)
1387         return;
1388     SGPropertyNode *nasal = prop->getNode("nasal");
1389     if(!nasal)
1390         return;
1391
1392     SGPropertyNode *load = nasal->getNode("load");
1393     _unload = nasal->getNode("unload");
1394     if(!load && !_unload)
1395         return;
1396
1397     std::stringstream m;
1398     m << "__model" << _module_id++;
1399     _module = m.str();
1400
1401     const char *s = load ? load->getStringValue() : "";
1402
1403     naRef arg[2];
1404     arg[0] = nasalSys->propNodeGhost(_root);
1405     arg[1] = nasalSys->propNodeGhost(prop);
1406     nasalSys->createModule(_module.c_str(), path.c_str(), s, strlen(s),
1407                            _root, 2, arg);
1408 }
1409
1410 FGNasalModelData::~FGNasalModelData()
1411 {
1412     if(_module.empty())
1413         return;
1414
1415     if(!nasalSys) {
1416         SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
1417                 "without Nasal subsystem present.");
1418         return;
1419     }
1420
1421     if(_unload) {
1422         const char *s = _unload->getStringValue();
1423         nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _root);
1424     }
1425     nasalSys->deleteModule(_module.c_str());
1426 }
1427
1428
1429
1430 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
1431 //
1432 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :
1433     _c(naSubContext(c)),
1434     _start_element(argc > 1 ? args[1] : naNil()),
1435     _end_element(argc > 2 ? args[2] : naNil()),
1436     _data(argc > 3 ? args[3] : naNil()),
1437     _pi(argc > 4 ? args[4] : naNil())
1438 {
1439 }
1440
1441 void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a)
1442 {
1443     if(naIsNil(_start_element)) return;
1444     naRef attr = naNewHash(_c);
1445     for(int i=0; i<a.size(); i++) {
1446         naRef name = make_string(a.getName(i));
1447         naRef value = make_string(a.getValue(i));
1448         naHash_set(attr, name, value);
1449     }
1450     call(_start_element, 2, make_string(tag), attr);
1451 }
1452
1453 void NasalXMLVisitor::endElement(const char* tag)
1454 {
1455     if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag));
1456 }
1457
1458 void NasalXMLVisitor::data(const char* str, int len)
1459 {
1460     if(!naIsNil(_data)) call(_data, 1, make_string(str, len));
1461 }
1462
1463 void NasalXMLVisitor::pi(const char* target, const char* data)
1464 {
1465     if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data));
1466 }
1467
1468 void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b)
1469 {
1470     naRef args[2];
1471     args[0] = a;
1472     args[1] = b;
1473     naCall(_c, func, num, args, naNil(), naNil());
1474     if(naGetError(_c))
1475         naRethrowError(_c);
1476 }
1477
1478 naRef NasalXMLVisitor::make_string(const char* s, int n)
1479 {
1480     return naStr_fromdata(naNewString(_c), const_cast<char *>(s),
1481                           n < 0 ? strlen(s) : n);
1482 }
1483
1484