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