]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/cppbind/Ghost.hxx
Missing include and more doxygen improvements
[simgear.git] / simgear / nasal / cppbind / Ghost.hxx
1 ///@file
2 /// Expose C++ objects to Nasal as ghosts
3 ///
4 // Copyright (C) 2012  Thomas Geymayer <tomgey@gmail.com>
5 //
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Library General Public
8 // License as published by the Free Software Foundation; either
9 // version 2 of the License, or (at your option) any later version.
10 //
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 // Library General Public License for more details.
15 //
16 // You should have received a copy of the GNU Library General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA
19
20 #ifndef SG_NASAL_GHOST_HXX_
21 #define SG_NASAL_GHOST_HXX_
22
23 #include "from_nasal.hxx"
24 #include "to_nasal.hxx"
25
26 #include <simgear/debug/logstream.hxx>
27
28 #include <boost/bind.hpp>
29 #include <boost/function.hpp>
30 #include <boost/lambda/lambda.hpp>
31 #include <boost/utility/enable_if.hpp>
32
33 #include <map>
34
35 /**
36  * Bindings between C++ and the Nasal scripting language
37  */
38 namespace nasal
39 {
40
41   /**
42    * Traits for C++ classes exposed as Ghost. This is the basic template for
43    * raw types.
44    */
45   template<class T>
46   struct GhostTypeTraits
47   {
48     /** Whether the class is passed by shared pointer or raw pointer */
49     typedef boost::false_type::type is_shared;
50
51     /** The raw class type (Without any shared pointer) */
52     typedef T raw_type;
53   };
54
55   template<class T>
56   struct GhostTypeTraits<boost::shared_ptr<T> >
57   {
58     typedef boost::true_type::type is_shared;
59     typedef T raw_type;
60   };
61
62 #ifdef OSG_REF_PTR
63   template<class T>
64   struct GhostTypeTraits<osg::ref_ptr<T> >
65   {
66     typedef boost::true_type::type is_shared;
67     typedef T raw_type;
68   };
69 #endif
70
71 #ifdef SGSharedPtr_HXX
72   template<class T>
73   struct GhostTypeTraits<SGSharedPtr<T> >
74   {
75     typedef boost::true_type::type is_shared;
76     typedef T raw_type;
77   };
78 #endif
79
80   /**
81    * Policy for creating ghost instances from shared pointer objects.
82    */
83   template<class T>
84   struct SharedPointerPolicy
85   {
86     typedef typename GhostTypeTraits<T>::raw_type raw_type;
87
88     /**
89      * Create a shared pointer on the heap to handle the reference counting for
90      * the passed shared pointer while it is used in Nasal space.
91      */
92     static T* createInstance(const T& ptr)
93     {
94       return new T(ptr);
95     }
96
97     static raw_type* getRawPtr(void* ptr)
98     {
99       return static_cast<T*>(ptr)->get();
100     }
101   };
102
103   /**
104    * Policy for creating ghost instances as raw objects on the heap.
105    */
106   template<class T>
107   struct RawPointerPolicy
108   {
109     typedef typename GhostTypeTraits<T>::raw_type raw_type;
110
111     /**
112      * Create a new object instance on the heap
113      */
114     static T* createInstance()
115     {
116       return new T();
117     }
118
119     static raw_type* getRawPtr(void* ptr)
120     {
121       BOOST_STATIC_ASSERT((boost::is_same<raw_type, T>::value));
122       return static_cast<T*>(ptr);
123     }
124   };
125
126   namespace internal
127   {
128     /**
129      * Metadata for Ghost object types
130      */
131     class GhostMetadata
132     {
133       public:
134         /**
135          * Add a nasal base class to the ghost. Will be available in the ghosts
136          * parents array.
137          */
138         void addNasalBase(const naRef& parent)
139         {
140           assert( naIsHash(parent) );
141           _parents.push_back(parent);
142         }
143
144       protected:
145         const std::string             _name;
146         naGhostType                   _ghost_type;
147   //      std::vector<GhostMetadata*>   _base_classes;
148         std::vector<naRef>            _parents;
149
150         explicit GhostMetadata(const std::string& name):
151           _name(name)
152         {
153
154         }
155
156   //      void addBaseClass(GhostMetadata* base)
157   //      {
158   //        assert(base);
159   //        _base_classes.push_back(base);
160   //      }
161
162         naRef getParents(naContext c)
163         {
164           return nasal::to_nasal(c, _parents);
165         }
166     };
167   }
168
169   /**
170    * Class for exposing C++ objects to Nasal
171    *
172    * @code{cpp}
173    * // Example class to be exposed to Nasal
174    * class MyClass
175    * {
176    *   public:
177    *     void setX(int x);
178    *     int getX() const;
179    *
180    *     naRef myMember(int argc, naRef* args);
181    * }
182    *
183    * void exposeClasses()
184    * {
185    *   // Register a nasal ghost type for MyClass. This needs to be done only
186    *   // once before creating the first ghost instance.
187    *   Ghost<MyClass>::init("MyClass")
188    *     // Members can be exposed by getters and setters
189    *     .member("x", &MyClass::getX, &MyClass::setX)
190    *     // For readonly variables only pass a getter
191    *     .member("x_readonly", &MyClass::getX)
192    *     // It is also possible to expose writeonly members
193    *     .member("x_writeonly", &MyClass::setX)
194    *     // Methods use a slightly different syntax - The pointer to the member
195    *     // function has to be passed as template argument
196    *     .method<&MyClass::myMember>("myMember");
197    * }
198    * @endcode
199    */
200   template<class T>
201   class Ghost:
202     public internal::GhostMetadata,
203     protected boost::mpl::if_< typename GhostTypeTraits<T>::is_shared,
204                                SharedPointerPolicy<T>,
205                                RawPointerPolicy<T> >::type
206   {
207     public:
208       typedef typename GhostTypeTraits<T>::raw_type                 raw_type;
209       typedef naRef (T::*member_func_t)(int, naRef*);
210       typedef boost::function<naRef(naContext c, raw_type*)>        getter_t;
211       typedef boost::function<void(naContext c, raw_type*, naRef)>  setter_t;
212
213       /**
214        * A ghost member. Can consist either of getter and/or setter functions
215        * for exposing a data variable or a single callable function.
216        */
217       struct member_t
218       {
219         member_t():
220           func(0)
221         {}
222
223         member_t( const getter_t& getter,
224                   const setter_t& setter,
225                   naCFunction func = 0 ):
226           getter( getter ),
227           setter( setter ),
228           func( func )
229         {}
230
231         member_t(naCFunction func):
232           func( func )
233         {}
234
235         getter_t    getter;
236         setter_t    setter;
237         naCFunction func;
238       };
239
240       typedef std::map<std::string, member_t> MemberMap;
241
242       /**
243        * Register a new ghost type.
244        *
245        * @param name    Descriptive name of the ghost type.
246        */
247       static Ghost& init(const std::string& name)
248       {
249         getSingletonHolder().reset( new Ghost(name) );
250         return *getSingletonPtr();
251       }
252
253       /**
254        * Register a base class for this ghost. The base class needs to be
255        * registers on its own before it can be used as base class.
256        *
257        * @tparam BaseGhost  Type of base class already wrapped into Ghost class
258        *                    (Ghost<Base>)
259        *
260        * @code{cpp}
261        * Ghost<MyBase>::init("MyBase");
262        * Ghost<MyClass>::init("MyClass")
263        *   .bases<Ghost<MyBase> >();
264        * @endcode
265        */
266       template<class BaseGhost>
267       typename boost::enable_if_c
268         <    boost::is_base_of<GhostMetadata, BaseGhost>::value
269           && boost::is_base_of<typename BaseGhost::raw_type, raw_type>::value,
270           Ghost
271         >::type&
272       bases()
273       {
274         BaseGhost* base = BaseGhost::getSingletonPtr();
275         //addBaseClass( base );
276
277         // Replace any getter that is not available in the current class.
278         // TODO check if this is the correct behavior of function overriding
279         for( typename BaseGhost::MemberMap::const_iterator member =
280                base->_members.begin();
281                member != base->_members.end();
282              ++member )
283         {
284           if( _members.find(member->first) == _members.end() )
285             _members[member->first] = member_t
286             (
287               member->second.getter,
288               member->second.setter,
289               member->second.func
290             );
291         }
292
293         return *this;
294       }
295
296       /**
297        * Register a base class for this ghost. The base class needs to be
298        * registers on its own before it can be used as base class.
299        *
300        * @tparam Base   Type of base class (Base as used in Ghost<Base>)
301        *
302        * @code{cpp}
303        * Ghost<MyBase>::init("MyBase");
304        * Ghost<MyClass>::init("MyClass")
305        *   .bases<MyBase>();
306        * @endcode
307        */
308       template<class Base>
309       typename boost::enable_if_c
310         <   !boost::is_base_of<GhostMetadata, Base>::value
311           && boost::is_base_of<typename Ghost<Base>::raw_type, raw_type>::value,
312           Ghost
313         >::type&
314       bases()
315       {
316         return bases< Ghost<Base> >();
317       }
318
319       /**
320        * Register an existing Nasal class/hash as base class for this ghost.
321        *
322        * @param parent  Nasal hash/class
323        */
324       Ghost& bases(const naRef& parent)
325       {
326         addNasalBase(parent);
327         return *this;
328       }
329
330       /**
331        * Register a member variable by passing a getter and/or setter method.
332        *
333        * @param field   Name of member
334        * @param getter  Getter for variable
335        * @param setter  Setter for variable (Pass 0 to prevent write access)
336        *
337        */
338       template<class Var>
339       Ghost& member( const std::string& field,
340                      Var (raw_type::*getter)() const,
341                      void (raw_type::*setter)(Var) = 0 )
342       {
343         member_t m;
344         if( getter )
345         {
346           naRef (*to_nasal_)(naContext, Var) = &nasal::to_nasal;
347
348           // Getter signature: naRef(naContext, raw_type*)
349           m.getter = boost::bind(to_nasal_, _1, boost::bind(getter, _2));
350         }
351
352         if( setter )
353         {
354           Var (*from_nasal_)(naContext, naRef) = &nasal::from_nasal;
355
356           // Setter signature: void(naContext, raw_type*, naRef)
357           m.setter = boost::bind(setter, _2, boost::bind(from_nasal_, _1, _3));
358         }
359
360         return member(field, m.getter, m.setter);
361       }
362
363       /**
364        * Register a write only member variable.
365        *
366        * @param field   Name of member
367        * @param setter  Setter for variable
368        */
369       template<class Var>
370       Ghost& member( const std::string& field,
371                      void (raw_type::*setter)(Var) )
372       {
373         return member<Var>(field, 0, setter);
374       }
375
376       /**
377        * Register a member variable by passing a getter and/or setter method.
378        *
379        * @param field   Name of member
380        * @param getter  Getter for variable
381        * @param setter  Setter for variable (Pass empty to prevent write access)
382        *
383        */
384       Ghost& member( const std::string& field,
385                      const getter_t& getter,
386                      const setter_t& setter = setter_t() )
387       {
388         if( !getter.empty() || !setter.empty() )
389           _members[field] = member_t(getter, setter);
390         else
391           SG_LOG
392           (
393             SG_NASAL,
394             SG_WARN,
395             "Member '" << field << "' requires a getter or setter"
396           );
397         return *this;
398       }
399
400       /**
401        * Register a member function.
402        *
403        * @note Because only function pointers can be registered as Nasal
404        *       functions it is needed to pass the function pointer as template
405        *       argument. This allows us to create a separate instance of the
406        *       MemberFunctionWrapper for each registered function and therefore
407        *       provides us with the needed static functions to be passed on to
408        *       Nasal.
409        *
410        * @tparam func   Pointer to member function being registered.
411        *
412        * @code{cpp}
413        * class MyClass
414        * {
415        *   public:
416        *     naRef myMethod(int argc, naRef* args);
417        * }
418        *
419        * Ghost<MyClass>::init("Test")
420        *   .method<&MyClass::myMethod>("myMethod");
421        * @endcode
422        */
423       template<member_func_t func>
424       Ghost& method(const std::string& name)
425       {
426         _members[name].func = &MemberFunctionWrapper<func>::call;
427         return *this;
428       }
429
430       // TODO use variadic template when supporting C++11
431       /**
432        * Create a Nasal instance of this ghost.
433        *
434        * @param c   Active Nasal context
435        */
436       static naRef create( naContext c )
437       {
438         return makeGhost(c, Ghost::createInstance());
439       }
440
441       /**
442        * Create a Nasal instance of this ghost.
443        *
444        * @param c   Active Nasal context
445        * @param a1  Parameter used for creating new instance
446        */
447       template<class A1>
448       static naRef create( naContext c, const A1& a1 )
449       {
450         return makeGhost(c, Ghost::createInstance(a1));
451       }
452
453       /**
454        * Nasal callback for creating a new instance of this ghost.
455        */
456       static naRef f_create(naContext c, naRef me, int argc, naRef* args)
457       {
458         return create(c);
459       }
460
461     private:
462
463       template<class>
464       friend class Ghost;
465
466       static Ghost* getSingletonPtr()
467       {
468         return getSingletonHolder().get();
469       }
470
471       /**
472        * Wrapper class to enable registering pointers to member functions as
473        * Nasal function callbacks. We need to use the function pointer as
474        * template parameter to ensure every registered function gets a static
475        * function which can be passed to Nasal.
476        */
477       template<member_func_t func>
478       struct MemberFunctionWrapper
479       {
480         /**
481          * Called from Nasal upon invocation of the according registered
482          * function. Forwards the call to the passed object instance.
483          */
484         static naRef call(naContext c, naRef me, int argc, naRef* args)
485         {
486           if( naGhost_type(me) != &getSingletonPtr()->_ghost_type )
487             naRuntimeError
488             (
489               c,
490               "method called on object of wrong type: '%s' expected",
491               getSingletonPtr()->_ghost_type.name
492             );
493
494           raw_type* obj = Ghost::getRawPtr( static_cast<T*>(naGhost_ptr(me)) );
495           assert(obj);
496
497           return (obj->*func)(argc, args);
498         }
499       };
500
501       typedef std::auto_ptr<Ghost> GhostPtr;
502       MemberMap _members;
503
504       explicit Ghost(const std::string& name):
505         GhostMetadata( name )
506       {
507         _ghost_type.destroy = &destroyGhost;
508         _ghost_type.name = _name.c_str();
509         _ghost_type.get_member = &getMember;
510         _ghost_type.set_member = &setMember;
511       }
512
513       static GhostPtr& getSingletonHolder()
514       {
515         static GhostPtr instance;
516         return instance;
517       }
518
519       static naRef makeGhost(naContext c, void *ptr)
520       {
521         return naNewGhost2(c, &getSingletonPtr()->_ghost_type, ptr);
522       }
523
524       static void destroyGhost(void *ptr)
525       {
526         delete (T*)ptr;
527       }
528
529       /**
530        * Callback for retrieving a ghost member.
531        */
532       static const char* getMember(naContext c, void* g, naRef key, naRef* out)
533       {
534         const std::string key_str = nasal::from_nasal<std::string>(c, key);
535         if( key_str == "parents" )
536         {
537           if( getSingletonPtr()->_parents.empty() )
538             return 0;
539
540           *out = getSingletonPtr()->getParents(c);
541           return "";
542         }
543
544         typename MemberMap::iterator member =
545           getSingletonPtr()->_members.find(key_str);
546
547         if( member == getSingletonPtr()->_members.end() )
548           return 0;
549
550         if( member->second.func )
551           *out = nasal::to_nasal(c, member->second.func);
552         else if( !member->second.getter.empty() )
553           *out = member->second.getter(c, Ghost::getRawPtr(g));
554         else
555           return "Read-protected member";
556
557         return "";
558       }
559
560       /**
561        * Callback for writing to a ghost member.
562        */
563       static void setMember(naContext c, void* g, naRef field, naRef val)
564       {
565         const std::string key = nasal::from_nasal<std::string>(c, field);
566         typename MemberMap::iterator member =
567           getSingletonPtr()->_members.find(key);
568
569         if( member == getSingletonPtr()->_members.end() )
570           naRuntimeError(c, "ghost: No such member: %s", key.c_str());
571         if( member->second.setter.empty() )
572           naRuntimeError(c, "ghost: Write protected member: %s", key.c_str());
573
574         member->second.setter(c, Ghost::getRawPtr(g), val);
575       }
576   };
577
578 } // namespace nasal
579
580 #endif /* SG_NASAL_GHOST_HXX_ */