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