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