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