]> git.mxchange.org Git - flightgear.git/blobdiff - src/Scripting/NasalSys.cxx
Add window decoration support to Canvas GUI.
[flightgear.git] / src / Scripting / NasalSys.cxx
index 2c98f6369dcd24e5660d7845afa15c1b737a3176..a0ebb47046efce309adcfe9d1e8099755b3ad224 100644 (file)
@@ -3,6 +3,10 @@
 #  include "config.h"
 #endif
 
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+
 #ifdef HAVE_SYS_TIME_H
 #  include <sys/time.h>  // gettimeofday
 #endif
 #include <simgear/math/sg_random.h>
 #include <simgear/misc/sg_path.hxx>
 #include <simgear/misc/sg_dir.hxx>
-#include <simgear/misc/interpolator.hxx>
 #include <simgear/structure/commands.hxx>
 #include <simgear/math/sg_geodesy.hxx>
 #include <simgear/structure/event_mgr.hxx>
+#include <simgear/debug/BufferedLogCallback.hxx>
+
+#include <simgear/nasal/cppbind/from_nasal.hxx>
+#include <simgear/nasal/cppbind/to_nasal.hxx>
+#include <simgear/nasal/cppbind/Ghost.hxx>
+#include <simgear/nasal/cppbind/NasalHash.hxx>
 
 #include "NasalSys.hxx"
+#include "NasalSys_private.hxx"
+#include "NasalModelData.hxx"
 #include "NasalPositioned.hxx"
 #include "NasalCanvas.hxx"
 #include "NasalClipboard.hxx"
@@ -35,7 +46,6 @@
 #include <Main/util.hxx>
 #include <Main/fg_props.hxx>
 
-
 using std::map;
 
 void postinitNasalGUI(naRef globals, naContext c);
@@ -67,6 +77,96 @@ void FGNasalModuleListener::valueChanged(SGPropertyNode*)
     }
 }
 
+//////////////////////////////////////////////////////////////////////////
+
+
+class TimerObj : public SGReferenced
+{
+public:
+  TimerObj(FGNasalSys* sys, naRef f, naRef self, double interval) :
+    _sys(sys),
+    _func(f),
+    _self(self),
+    _isRunning(false),
+    _interval(interval),
+    _singleShot(false)
+  {
+    char nm[128];
+    snprintf(nm, 128, "nasal-timer-%p", this);
+    _name = nm;
+    _gcRoot =  sys->gcSave(f);
+    _gcSelf = sys->gcSave(self);
+  }
+  
+  virtual ~TimerObj()
+  {
+    stop();
+    _sys->gcRelease(_gcRoot);
+    _sys->gcRelease(_gcSelf);
+  }
+  
+  bool isRunning() const { return _isRunning; }
+    
+  void stop()
+  {
+    if (_isRunning) {
+      globals->get_event_mgr()->removeTask(_name);
+      _isRunning = false;
+    }
+  }
+  
+  void start()
+  {
+    if (_isRunning) {
+      return;
+    }
+    
+    _isRunning = true;
+    if (_singleShot) {
+      globals->get_event_mgr()->addEvent(_name, this, &TimerObj::invoke, _interval);
+    } else {
+      globals->get_event_mgr()->addTask(_name, this, &TimerObj::invoke, _interval);
+    }
+  }
+  
+  // stop and then start -
+  void restart(double newInterval)
+  {
+    _interval = newInterval;
+    stop();
+    start();
+  }
+  
+  void invoke()
+  {
+    naRef *args = NULL;
+    _sys->callMethod(_func, _self, 0, args, naNil() /* locals */);
+    if (_singleShot) {
+      _isRunning = false;
+    }
+  }
+  
+  void setSingleShot(bool aSingleShot)
+  {
+    _singleShot = aSingleShot;
+  }
+  
+  bool isSingleShot() const
+  { return _singleShot; }
+private:
+  std::string _name;
+  FGNasalSys* _sys;
+  naRef _func, _self;
+  int _gcRoot, _gcSelf;
+  bool _isRunning;
+  double _interval;
+  bool _singleShot;
+};
+
+typedef SGSharedPtr<TimerObj> TimerObjRef;
+typedef nasal::Ghost<TimerObjRef> NasalTimerObj;
+
+///////////////////////////////////////////////////////////////////////////
 
 // Read and return file contents in a single buffer.  Note use of
 // stat() to get the file size.  This is a win32 function, believe it
