]> git.mxchange.org Git - flightgear.git/blobdiff - src/Scripting/NasalSys.cxx
Fix for a premature deletion bug. The _arg SGPropertyNode* is passed
[flightgear.git] / src / Scripting / NasalSys.cxx
index e481ac510a5f0384a73dadbe4baa4c7efa4b6136..938c740e1ac119d0cb87021a67d674083ed4b30a 100644 (file)
@@ -7,10 +7,13 @@
 
 #include <simgear/nasal/nasal.h>
 #include <simgear/props/props.hxx>
+#include <simgear/math/sg_random.h>
 #include <simgear/misc/sg_path.hxx>
+#include <simgear/misc/interpolator.hxx>
 #include <simgear/structure/commands.hxx>
 
 #include <Main/globals.hxx>
+#include <Main/fg_props.hxx>
 
 #include "NasalSys.hxx"
 
@@ -34,7 +37,8 @@ static char* readfile(const char* file, int* lenOut)
         // etc...)
         SG_LOG(SG_NASAL, SG_ALERT,
                "ERROR in Nasal initialization: " <<
-               "short count returned from fread().  Check your C library!");
+               "short count returned from fread() of " << file <<
+               ".  Check your C library!");
         delete[] buf;
         return 0;
     }
@@ -45,8 +49,8 @@ FGNasalSys::FGNasalSys()
 {
     _context = 0;
     _globals = naNil();
-    _timerHash = naNil();
-    _nextTimerHashKey = 0; // Any value will do
+    _gcHash = naNil();
+    _nextGCKey = 0; // Any value will do
 }
 
 FGNasalSys::~FGNasalSys()
@@ -60,6 +64,42 @@ FGNasalSys::~FGNasalSys()
     _globals = naNil();
 }
 
+bool FGNasalSys::parseAndRun(const char* sourceCode)
+{
+    naRef code = parse("FGNasalSys::parseAndRun()", sourceCode,
+                       strlen(sourceCode));
+    if(naIsNil(code))
+        return false;
+
+    naCall(_context, code, naNil(), naNil(), naNil());
+
+    if(!naGetError(_context)) return true;
+    logError();
+    return false;
+}
+
+FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
+{
+    FGNasalScript* script = new FGNasalScript();
+    script->_gcKey = -1; // important, if we delete it on a parse
+    script->_nas = this; // error, don't clobber a real handle!
+
+    char buf[256];
+    if(!name) {
+        sprintf(buf, "FGNasalScript@%8.8x", (int)script);
+        name = buf;
+    }
+
+    script->_code = parse(name, src);
+    if(naIsNil(script->_code)) {
+        delete script;
+        return 0;
+    }
+
+    script->_gcKey = gcSave(script->_code);
+    return script;
+}
+
 // Utility.  Sets a named key in a hash by C string, rather than nasal
 // string object.
 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
@@ -176,13 +216,11 @@ static naRef f_fgcommand(naContext c, naRef args)
 {
     naRef cmd = naVec_get(args, 0);
     naRef props = naVec_get(args, 1);
-    if(!naIsString(cmd) || !naIsString(props)) return naNil();
-
-    SGPropertyNode* pnode =
-        globals->get_props()->getNode(naStr_data(props));
-    if(pnode)
-        globals->get_commands()->execute(naStr_data(cmd), pnode);
+    if(!naIsString(cmd) || !naIsGhost(props)) return naNil();
+    SGPropertyNode_ptr* node = (SGPropertyNode_ptr*)naGhost_ptr(props);
+    globals->get_commands()->execute(naStr_data(cmd), *node);
     return naNil();
+
 }
 
 // settimer(func, dt, simtime) extension function.  Falls through to
@@ -194,18 +232,67 @@ static naRef f_settimer(naContext c, naRef args)
     return naNil();
 }
 
