# 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"
#include "NasalCondition.hxx"
+#include "NasalString.hxx"
#include <Main/globals.hxx>
#include <Main/util.hxx>
#include <Main/fg_props.hxx>
-
using std::map;
+void postinitNasalGUI(naRef globals, naContext c);
+
static FGNasalSys* nasalSys = 0;
// Listener class for loading Nasal modules on demand
}
}
+//////////////////////////////////////////////////////////////////////////
+
+
+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
nasalSys = this;
_context = 0;
_globals = naNil();
+ _string = naNil();
_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
naFreeContext(_context);
_globals = naNil();
+ _string = naNil();
}
bool FGNasalSys::parseAndRun(const char* sourceCode)
return true;
}
+#if 0
FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name)
{
FGNasalScript* script = new FGNasalScript();
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.
return naNum(buf.length());
}
+// logprint() extension function. Same as above, all arguments after the
+// first argument are concatenated. Argument 0 is the log-level, matching
+// sgDebugPriority.
+static naRef f_logprint(naContext c, naRef me, int argc, naRef* args)
+{
+ if (argc < 1)
+ naRuntimeError(c, "no prioirty argument to logprint()");
+
+ naRef priority = args[0];
+ string buf;
+ int n = argc;
+ for(int i=1; i<n; i++) {
+ naRef s = naStringValue(c, args[i]);
+ if(naIsNil(s)) continue;
+ buf += naStr_data(s);
+ }
+// 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());
+}
+
+
// fgcommand() extension function. Executes a named command via the
// FlightGear command manager. Takes a single property node name as
// an argument.
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)
// 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;
- }
+ 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();
- ((SGInterpolator*)globals->get_subsystem_mgr()
- ->get_group(SGSubsystemMgr::INIT)->get_subsystem("interpolator"))
- ->interpolate(node, nPoints, values, deltas);
+ naRef curve = argc > 1 ? args[1] : naNil();
+ if(!naIsVector(curve)) return naNil();
+ int nPoints = naVec_size(curve) / 2;
- delete[] values;
- delete[] deltas;
- return naNil();
+ 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);
+ }
+
+ node->interpolate("numeric", value_nodes, deltas, "linear");
+ return naNil();
}
// This is a better RNG than the one in the default Nasal distribution
return naStr_fromdata(naNewString(c), const_cast<char*>(pdata), strlen(pdata));
}
+static naRef f_findDataDir(naContext c, naRef me, int argc, naRef* args)
+{
+ if(argc != 1 || !naIsString(args[0]))
+ naRuntimeError(c, "bad arguments to findDataDir()");
+
+ SGPath p = globals->find_data_dir(naStr_data(args[0]));
+ const char* pdata = p.c_str();
+ 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>]]]]);
//
{ "getprop", f_getprop },
{ "setprop", f_setprop },
{ "print", f_print },
+ { "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 },
{ "abort", f_abort },
{ "directory", f_directory },
{ "resolvepath", f_resolveDataPath },
+ { "finddata", f_findDataDir },
{ "parsexml", f_parsexml },
{ "systime", f_systime },
{ 0, 0 }
return propNodeGhost(_cmdArg);
}
+void FGNasalSys::setCmdArg(SGPropertyNode* aNode)
+{
+ _cmdArg = aNode;
+}
+
void FGNasalSys::init()
{
int i;
hashset(_globals, funcs[i].name,
naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
-
-
// And our SGPropertyNode wrapper
hashset(_globals, "props", genPropsModule());
_gcHash = naNewHash(_context);
hashset(_globals, "__gcsave", _gcHash);
+ // Add string methods
+ _string = naInit_string(_context);
+ naSave(_context, _string);
+ 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);
- // NasalCanvas needs to be initialized after the props module from props.nas
- // (located in $FG_ROOT/Nasal/) has been loaded but before loading the
- // canvas module or any script creating a canvas.
- initNasalCanvas(_globals, _context, _gcHash);
-
// Add modules in Nasal subdirectories to property tree
simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+
simgear::Dir::NO_DOT_OR_DOTDOT, "");
// now Nasal modules are loaded, we can do some delayed work
postinitNasalPositioned(_globals, _context);
+ 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 (!_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())
// Create module with list of scripts
void FGNasalSys::addModule(string moduleName, simgear::PathList scripts)
{
- if (scripts.size()>0)
+ if (! scripts.empty())
{
SGPropertyNode* nasal = globals->get_props()->getNode("nasal");
SGPropertyNode* module_node = nasal->getChild(moduleName,0,true);
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,
void FGNasalListener::call(SGPropertyNode* which, naRef mode)
{
if(_active || _dead) return;
- SG_LOG(SG_NASAL, SG_DEBUG, "trigger listener #" << _id);
_active++;
naRef arg[4];
arg[0] = _nas->propNodeGhost(which);
}
}
-
-
-// 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) :