@@ -105,6 +205,10 @@ FGNasalSys::FGNasalSys()
     _gcHash = naNil();
     _nextGCKey = 0; // Any value will do
     _callCount = 0;
+    
+    _log = new simgear::BufferedLogCallback(SG_NASAL, SG_INFO);
+    _log->truncateAt(255);
+    sglog().addCallback(_log);
 }
 
 // Utility.  Sets a named key in a hash by C string, rather than nasal
@@ -169,6 +273,7 @@ bool FGNasalSys::parseAndRun(const char* sourceCode)
     return true;
 }
 
+#if 0
 FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
 {
     FGNasalScript* script = new FGNasalScript();
@@ -190,6 +295,7 @@ FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
     script->_gcKey = gcSave(script->_code);
     return script;
 }
+#endif
 
 // The get/setprop functions accept a *list* of strings and walk
 // through the property tree with them to find the appropriate node.
@@ -330,7 +436,11 @@ static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
     if(naIsNil(s)) continue;
     buf += naStr_data(s);
   }
-  SG_LOG(SG_NASAL, (sgDebugPriority) priority.num, buf);
+// use the nasal source file and line for the message location, since
+// that's more useful than the location here!
+  sglog().log(SG_NASAL, (sgDebugPriority)(int) priority.num,
+               naStr_data(naGetSourceFile(c, 0)),
+               naGetLine(c, 0), buf);
   return naNum(buf.length());
 }
 
@@ -362,6 +472,24 @@ static naRef f_settimer(naContext c, naRef me, int argc, naRef* args)
     return naNil();
 }
 
+static naRef f_makeTimer(naContext c, naRef me, int argc, naRef* args)
+{
+  if (!naIsNum(args[0])) {
+    naRuntimeError(c, "bad interval argument to maketimer");
+  }
+    
+  naRef func, self = naNil();
+  if (naIsFunc(args[1])) {
+    func = args[1];
+  } else if ((argc == 3) && naIsFunc(args[2])) {
+    self = args[1];
+    func = args[2];
+  }
+  
+  TimerObj* timerObj = new TimerObj(nasalSys, func, self, args[0].num);
+  return NasalTimerObj::create(c, timerObj);
+}
+
 // setlistener(func, property, bool) extension function.  Falls through to
 // FGNasalSys::setListener().  See there for docs.
 static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args)
@@ -389,29 +517,31 @@ static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args)
 // value/delta numbers.
 static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args)
 {
-    SGPropertyNode* node;
-    naRef prop = argc > 0 ? args[0] : naNil();
-    if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
-    else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
-    else return naNil();
-
-    naRef curve = argc > 1 ? args[1] : naNil();
-    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_mgr()
-        ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
-        ->interpolate(node, nPoints, values, deltas);
+  SGPropertyNode* node;
+  naRef prop = argc > 0 ? args[0] : naNil();
+  if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true);
+  else if(naIsGhost(prop)) node = *(SGPropertyNode_ptr*)naGhost_ptr(prop);
+  else return naNil();
+
+  naRef curve = argc > 1 ? args[1] : naNil();
+  if(!naIsVector(curve)) return naNil();
+  int nPoints = naVec_size(curve) / 2;
+
+  simgear::PropertyList value_nodes;
+  value_nodes.reserve(nPoints);
+  double_list deltas;
+  deltas.reserve(nPoints);
+
+  for( int i = 0; i < nPoints; ++i )
+  {
+    SGPropertyNode* val = new SGPropertyNode;
+    val->setDoubleValue(naNumValue(naVec_get(curve, 2*i)).num);
+    value_nodes.push_back(val);
+    deltas.push_back(naNumValue(naVec_get(curve, 2*i+1)).num);
+  }
 
-    delete[] values;
-    delete[] deltas;
-    return naNil();
+  node->interpolate("numeric", value_nodes, deltas, "linear");
+  return naNil();
 }
 
 // This is a better RNG than the one in the default Nasal distribution