+// Returns a ghost handle to the argument to the currently executing
+// command
+static naRef f_cmdarg(naContext c, naRef args)
+{
+    FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
+    return nasal->cmdArgGhost();
+}
+
+// Sets up a property interpolation.  The first argument is either a
+// ghost (SGPropertyNode_ptr*) or a string (global property path) to
+// interpolate.  The second argument is a vector of pairs of
+// value/delta numbers.
+static naRef f_interpolate(naContext c, naRef args)
+{
+    SGPropertyNode* node;
+    naRef prop = naVec_get(args, 0);
+    if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
+    else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
+    else return naNil();
+
+    naRef curve = naVec_get(args, 1);
+    if(!naIsVector(curve)) return naNil();
+    int nPoints = naVec_size(curve) / 2;
+    double* values = new double[nPoints];
+    double* deltas = new double[nPoints];
+    for(int i=0; i<nPoints; i++) {
+        values[i] = naNumValue(naVec_get(curve, 2*i)).num;
+        deltas[i] = naNumValue(naVec_get(curve, 2*i+1)).num;
+    }
+
+    ((SGInterpolator*)globals->get_subsystem("interpolator"))
+        ->interpolate(node, nPoints, values, deltas);
+}
+
+static naRef f_rand(naContext c, naRef args)
+{
+    return naNum(sg_random());
+}
+
 // Table of extension functions.  Terminate with zeros.
 static struct { char* name; naCFunction func; } funcs[] = {
     { "getprop",   f_getprop },
     { "setprop",   f_setprop },
     { "print",     f_print },
-    { "fgcommand", f_fgcommand },
+    { "_fgcommand", f_fgcommand },
     { "settimer",  f_settimer },
+    { "_cmdarg",  f_cmdarg },
+    { "_interpolate",  f_interpolate },
+    { "rand",  f_rand },
     { 0, 0 }
 };
 
+naRef FGNasalSys::cmdArgGhost()
+{
+    return propNodeGhost(_cmdArg);
+}
+
 void FGNasalSys::init()
 {
+    int i;
+
     _context = naNewContext();
 
     // Start with globals.  Add it to itself as a recursive
@@ -220,14 +307,18 @@ void FGNasalSys::init()
     hashset(_globals, "math", naMathLib(_context));
 
     // Add our custom extension functions:
-    for(int i=0; funcs[i].name; i++)
+    for(i=0; funcs[i].name; i++)
         hashset(_globals, funcs[i].name,
                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
 
-    // Make a "__timers" hash to hold the settimer() handlers (to
-    // protect them from begin garbage-collected).
-    _timerHash = naNewHash(_context);
-    hashset(_globals, "__timers", _timerHash);
+    // And our SGPropertyNode wrapper
+    hashset(_globals, "props", genPropsModule());
+
+    // Make a "__gcsave" hash to hold the naRef objects which get
+    // passed to handles outside the interpreter (to protect them from
+    // begin garbage-collected).
+    _gcHash = naNewHash(_context);
+    hashset(_globals, "__gcsave", _gcHash);
 
     // Now load the various source files in the Nasal directory
     SGPath p(globals->get_fg_root());
@@ -241,6 +332,42 @@ void FGNasalSys::init()
         if(file.extension() != "nas") continue;
         readScriptFile(fullpath, file.base().c_str());
     }
+
+    // Pull scripts out of the property tree, too
+    loadPropertyScripts();
+}
+
+// Loads the scripts found under /nasal in the global tree
+void FGNasalSys::loadPropertyScripts()
+{
+    SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
+    if(!nasal) return;
+
+    for(int i=0; i<nasal->nChildren(); i++) {
+        SGPropertyNode* n = nasal->getChild(i);
+
+        const char* module = n->getName();
+        if(n->hasChild("module"))
+            module = n->getStringValue("module");
+
+        const char* file = n->getStringValue("file");
+        if(!n->hasChild("file")) file = 0; // Hrm...
+        if(file) {
+            SGPath p(globals->get_fg_root());
+            p.append(file);
+            readScriptFile(p, module);
+        }
+        
+        const char* src = n->getStringValue("script");
+        if(!n->hasChild("script")) src = 0; // Hrm...
+        if(src)
+            initModule(module, n->getPath(), src, strlen(src));
+
+        if(!file && !src)
+            SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " <<
+                   "no <file> or <script> defined in " <<
+                   "/nasal/" << module);
+    }
 }
 
 // Logs a runtime error, with stack trace, to the FlightGear log stream
@@ -260,31 +387,52 @@ void FGNasalSys::logError()
 // Reads a script file, executes it, and places the resulting
 // namespace into the global namespace under the specified module
 // name.
