2 /// Expose C++ objects to Nasal as ghosts
4 // Copyright (C) 2012 Thomas Geymayer <tomgey@gmail.com>
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.
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.
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
20 #ifndef SG_NASAL_GHOST_HXX_
21 #define SG_NASAL_GHOST_HXX_
23 #include "from_nasal.hxx"
24 #include "to_nasal.hxx"
26 #include <simgear/debug/logstream.hxx>
28 #include <boost/bind.hpp>
29 #include <boost/function.hpp>
30 #include <boost/lambda/lambda.hpp>
31 #include <boost/utility/enable_if.hpp>
36 * Bindings between C++ and the Nasal scripting language
42 * Traits for C++ classes exposed as Ghost. This is the basic template for
46 struct GhostTypeTraits
48 /** Whether the class is passed by shared pointer or raw pointer */
49 typedef boost::false_type::type is_shared;
51 /** The raw class type (Without any shared pointer) */
56 struct GhostTypeTraits<boost::shared_ptr<T> >
58 typedef boost::true_type::type is_shared;
64 struct GhostTypeTraits<osg::ref_ptr<T> >
66 typedef boost::true_type::type is_shared;
71 #ifdef SGSharedPtr_HXX
73 struct GhostTypeTraits<SGSharedPtr<T> >
75 typedef boost::true_type::type is_shared;
81 * Policy for creating ghost instances from shared pointer objects.
84 struct SharedPointerPolicy
86 typedef typename GhostTypeTraits<T>::raw_type raw_type;
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.
92 static T* createInstance(const T& ptr)
97 static raw_type* getRawPtr(void* ptr)
99 return static_cast<T*>(ptr)->get();
104 * Policy for creating ghost instances as raw objects on the heap.
107 struct RawPointerPolicy
109 typedef typename GhostTypeTraits<T>::raw_type raw_type;
112 * Create a new object instance on the heap
114 static T* createInstance()
119 static raw_type* getRawPtr(void* ptr)
121 BOOST_STATIC_ASSERT((boost::is_same<raw_type, T>::value));
122 return static_cast<T*>(ptr);
129 * Metadata for Ghost object types
135 * Add a nasal base class to the ghost. Will be available in the ghosts
138 void addNasalBase(const naRef& parent)
140 assert( naIsHash(parent) );
141 _parents.push_back(parent);
145 const std::string _name;
146 naGhostType _ghost_type;
147 // std::vector<GhostMetadata*> _base_classes;
148 std::vector<naRef> _parents;
150 explicit GhostMetadata(const std::string& name):
156 // void addBaseClass(GhostMetadata* base)
159 // _base_classes.push_back(base);
162 naRef getParents(naContext c)
164 return nasal::to_nasal(c, _parents);
170 * Class for exposing C++ objects to Nasal
173 * // Example class to be exposed to Nasal
180 * naRef myMember(int argc, naRef* args);
183 * void exposeClasses()
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");
202 public internal::GhostMetadata,
203 protected boost::mpl::if_< typename GhostTypeTraits<T>::is_shared,
204 SharedPointerPolicy<T>,
205 RawPointerPolicy<T> >::type
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;
214 * A ghost member. Can consist either of getter and/or setter functions
215 * for exposing a data variable or a single callable function.
223 member_t( const getter_t& getter,
224 const setter_t& setter,
225 naCFunction func = 0 ):
231 member_t(naCFunction func):
240 typedef std::map<std::string, member_t> MemberMap;
243 * Register a new ghost type.
245 * @param name Descriptive name of the ghost type.
247 static Ghost& init(const std::string& name)
249 getSingletonHolder().reset( new Ghost(name) );
250 return *getSingletonPtr();
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.
257 * @tparam BaseGhost Type of base class already wrapped into Ghost class
261 * Ghost<MyBase>::init("MyBase");
262 * Ghost<MyClass>::init("MyClass")
263 * .bases<Ghost<MyBase> >();
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,
274 BaseGhost* base = BaseGhost::getSingletonPtr();
275 //addBaseClass( base );
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();
284 if( _members.find(member->first) == _members.end() )
285 _members[member->first] = member_t
287 member->second.getter,
288 member->second.setter,
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.
300 * @tparam Base Type of base class (Base as used in Ghost<Base>)
303 * Ghost<MyBase>::init("MyBase");
304 * Ghost<MyClass>::init("MyClass")
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,
316 return bases< Ghost<Base> >();
320 * Register an existing Nasal class/hash as base class for this ghost.
322 * @param parent Nasal hash/class
324 Ghost& bases(const naRef& parent)
326 addNasalBase(parent);
331 * Register a member variable by passing a getter and/or setter method.
333 * @param field Name of member
334 * @param getter Getter for variable
335 * @param setter Setter for variable (Pass 0 to prevent write access)
339 Ghost& member( const std::string& field,
340 Var (raw_type::*getter)() const,
341 void (raw_type::*setter)(Var) = 0 )
346 naRef (*to_nasal_)(naContext, Var) = &nasal::to_nasal;
348 // Getter signature: naRef(naContext, raw_type*)
349 m.getter = boost::bind(to_nasal_, _1, boost::bind(getter, _2));
354 Var (*from_nasal_)(naContext, naRef) = &nasal::from_nasal;
356 // Setter signature: void(naContext, raw_type*, naRef)
357 m.setter = boost::bind(setter, _2, boost::bind(from_nasal_, _1, _3));
360 return member(field, m.getter, m.setter);
364 * Register a write only member variable.
366 * @param field Name of member
367 * @param setter Setter for variable
370 Ghost& member( const std::string& field,
371 void (raw_type::*setter)(Var) )
373 return member<Var>(field, 0, setter);
377 * Register a member variable by passing a getter and/or setter method.
379 * @param field Name of member
380 * @param getter Getter for variable
381 * @param setter Setter for variable (Pass empty to prevent write access)
384 Ghost& member( const std::string& field,
385 const getter_t& getter,
386 const setter_t& setter = setter_t() )
388 if( !getter.empty() || !setter.empty() )
389 _members[field] = member_t(getter, setter);
395 "Member '" << field << "' requires a getter or setter"
401 * Register a member function.
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
410 * @tparam func Pointer to member function being registered.
416 * naRef myMethod(int argc, naRef* args);
419 * Ghost<MyClass>::init("Test")
420 * .method<&MyClass::myMethod>("myMethod");
423 template<member_func_t func>
424 Ghost& method(const std::string& name)
426 _members[name].func = &MemberFunctionWrapper<func>::call;
430 // TODO use variadic template when supporting C++11
432 * Create a Nasal instance of this ghost.
434 * @param c Active Nasal context
436 static naRef create( naContext c )
438 return makeGhost(c, Ghost::createInstance());
442 * Create a Nasal instance of this ghost.
444 * @param c Active Nasal context
445 * @param a1 Parameter used for creating new instance
448 static naRef create( naContext c, const A1& a1 )
450 return makeGhost(c, Ghost::createInstance(a1));
454 * Nasal callback for creating a new instance of this ghost.
456 static naRef f_create(naContext c, naRef me, int argc, naRef* args)
466 static Ghost* getSingletonPtr()
468 return getSingletonHolder().get();
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.
477 template<member_func_t func>
478 struct MemberFunctionWrapper
481 * Called from Nasal upon invocation of the according registered
482 * function. Forwards the call to the passed object instance.
484 static naRef call(naContext c, naRef me, int argc, naRef* args)
486 if( naGhost_type(me) != &getSingletonPtr()->_ghost_type )
490 "method called on object of wrong type: '%s' expected",
491 getSingletonPtr()->_ghost_type.name
494 raw_type* obj = Ghost::getRawPtr( static_cast<T*>(naGhost_ptr(me)) );
497 return (obj->*func)(argc, args);
501 typedef std::auto_ptr<Ghost> GhostPtr;
504 explicit Ghost(const std::string& name):
505 GhostMetadata( name )
507 _ghost_type.destroy = &destroyGhost;
508 _ghost_type.name = _name.c_str();
509 _ghost_type.get_member = &getMember;
510 _ghost_type.set_member = &setMember;
513 static GhostPtr& getSingletonHolder()
515 static GhostPtr instance;
519 static naRef makeGhost(naContext c, void *ptr)
521 return naNewGhost2(c, &getSingletonPtr()->_ghost_type, ptr);
524 static void destroyGhost(void *ptr)
530 * Callback for retrieving a ghost member.
532 static const char* getMember(naContext c, void* g, naRef key, naRef* out)
534 const std::string key_str = nasal::from_nasal<std::string>(c, key);
535 if( key_str == "parents" )
537 if( getSingletonPtr()->_parents.empty() )
540 *out = getSingletonPtr()->getParents(c);
544 typename MemberMap::iterator member =
545 getSingletonPtr()->_members.find(key_str);
547 if( member == getSingletonPtr()->_members.end() )
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));
555 return "Read-protected member";
561 * Callback for writing to a ghost member.
563 static void setMember(naContext c, void* g, naRef field, naRef val)
565 const std::string key = nasal::from_nasal<std::string>(c, field);
566 typename MemberMap::iterator member =
567 getSingletonPtr()->_members.find(key);
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());
574 member->second.setter(c, Ghost::getRawPtr(g), val);
580 #endif /* SG_NASAL_GHOST_HXX_ */