@@ -466,6 +596,60 @@ static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args)
     return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
 }
 
+class NasalCommand : public SGCommandMgr::Command
+{
+public:
+    NasalCommand(FGNasalSys* sys, naRef f) :
+        _sys(sys),
+        _func(f)
+    {
+        _gcRoot =  sys->gcSave(f);
+    }
+    
+    virtual ~NasalCommand()
+    {
+        _sys->gcRelease(_gcRoot);
+    }
+    
+    virtual bool operator()(const SGPropertyNode* aNode)
+    {
+        _sys->setCmdArg(const_cast<SGPropertyNode*>(aNode));
+        naRef args[1];
+        args[0] = _sys->wrappedPropsNode(const_cast<SGPropertyNode*>(aNode));
+    
+        _sys->callMethod(_func, naNil(), 1, args, naNil() /* locals */);
+
+        return true;
+    }
+    
+private:
+    FGNasalSys* _sys;
+    naRef _func;
+    int _gcRoot;
+};
+
+static naRef f_addCommand(naContext c, naRef me, int argc, naRef* args)
+{
+    if(argc != 2 || !naIsString(args[0]) || !naIsFunc(args[1]))
+        naRuntimeError(c, "bad arguments to addcommand()");
+    
+    naRef func = args[1];
+    NasalCommand* cmd = new NasalCommand(nasalSys, func);
+    globals->get_commands()->addCommandObject(naStr_data(args[0]), cmd);
+    return naNil();
+}
+
+static naRef f_removeCommand(naContext c, naRef me, int argc, naRef* args)
+{
+    SGCommandMgr::Command* cmd = globals->get_commands()->getCommand(naStr_data(args[0]));
+
+  //  SGCommandMgr::Command* cmd = globals->get_commands()->removeCommand(naStr_data(args[0]))
+    
+    delete cmd;
+    
+    return naNil();
+}
+
 // Parse XML file.
 //     parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]);
 //
@@ -528,8 +712,11 @@ static struct { const char* name; naCFunction func; } funcs[] = {
     { "logprint",  f_logprint },
     { "_fgcommand", f_fgcommand },
     { "settimer",  f_settimer },
+    { "maketimer", f_makeTimer },
     { "_setlistener", f_setlistener },
     { "removelistener", f_removelistener },
+    { "addcommand", f_addCommand },
+    { "removecommand", f_removeCommand },
     { "_cmdarg",  f_cmdarg },
     { "_interpolate",  f_interpolate },
     { "rand",  f_rand },
@@ -547,6 +734,11 @@ naRef FGNasalSys::cmdArgGhost()
     return propNodeGhost(_cmdArg);
 }
 
+void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
+{
+    _cmdArg = aNode;
+}
+
 void FGNasalSys::init()
 {
     int i;
@@ -587,10 +779,18 @@ void FGNasalSys::init()
     initNasalString(_globals, _string, _context, _gcHash);
 
     initNasalPositioned(_globals, _context, _gcHash);
+    initNasalPositioned_cppbind(_globals, _context, _gcHash);
     NasalClipboard::init(this);
     initNasalCanvas(_globals, _context, _gcHash);
     initNasalCondition(_globals, _context, _gcHash);
   
+    NasalTimerObj::init("Timer")
+      .method("start", &TimerObj::start)
+      .method("stop", &TimerObj::stop)
+      .method("restart", &TimerObj::restart)
+      .member("singleShot", &TimerObj::isSingleShot, &TimerObj::setSingleShot)
+      .member("isRunning", &TimerObj::isRunning);
+  
     // Now load the various source files in the Nasal directory
     simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal"));
     loadScriptDirectory(nasalDir);
@@ -618,6 +818,19 @@ void FGNasalSys::init()
     postinitNasalGUI(_globals, _context);
 }
 
+naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps)
+{
+    static naRef wrapNodeFunc = naNil();
+    if (naIsNil(wrapNodeFunc)) {
+        nasal::Hash props = getGlobals().get<nasal::Hash>("props");
+        wrapNodeFunc = props.get("wrapNode");
+    }
+    
+    naRef args[1];
+    args[0] = propNodeGhost(aProps);
+    return naCall(_context, wrapNodeFunc, 1, args, naNil(), naNil());
+}
+
 void FGNasalSys::update(double)
 {
     if( NasalClipboard::getInstance() )
@@ -631,8 +844,11 @@ void FGNasalSys::update(double)
 
     if (!_loadList.empty())
     {
-        // process Nasal load hook (only one per update loop to avoid excessive lags)
-        _loadList.pop()->load();
+        if( _delay_load )
+          _delay_load = false;
+        else
+          // process Nasal load hook (only one per update loop to avoid excessive lags)
+          _loadList.pop()->load();
     }
     else
     if (!_unloadList.empty())
@@ -1025,8 +1241,19 @@ naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args)
     return naNum(_listener.size());
 }
 
+void FGNasalSys::registerToLoad(FGNasalModelData *data)
+{
+  if( _loadList.empty() )
+    _delay_load = true;
+  _loadList.push(data);
+}
 
+void FGNasalSys::registerToUnload(FGNasalModelData *data)
+{
+    _unloadList.push(data);
+}
 
+//////////////////////////////////////////////////////////////////////////
 // FGNasalListener class.
 
 FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code,
@@ -1123,90 +1350,6 @@ bool FGNasalListener::changed(SGPropertyNode* node)
     }
 }
 
-
-
-// FGNasalModelData class.  If sgLoad3DModel() is called with a pointer to
-// such a class, then it lets modelLoaded() run the <load> script, and the
-// destructor the <unload> script. The latter happens when the model branch
-// is removed from the scene graph.
-
-unsigned int FGNasalModelData::_module_id = 0;
-
-void FGNasalModelData::load()
-{
-    std::stringstream m;
-    m << "__model" << _module_id++;
-    _module = m.str();
-
-    SG_LOG(SG_NASAL, SG_DEBUG, "Loading nasal module " << _module.c_str());
-
-    const char *s = _load ? _load->getStringValue() : "";
-
-    naRef arg[2];
-    arg[0] = nasalSys->propNodeGhost(_root);
-    arg[1] = nasalSys->propNodeGhost(_prop);
-    nasalSys->createModule(_module.c_str(), _path.c_str(), s, strlen(s),
-                           _root, 2, arg);
-}
-
-void FGNasalModelData::unload()
-{
-    if (_module.empty())
-        return;
-
-    if(!nasalSys) {
-        SG_LOG(SG_NASAL, SG_WARN, "Trying to run an <unload> script "
-                "without Nasal subsystem present.");
-        return;
-    }
-
-    SG_LOG(SG_NASAL, SG_DEBUG, "Unloading nasal module " << _module.c_str());
-
-    if (_unload)
-    {
-        const char *s = _unload->getStringValue();
-        nasalSys->createModule(_module.c_str(), _module.c_str(), s, strlen(s), _root);
-    }
-
-    nasalSys->deleteModule(_module.c_str());
-}
-
-void FGNasalModelDataProxy::modelLoaded(const string& path, SGPropertyNode *prop,
-                                   osg::Node *)
-{
-    if(!nasalSys) {
-        SG_LOG(SG_NASAL, SG_WARN, "Trying to run a <load> script "
-                "without Nasal subsystem present.");
-        return;
-    }
-
-    if(!prop)
-        return;
-
-    SGPropertyNode *nasal = prop->getNode("nasal");
-    if(!nasal)
-        return;
-
-    SGPropertyNode* load   = nasal->getNode("load");
-    SGPropertyNode* unload = nasal->getNode("unload");
-
-    if ((!load) && (!unload))
-        return;
-
-    _data = new FGNasalModelData(_root, path, prop, load, unload);
-
-    // register Nasal module to be created and loaded in the main thread.
-    nasalSys->registerToLoad(_data);
-}
-
-FGNasalModelDataProxy::~FGNasalModelDataProxy()
-{
-    // when necessary, register Nasal module to be destroyed/unloaded
-    // in the main thread.
-    if ((_data.valid())&&(nasalSys))
-        nasalSys->registerToUnload(_data);
-}
-
 // NasalXMLVisitor class: handles EasyXML visitor callback for parsexml()
 //
 NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) :