-void FGNasalSys::readScriptFile(SGPath file, const char* lib)
+void FGNasalSys::readScriptFile(SGPath file, const char* module)
 {
     int len = 0;
     char* buf = readfile(file.c_str(), &len);
-    if(!buf) return;
+    if(!buf) {
+        SG_LOG(SG_NASAL, SG_ALERT,
+               "Nasal error: could not read script file " << file.c_str()
+               << " into module " << module);
+        return;
+    }
 
-    // Parse and run.  Save the local variables namespace, as it will
-    // become a sub-object of globals.
-    naRef code = parse(file.c_str(), buf, len);
+    initModule(module, file.c_str(), buf, len);
     delete[] buf;
+}
+
+// Parse and run.  Save the local variables namespace, as it will
+// become a sub-object of globals.
+void FGNasalSys::initModule(const char* moduleName, const char* fileName,
+                            const char* src, int len)
+{
+    if(len == 0) len = strlen(src);
+
+    naRef code = parse(fileName, src, len);
     if(naIsNil(code))
         return;
 
-    naRef locals = naNewHash(_context);
+    // See if we already have a module hash to use.  This allows the
+    // user to, for example, add functions to the built-in math
+    // module.  Make a new one if necessary.
+    naRef locals;
+    naRef modname = naNewString(_context);
+    naStr_fromdata(modname, (char*)moduleName, strlen(moduleName));
+    if(!naHash_get(_globals, modname, &locals))
+        locals = naNewHash(_context);
+
     naCall(_context, code, naNil(), naNil(), locals);
     if(naGetError(_context)) {
         logError();
         return;
     }
-
-    hashset(_globals, lib, locals);
+    hashset(_globals, moduleName, locals);
 }
 
 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
 {
+    if(len == 0) len = strlen(buf);
     int errLine = -1;
     naRef srcfile = naNewString(_context);
     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
@@ -307,26 +455,16 @@ bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
     // location in the property tree.  arg->getPath() returns an empty
     // string.
     const char* nasal = arg->getStringValue("script");
-    naRef code = parse("<command>", nasal, strlen(nasal));
+    naRef code = parse("<command>", nasal);
     if(naIsNil(code)) return false;
     
-    // FIXME: Cache the just-created code object somewhere, but watch
-    // for changes to the source in the property tree.  Maybe store an
-    // integer index into a Nasal vector in the original property
-    // location?
-
-    // Extract the "value" or "offset" arguments if present
-    naRef locals = naNil();
-    if(arg->hasValue("value")) {
-        locals = naNewHash(_context);
-        hashset(locals, "value", naNum(arg->getDoubleValue("value")));
-    } else if(arg->hasValue("offset")) {
-        locals = naNewHash(_context);
-        hashset(locals, "offset", naNum(arg->getDoubleValue("offset")));
-    }
+    // Cache the command argument for inspection via cmdarg().  For
+    // performance reasons, we won't bother with it if the invoked
+    // code doesn't need it.
+    _cmdArg = (SGPropertyNode*)arg;
 
     // Call it!
-    naRef result = naCall(_context, code, naNil(), naNil(), locals);
+    naRef result = naCall(_context, code, naNil(), naNil(), naNil());
     if(!naGetError(_context)) return true;
     logError();
     return false;
@@ -340,7 +478,7 @@ bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
 // Implementation note: the FGTimer objects don't live inside the
 // garbage collector, so the Nasal handler functions have to be
 // "saved" somehow lest they be inadvertently cleaned.  In this case,
-// they are inserted into a globals._timers hash and removed on
+// they are inserted into a globals.__gcsave hash and removed on
 // expiration.
 void FGNasalSys::setTimer(naRef args)
 {
@@ -357,23 +495,30 @@ void FGNasalSys::setTimer(naRef args)
     // Generate and register a C++ timer handler
     NasalTimer* t = new NasalTimer;
     t->handler = handler;
-    t->hashKey = _nextTimerHashKey++;
+    t->gcKey = gcSave(handler);
     t->nasal = this;
 
     globals->get_event_mgr()->addEvent("NasalTimer",
                                        t, &NasalTimer::timerExpired,
                                        delta.num, simtime);
-
-
-    // Save the handler in the globals.__timers hash to prevent
-    // garbage collection.
-    naHash_set(_timerHash, naNum(t->hashKey), handler);
 }
 
 void FGNasalSys::handleTimer(NasalTimer* t)
 {
     naCall(_context, t->handler, naNil(), naNil(), naNil());
-    naHash_delete(_timerHash, naNum(t->hashKey));
+    gcRelease(t->gcKey);
+}
+
+int FGNasalSys::gcSave(naRef r)
+{
+    int key = _nextGCKey++;
+    naHash_set(_gcHash, naNum(key), r);
+    return key;
+}
+
+void FGNasalSys::gcRelease(int key)
+{
+    naHash_delete(_gcHash, naNum(key));
 }
 
 void FGNasalSys::NasalTimer::timerExpired()