]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.hxx
7fa3fb7ae220138fe9241d62bedf3ff836afb819
[flightgear.git] / src / Scripting / NasalSys.hxx
1 #ifndef __NASALSYS_HXX
2 #define __NASALSYS_HXX
3
4 #include <simgear/misc/sg_path.hxx>
5 #include <simgear/structure/subsystem_mgr.hxx>
6 #include <simgear/misc/sg_dir.hxx>
7 #include <simgear/nasal/nasal.h>
8 #include <simgear/scene/model/modellib.hxx>
9 #include <simgear/xml/easyxml.hxx>
10 #include <simgear/threads/SGQueue.hxx>
11
12 #include <map>
13
14
15 class FGNasalScript;
16 class FGNasalListener;
17 class SGCondition;
18
19 namespace simgear { class BufferedLogCallback; }
20
21 /** Nasal model data container.
22  * load and unload methods must be run in main thread (not thread-safe). */
23 class FGNasalModelData : public SGReferenced
24 {
25 public:
26     /** Constructor to be run in an arbitrary thread. */
27     FGNasalModelData(SGPropertyNode *root, const string& path, SGPropertyNode *prop,
28                      SGPropertyNode* load, SGPropertyNode* unload) :
29         _path(path),
30         _root(root), _prop(prop),
31         _load(load), _unload(unload)
32      {
33      }
34
35     /** Load hook. Always call from inside the main loop. */
36     void load();
37
38     /** Unload hook. Always call from inside the main loop. */
39     void unload();
40
41 private:
42     static unsigned int _module_id;
43
44     string _module, _path;
45     SGPropertyNode_ptr _root, _prop;
46     SGConstPropertyNode_ptr _load, _unload;
47 };
48
49 /** Thread-safe proxy for FGNasalModelData.
50  * modelLoaded/destroy methods only register the requested
51  * operation. Actual (un)loading of Nasal module is deferred
52  * and done in the main loop. */
53 class FGNasalModelDataProxy : public simgear::SGModelData
54 {
55 public:
56     FGNasalModelDataProxy(SGPropertyNode *root = 0) :
57         _root(root), _data(0)
58     {
59     }
60
61     ~FGNasalModelDataProxy();
62
63     void modelLoaded(const string& path, SGPropertyNode *prop, osg::Node *);
64
65 protected:
66     SGPropertyNode_ptr _root;
67     SGSharedPtr<FGNasalModelData> _data;
68 };
69
70 SGPropertyNode* ghostToPropNode(naRef ref);
71 SGCondition* conditionGhost(naRef r);
72
73 class FGNasalSys : public SGSubsystem
74 {
75 public:
76     FGNasalSys();
77     virtual ~FGNasalSys();
78     virtual void init();
79     virtual void update(double dt);
80
81     // Loads a nasal script from an external file and inserts it as a
82     // global module of the specified name.
83     bool loadModule(SGPath file, const char* moduleName);
84
85     // Simple hook to run arbitrary source code.  Returns a bool to
86     // indicate successful execution.  Does *not* return any Nasal
87     // values, because handling garbage-collected objects from C space
88     // is deep voodoo and violates the "simple hook" idea.
89     bool parseAndRun(const char* sourceCode);
90
91     // Slightly more complicated hook to get a handle to a precompiled
92     // Nasal script that can be invoked via a call() method.  The
93     // caller is expected to delete the FGNasalScript returned from
94     // this function.  The "name" argument specifies the "file name"
95     // for the source code that will be printed in Nasal stack traces
96     // on error.
97     FGNasalScript* parseScript(const char* src, const char* name=0);
98
99     // Implementation of the settimer extension function
100     void setTimer(naContext c, int argc, naRef* args);
101
102     // Implementation of the setlistener extension function
103     naRef setListener(naContext c, int argc, naRef* args);
104     naRef removeListener(naContext c, int argc, naRef* args);
105
106     // Returns a ghost wrapper for the current _cmdArg
107     naRef cmdArgGhost();
108
109     // Callbacks for command and timer bindings
110     virtual bool handleCommand( const char* moduleName,
111                                 const char* fileName,
112                                 const char* src,
113                                 const SGPropertyNode* arg = 0 );
114     virtual bool handleCommand(const SGPropertyNode* arg);
115
116     bool createModule(const char* moduleName, const char* fileName,
117                       const char* src, int len, const SGPropertyNode* cmdarg=0,
118                       int argc=0, naRef*args=0);
119
120     void deleteModule(const char* moduleName);
121
122     /**
123      * Set member of specified hash to given value
124      */
125     void hashset(naRef hash, const char* key, naRef val);
126
127     /**
128      * Set member of globals hash to given value
129      */
130     void globalsSet(const char* key, naRef val);
131
132     naRef call(naRef code, int argc, naRef* args, naRef locals);
133   
134     naRef callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals);
135   
136     naRef propNodeGhost(SGPropertyNode* handle);
137   
138     void registerToLoad(FGNasalModelData* data)   { _loadList.push(data);}
139     void registerToUnload(FGNasalModelData* data) { _unloadList.push(data);}
140
141     // can't call this 'globals' due to naming clash
142     naRef nasalGlobals() const
143     { return _globals; }
144   
145     naContext context() const
146     { return _context; }
147   
148     // This mechanism is here to allow naRefs to be passed to
149     // locations "outside" the interpreter.  Normally, such a
150     // reference would be garbage collected unexpectedly.  By passing
151     // it to gcSave and getting a key/handle, it can be cached in a
152     // globals.__gcsave hash.  Be sure to release it with gcRelease
153     // when done.
154     int gcSave(naRef r);
155     void gcRelease(int key);
156     
157     /// retrive the associated log object, for displaying log
158     /// output somewhere (a UI, presumably)
159     simgear::BufferedLogCallback* log() const
160     { return _log; }
161 private:
162     friend class FGNasalScript;
163     friend class FGNasalListener;
164     friend class FGNasalModuleListener;
165
166     SGLockedQueue<SGSharedPtr<FGNasalModelData> > _loadList;
167     SGLockedQueue<SGSharedPtr<FGNasalModelData> > _unloadList;
168
169     //
170     // FGTimer subclass for handling Nasal timer callbacks.
171     // See the implementation of the settimer() extension function for
172     // more notes.
173     //
174     struct NasalTimer {
175         virtual void timerExpired();
176         virtual ~NasalTimer() {}
177         naRef handler;
178         int gcKey;
179         FGNasalSys* nasal;
180     };
181
182     // Listener
183     std::map<int, FGNasalListener *> _listener;
184     vector<FGNasalListener *> _dead_listener;
185     static int _listenerId;
186
187     void loadPropertyScripts();
188     void loadPropertyScripts(SGPropertyNode* n);
189     void loadScriptDirectory(simgear::Dir nasalDir);
190     void addModule(string moduleName, simgear::PathList scripts);
191     void logError(naContext);
192     naRef parse(const char* filename, const char* buf, int len);
193     naRef genPropsModule();
194
195     naContext _context;
196     naRef _globals,
197           _string;
198
199     SGPropertyNode_ptr _cmdArg;
200
201     int _nextGCKey;
202     naRef _gcHash;
203     int _callCount;
204
205     simgear::BufferedLogCallback* _log;
206 public:
207     void handleTimer(NasalTimer* t);
208 };
209
210
211 class FGNasalScript {
212 public:
213     ~FGNasalScript() { _nas->gcRelease(_gcKey); }
214
215     bool call() {
216         naRef n = naNil();
217         naCall(_nas->_context, _code, 0, &n, naNil(), naNil());
218         return naGetError(_nas->_context) == 0;
219     }
220
221 private:
222     friend class FGNasalSys;
223     naRef _code;
224     int _gcKey;
225     FGNasalSys* _nas;
226 };
227
228
229 class FGNasalListener : public SGPropertyChangeListener {
230 public:
231     FGNasalListener(SGPropertyNode* node, naRef code, FGNasalSys* nasal,
232                     int key, int id, int init, int type);
233
234     virtual ~FGNasalListener();
235     virtual void valueChanged(SGPropertyNode* node);
236     virtual void childAdded(SGPropertyNode* parent, SGPropertyNode* child);
237     virtual void childRemoved(SGPropertyNode* parent, SGPropertyNode* child);
238
239 private:
240     bool changed(SGPropertyNode* node);
241     void call(SGPropertyNode* which, naRef mode);
242
243     friend class FGNasalSys;
244     SGPropertyNode_ptr _node;
245     naRef _code;
246     int _gcKey;
247     int _id;
248     FGNasalSys* _nas;
249     int _init;
250     int _type;
251     unsigned int _active;
252     bool _dead;
253     long _last_int;
254     double _last_float;
255     string _last_string;
256 };
257
258
259 class NasalXMLVisitor : public XMLVisitor {
260 public:
261     NasalXMLVisitor(naContext c, int argc, naRef* args);
262     virtual ~NasalXMLVisitor() { naFreeContext(_c); }
263
264     virtual void startElement(const char* tag, const XMLAttributes& a);
265     virtual void endElement(const char* tag);
266     virtual void data(const char* str, int len);
267     virtual void pi(const char* target, const char* data);
268
269 private:
270     void call(naRef func, int num, naRef a = naNil(), naRef b = naNil());
271     naRef make_string(const char* s, int n = -1);
272
273     naContext _c;
274     naRef _start_element, _end_element, _data, _pi;
275 };
276
277 #endif // __NASALSYS_HXX