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