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