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