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