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