]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
53b9f835728aa058df89fb51b76ea2a004a72ce3
[flightgear.git] / src / Scripting / NasalSys.cxx
1 #include <string.h>
2 #include <stdio.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5
6 #include <plib/ul.h>
7
8 #include <simgear/nasal/nasal.h>
9 #include <simgear/props/props.hxx>
10 #include <simgear/math/sg_random.h>
11 #include <simgear/misc/sg_path.hxx>
12 #include <simgear/misc/interpolator.hxx>
13 #include <simgear/structure/commands.hxx>
14
15 #include <Main/globals.hxx>
16 #include <Main/fg_props.hxx>
17
18 #include "NasalSys.hxx"
19
20 // Read and return file contents in a single buffer.  Note use of
21 // stat() to get the file size.  This is a win32 function, believe it
22 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
23 // Text mode brain damage will kill us if we're trying to do bytewise
24 // I/O.
25 static char* readfile(const char* file, int* lenOut)
26 {
27     struct stat data;
28     if(stat(file, &data) != 0) return 0;
29     FILE* f = fopen(file, "rb");
30     if(!f) return 0;
31     char* buf = new char[data.st_size];
32     *lenOut = fread(buf, 1, data.st_size, f);
33     fclose(f);
34     if(*lenOut != data.st_size) {
35         // Shouldn't happen, but warn anyway since it represents a
36         // platform bug and not a typical runtime error (missing file,
37         // etc...)
38         SG_LOG(SG_NASAL, SG_ALERT,
39                "ERROR in Nasal initialization: " <<
40                "short count returned from fread() of " << file <<
41                ".  Check your C library!");
42         delete[] buf;
43         return 0;
44     }
45     return buf;
46 }
47
48 FGNasalSys::FGNasalSys()
49 {
50     _context = 0;
51     _globals = naNil();
52     _gcHash = naNil();
53     _nextGCKey = 0; // Any value will do
54 }
55
56 FGNasalSys::~FGNasalSys()
57 {
58     // Nasal doesn't have a "destroy context" API yet. :(
59     // Not a problem for a global subsystem that will never be
60     // destroyed.  And the context is actually a global, so no memory
61     // is technically leaked (although the GC pool memory obviously
62     // won't be freed).
63     _context = 0;
64     _globals = naNil();
65 }
66
67 bool FGNasalSys::parseAndRun(const char* sourceCode)
68 {
69     naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
70                        strlen(sourceCode));
71     if(naIsNil(code))
72         return false;
73
74     naCall(_context, code, 0, 0, naNil(), naNil());
75
76     if(!naGetError(_context)) return true;
77     logError();
78     return false;
79 }
80
81 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
82 {
83     FGNasalScript* script = new FGNasalScript();
84     script->_gcKey = -1; // important, if we delete it on a parse
85     script->_nas = this; // error, don't clobber a real handle!
86
87     char buf[256];
88     if(!name) {
89         sprintf(buf, "FGNasalScript@%p", script);
90         name = buf;
91     }
92
93     script->_code = parse(name, src, strlen(src));
94     if(naIsNil(script->_code)) {
95         delete script;
96         return 0;
97     }
98
99     script->_gcKey = gcSave(script->_code);
100     return script;
101 }
102
103 // Utility.  Sets a named key in a hash by C string, rather than nasal
104 // string object.
105 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
106 {
107     naRef s = naNewString(_context);
108     naStr_fromdata(s, (char*)key, strlen(key));
109     naHash_set(hash, s, val);
110 }
111
112 // The get/setprop functions accept a *list* of strings and walk
113 // through the property tree with them to find the appropriate node.
114 // This allows a Nasal object to hold onto a property path and use it
115 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02).  This
116 // is the utility function that walks the property tree.
117 // Future enhancement: support integer arguments to specify array
118 // elements.
119 static SGPropertyNode* findnode(naContext c, naRef* vec, int len)
120 {
121     SGPropertyNode* p = globals->get_props();
122     for(int i=0; i<len; i++) {
123         naRef a = vec[i];
124         if(!naIsString(a)) return 0;
125         p = p->getNode(naStr_data(a));
126         if(p == 0) return 0;
127     }
128     return p;
129 }
130
131 // getprop() extension function.  Concatenates its string arguments as
132 // property names and returns the value of the specified property.  Or
133 // nil if it doesn't exist.
134 static naRef f_getprop(naContext c, naRef me, int argc, naRef* args)
135 {
136     const SGPropertyNode* p = findnode(c, args, argc);
137     if(!p) return naNil();
138
139     switch(p->getType()) {
140     case SGPropertyNode::BOOL:   case SGPropertyNode::INT:
141     case SGPropertyNode::LONG:   case SGPropertyNode::FLOAT:
142     case SGPropertyNode::DOUBLE:
143         return naNum(p->getDoubleValue());
144
145     case SGPropertyNode::STRING:
146     case SGPropertyNode::UNSPECIFIED:
147         {
148             naRef nastr = naNewString(c);
149             const char* val = p->getStringValue();
150             naStr_fromdata(nastr, (char*)val, strlen(val));
151             return nastr;
152         }
153     case SGPropertyNode::ALIAS: // <--- FIXME, recurse?
154     default:
155         return naNil();
156     }
157 }
158
159 // setprop() extension function.  Concatenates its string arguments as
160 // property names and sets the value of the specified property to the
161 // final argument.
162 static naRef f_setprop(naContext c, naRef me, int argc, naRef* args)
163 {
164 #define BUFLEN 1024
165     char buf[BUFLEN + 1];
166     buf[BUFLEN] = 0;
167     char* p = buf;
168     int buflen = BUFLEN;
169     for(int i=0; i<argc-1; i++) {
170         naRef s = naStringValue(c, args[i]);
171         if(naIsNil(s)) return naNil();
172         strncpy(p, naStr_data(s), buflen);
173         p += naStr_len(s);
174         buflen = BUFLEN - (p - buf);
175         if(i < (argc-2) && buflen > 0) {
176             *p++ = '/';
177             buflen--;
178         }
179     }
180
181     SGPropertyNode* props = globals->get_props();
182     naRef val = args[argc-1];
183     if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
184     else                props->setDoubleValue(buf, naNumValue(val).num);
185     return naNil();
186 #undef BUFLEN
187 }
188
189 // print() extension function.  Concatenates and prints its arguments
190 // to the FlightGear log.  Uses the highest log level (SG_ALERT), to
191 // make sure it appears.  Is there better way to do this?
192 static naRef f_print(naContext c, naRef me, int argc, naRef* args)
193 {
194 #define BUFLEN 1024
195     char buf[BUFLEN + 1];
196     buf[BUFLEN] = 0; // extra nul to handle strncpy brain damage
197     buf[0] = 0; // Zero-length in case there are no arguments
198     char* p = buf;
199     int buflen = BUFLEN;
200     int n = argc;
201     for(int i=0; i<n; i++) {
202         naRef s = naStringValue(c, args[i]);
203         if(naIsNil(s)) continue;
204         strncpy(p, naStr_data(s), buflen);
205         p += naStr_len(s);
206         buflen = BUFLEN - (p - buf);
207         if(buflen <= 0) break;
208     }
209     SG_LOG(SG_GENERAL, SG_ALERT, buf);
210     return naNil();
211 #undef BUFLEN
212 }
213
214 // fgcommand() extension function.  Executes a named command via the
215 // FlightGear command manager.  Takes a single property node name as
216 // an argument.
217 static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args)
218 {
219     if(argc < 2 || !naIsString(args[0]) || !naIsGhost(args[1]))
220         naRuntimeError(c, "bad arguments to fgcommand()");
221     naRef cmd = args[0], props = args[1];
222     SGPropertyNode_ptr* node = (SGPropertyNode_ptr*)naGhost_ptr(props);
223     globals->get_commands()->execute(naStr_data(cmd), *node);
224     return naNil();
225
226 }
227
228 // settimer(func, dt, simtime) extension function.  Falls through to
229 // FGNasalSys::setTimer().  See there for docs.
230 static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
231 {
232     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
233     nasal->setTimer(argc, args);
234     return naNil();
235 }
236
237 // setlistener(func, property) extension function.  Falls through to
238 // FGNasalSys::setListener().  See there for docs.
239 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
240 {
241     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
242     nasal->setListener(argc, args);
243     return naNil();
244 }
245
246 // Returns a ghost handle to the argument to the currently executing
247 // command
248 static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
249 {
250     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
251     return nasal->cmdArgGhost();
252 }
253
254 // Sets up a property interpolation.  The first argument is either a
255 // ghost (SGPropertyNode_ptr*) or a string (global property path) to
256 // interpolate.  The second argument is a vector of pairs of
257 // value/delta numbers.
258 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
259 {
260     SGPropertyNode* node;
261     naRef prop = argc > 0 ? args[0] : naNil();
262     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
263     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
264     else return naNil();
265
266     naRef curve = argc > 1 ? args[1] : naNil();
267     if(!naIsVector(curve)) return naNil();
268     int nPoints = naVec_size(curve) / 2;
269     double* values = new double[nPoints];
270     double* deltas = new double[nPoints];
271     for(int i=0; i<nPoints; i++) {
272         values[i] = naNumValue(naVec_get(curve, 2*i)).num;
273         deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
274     }
275
276     ((SGInterpolator*)globals->get_subsystem("interpolator"))
277         ->interpolate(node, nPoints, values, deltas);
278
279     return naNil();
280 }
281
282 // This is a better RNG than the one in the default Nasal distribution
283 // (which is based on the C library rand() implementation). It will
284 // override.
285 static naRef f_rand(naContext c, naRef me, int argc, naRef* args)
286 {
287     return naNum(sg_random());
288 }
289
290 // Table of extension functions.  Terminate with zeros.
291 static struct { char* name; naCFunction func; } funcs[] = {
292     { "getprop",   f_getprop },
293     { "setprop",   f_setprop },
294     { "print",     f_print },
295     { "_fgcommand", f_fgcommand },
296     { "settimer",  f_settimer },
297     { "_setlistener", f_setlistener },
298     { "_cmdarg",  f_cmdarg },
299     { "_interpolate",  f_interpolate },
300     { "rand",  f_rand },
301     { 0, 0 }
302 };
303
304 naRef FGNasalSys::cmdArgGhost()
305 {
306     return propNodeGhost(_cmdArg);
307 }
308
309 void FGNasalSys::init()
310 {
311     int i;
312
313     _context = naNewContext();
314
315     // Start with globals.  Add it to itself as a recursive
316     // sub-reference under the name "globals".  This gives client-code
317     // write access to the namespace if someone wants to do something
318     // fancy.
319     _globals = naStdLib(_context);
320     naSave(_context, _globals);
321     hashset(_globals, "globals", _globals);
322
323     // Add in the math library under "math"
324     hashset(_globals, "math", naMathLib(_context));
325
326     // Add our custom extension functions:
327     for(i=0; funcs[i].name; i++)
328         hashset(_globals, funcs[i].name,
329                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
330
331     // And our SGPropertyNode wrapper
332     hashset(_globals, "props", genPropsModule());
333
334     // Make a "__gcsave" hash to hold the naRef objects which get
335     // passed to handles outside the interpreter (to protect them from
336     // begin garbage-collected).
337     _gcHash = naNewHash(_context);
338     hashset(_globals, "__gcsave", _gcHash);
339
340     // Now load the various source files in the Nasal directory
341     SGPath p(globals->get_fg_root());
342     p.append("Nasal");
343     ulDirEnt* dent;
344     ulDir* dir = ulOpenDir(p.c_str());
345     while(dir && (dent = ulReadDir(dir)) != 0) {
346         SGPath fullpath(p);
347         fullpath.append(dent->d_name);
348         SGPath file(dent->d_name);
349         if(file.extension() != "nas") continue;
350         loadModule(fullpath, file.base().c_str());
351     }
352
353     // Pull scripts out of the property tree, too
354     loadPropertyScripts();
355 }
356
357 // Loads the scripts found under /nasal in the global tree
358 void FGNasalSys::loadPropertyScripts()
359 {
360     SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
361     if(!nasal) return;
362
363     for(int i=0; i<nasal->nChildren(); i++) {
364         SGPropertyNode* n = nasal->getChild(i);
365
366         const char* module = n->getName();
367         if(n->hasChild("module"))
368             module = n->getStringValue("module");
369
370         // allow multiple files to be specified within in a single
371         // Nasal module tag
372         int j = 0;
373         SGPropertyNode *fn;
374         bool file_specified = false;
375         while ( (fn = n->getChild("file", j)) != NULL ) {
376             file_specified = true;
377             const char* file = fn->getStringValue();
378             SGPath p(globals->get_fg_root());
379             p.append(file);
380             loadModule(p, module);
381             j++;
382         }
383
384         // Old code which only allowed a single file to be specified per module
385         /*
386         const char* file = n->getStringValue("file");
387         if(!n->hasChild("file")) file = 0; // Hrm...
388         if(file) {
389             SGPath p(globals->get_fg_root());
390             p.append(file);
391             loadModule(p, module);
392         }
393         */
394         
395         const char* src = n->getStringValue("script");
396         if(!n->hasChild("script")) src = 0; // Hrm...
397         if(src)
398             createModule(module, n->getPath(), src, strlen(src));
399
400         if(!file_specified && !src)
401             SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
402                    "no <file> or <script> defined in " <<
403                    "/nasal/" << module);
404     }
405 }
406
407 // Logs a runtime error, with stack trace, to the FlightGear log stream
408 void FGNasalSys::logError()
409 {
410     SG_LOG(SG_NASAL, SG_ALERT,
411            "Nasal runtime error: " << naGetError(_context));
412     SG_LOG(SG_NASAL, SG_ALERT,
413            "  at " << naStr_data(naGetSourceFile(_context, 0)) <<
414            ", line " << naGetLine(_context, 0));
415     for(int i=1; i<naStackDepth(_context); i++)
416         SG_LOG(SG_NASAL, SG_ALERT,
417                "  called from: " << naStr_data(naGetSourceFile(_context, i)) <<
418                ", line " << naGetLine(_context, i));
419 }
420
421 // Reads a script file, executes it, and places the resulting
422 // namespace into the global namespace under the specified module
423 // name.
424 void FGNasalSys::loadModule(SGPath file, const char* module)
425 {
426     int len = 0;
427     char* buf = readfile(file.c_str(), &len);
428     if(!buf) {
429         SG_LOG(SG_NASAL, SG_ALERT,
430                "Nasal error: could not read script file " << file.c_str()
431                << " into module " << module);
432         return;
433     }
434
435     createModule(module, file.c_str(), buf, len);
436     delete[] buf;
437 }
438
439 // Parse and run.  Save the local variables namespace, as it will
440 // become a sub-object of globals.
441 void FGNasalSys::createModule(const char* moduleName, const char* fileName,
442                               const char* src, int len)
443 {
444     naRef code = parse(fileName, src, len);
445     if(naIsNil(code))
446         return;
447
448     // See if we already have a module hash to use.  This allows the
449     // user to, for example, add functions to the built-in math
450     // module.  Make a new one if necessary.
451     naRef locals;
452     naRef modname = naNewString(_context);
453     naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
454     if(!naHash_get(_globals, modname, &locals))
455         locals = naNewHash(_context);
456
457     naCall(_context, code, 0, 0, naNil(), locals);
458     if(naGetError(_context)) {
459         logError();
460         return;
461     }
462     hashset(_globals, moduleName, locals);
463 }
464
465 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
466 {
467     int errLine = -1;
468     naRef srcfile = naNewString(_context);
469     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
470     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
471     if(naIsNil(code)) {
472         SG_LOG(SG_NASAL, SG_ALERT,
473                "Nasal parse error: " << naGetError(_context) <<
474                " in "<< filename <<", line " << errLine);
475         return naNil();
476     }
477
478     // Bind to the global namespace before returning
479     return naBindFunction(_context, code, _globals);
480 }
481
482 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
483 {
484     const char* nasal = arg->getStringValue("script");
485     const char* moduleName = arg->getStringValue("module");
486     naRef code = parse(arg->getPath(true), nasal, strlen(nasal));
487     if(naIsNil(code)) return false;
488
489     naRef locals = naNil();
490     if (moduleName[0]) {
491         naRef modname = naNewString(_context);
492         naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
493         if(!naHash_get(_globals, modname, &locals))
494             locals = naNewHash(_context);
495     }
496     // Cache the command argument for inspection via cmdarg().  For
497     // performance reasons, we won't bother with it if the invoked
498     // code doesn't need it.
499     _cmdArg = (SGPropertyNode*)arg;
500
501     // Call it!
502     naRef result = naCall(_context, code, 0, 0, naNil(), locals);
503     if(!naGetError(_context)) return true;
504     logError();
505     return false;
506 }
507
508 // settimer(func, dt, simtime) extension function.  The first argument
509 // is a Nasal function to call, the second is a delta time (from now),
510 // in seconds.  The third, if present, is a boolean value indicating
511 // that "real world" time (rather than simulator time) is to be used.
512 //
513 // Implementation note: the FGTimer objects don't live inside the
514 // garbage collector, so the Nasal handler functions have to be
515 // "saved" somehow lest they be inadvertently cleaned.  In this case,
516 // they are inserted into a globals.__gcsave hash and removed on
517 // expiration.
518 void FGNasalSys::setTimer(int argc, naRef* args)
519 {
520     // Extract the handler, delta, and simtime arguments:
521     naRef handler = argc > 0 ? args[0] : naNil();
522     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
523         return;
524
525     naRef delta = argc > 1 ? args[1] : naNil();
526     if(naIsNil(delta)) return;
527     
528     bool simtime = (argc > 2 && naTrue(args[2])) ? false : true;
529
530     // Generate and register a C++ timer handler
531     NasalTimer* t = new NasalTimer;
532     t->handler = handler;
533     t->gcKey = gcSave(handler);
534     t->nasal = this;
535
536     globals->get_event_mgr()->addEvent("NasalTimer",
537                                        t, &NasalTimer::timerExpired,
538                                        delta.num, simtime);
539 }
540
541 void FGNasalSys::handleTimer(NasalTimer* t)
542 {
543     naCall(_context, t->handler, 0, 0, naNil(), naNil());
544     if(naGetError(_context))
545         logError();
546     gcRelease(t->gcKey);
547 }
548
549 int FGNasalSys::gcSave(naRef r)
550 {
551     int key = _nextGCKey++;
552     naHash_set(_gcHash, naNum(key), r);
553     return key;
554 }
555
556 void FGNasalSys::gcRelease(int key)
557 {
558     naHash_delete(_gcHash, naNum(key));
559 }
560
561 void FGNasalSys::NasalTimer::timerExpired()
562 {
563     nasal->handleTimer(this);
564     delete this;
565 }
566
567 // setlistener(property, func) extension function.  The first argument
568 // is either a ghost (SGPropertyNode_ptr*) or a string (global property
569 // path), the second is a Nasal function.
570 void FGNasalSys::setListener(int argc, naRef* args)
571 {
572     SGPropertyNode* node;
573     naRef prop = argc > 0 ? args[0] : naNil();
574     if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
575     else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
576     else return;
577
578     naRef handler = argc > 1 ? args[1] : naNil();
579     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
580         return;
581
582     node->addChangeListener(new FGNasalListener(handler, this, gcSave(handler)));
583 }
584