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;
88 typedef boost::false_type returns_dynamic_type;
91 * Create a shared pointer on the heap to handle the reference counting for
92 * the passed shared pointer while it is used in Nasal space.
94 static T* createInstance(const T& ptr)
99 static pointer getPtr(void* ptr)
102 return *static_cast<T*>(ptr);
107 static raw_type* getRawPtr(void* ptr)
110 return static_cast<T*>(ptr)->get();
115 static raw_type* getRawPtr(const T& ptr)
122 * Policy for creating ghost instances as raw objects on the heap.
125 struct RawPointerPolicy
127 typedef typename GhostTypeTraits<T>::raw_type raw_type;
128 typedef raw_type* pointer;
129 typedef boost::true_type returns_dynamic_type;
132 * Create a new object instance on the heap
134 static T* createInstance()
139 static pointer getPtr(void* ptr)
141 BOOST_STATIC_ASSERT((boost::is_same<pointer, T*>::value));
142 return static_cast<T*>(ptr);
145 static raw_type* getRawPtr(void* ptr)
147 BOOST_STATIC_ASSERT((boost::is_same<raw_type, T>::value));
148 return static_cast<T*>(ptr);
155 * Metadata for Ghost object types
161 * Add a nasal base class to the ghost. Will be available in the ghosts
164 void addNasalBase(const naRef& parent)
166 assert( naIsHash(parent) );
167 _parents.push_back(parent);
170 bool isBaseOf(naGhostType* ghost_type) const
172 if( ghost_type == &_ghost_type )
175 for( DerivedList::const_iterator derived = _derived_classes.begin();
176 derived != _derived_classes.end();
179 if( (*derived)->isBaseOf(ghost_type) )
188 typedef std::vector<const GhostMetadata*> DerivedList;
190 const std::string _name;
191 naGhostType _ghost_type;
192 DerivedList _derived_classes;
193 std::vector<naRef> _parents;
195 explicit GhostMetadata(const std::string& name):
201 void addDerived(const GhostMetadata* derived)
204 _derived_classes.push_back(derived);
210 "Ghost::addDerived: " <<_ghost_type.name << " -> " << derived->_name
214 naRef getParents(naContext c)
216 return nasal::to_nasal(c, _parents);
222 * Context passed to a function/method being called from Nasal
226 CallContext(naContext c, size_t argc, naRef* args):
233 T get(size_t index, const T& def = T()) const
238 return from_nasal<T>(c, args[index]);
242 T require(size_t index) const
245 naRuntimeError(c, "Missing required arg #%d", index);
247 return from_nasal<T>(c, args[index]);
256 * Class for exposing C++ objects to Nasal
259 * // Example class to be exposed to Nasal
266 * naRef myMember(naContext c, int argc, naRef* args);
269 * void exposeClasses()
271 * // Register a nasal ghost type for MyClass. This needs to be done only
272 * // once before creating the first ghost instance.
273 * Ghost<MyClass>::init("MyClass")
274 * // Members can be exposed by getters and setters
275 * .member("x", &MyClass::getX, &MyClass::setX)
276 * // For readonly variables only pass a getter
277 * .member("x_readonly", &MyClass::getX)
278 * // It is also possible to expose writeonly members
279 * .member("x_writeonly", &MyClass::setX)
280 * // Methods use a slightly different syntax - The pointer to the member
281 * // function has to be passed as template argument
282 * .method<&MyClass::myMember>("myMember");
288 public internal::GhostMetadata,
289 protected boost::mpl::if_< typename GhostTypeTraits<T>::is_shared,
290 SharedPointerPolicy<T>,
291 RawPointerPolicy<T> >::type
294 typedef T value_type;
295 typedef typename GhostTypeTraits<T>::raw_type raw_type;
296 typedef typename Ghost::pointer pointer;
297 typedef naRef (raw_type::*member_func_t)(const CallContext&);
298 typedef naRef (*free_func_t)(raw_type&, const CallContext&);
299 typedef boost::function<naRef(naContext, raw_type&)> getter_t;
300 typedef boost::function<void(naContext, raw_type&, naRef)> setter_t;
303 * A ghost member. Can consist either of getter and/or setter functions
304 * for exposing a data variable or a single callable function.
312 member_t( const getter_t& getter,
313 const setter_t& setter,
314 naCFunction func = 0 ):
320 member_t(naCFunction func):
329 typedef std::map<std::string, member_t> MemberMap;
332 * Register a new ghost type.
334 * @note Only intialize each ghost type once!
336 * @param name Descriptive name of the ghost type.
338 static Ghost& init(const std::string& name)
340 assert( !getSingletonPtr() );
342 getSingletonHolder().reset( new Ghost(name) );
343 return *getSingletonPtr();
347 * Register a base class for this ghost. The base class needs to be
348 * registers on its own before it can be used as base class.
350 * @tparam BaseGhost Type of base class already wrapped into Ghost class
354 * Ghost<MyBase>::init("MyBase");
355 * Ghost<MyClass>::init("MyClass")
356 * .bases<Ghost<MyBase> >();
359 template<class BaseGhost>
360 typename boost::enable_if_c
361 < boost::is_base_of<GhostMetadata, BaseGhost>::value
362 && boost::is_base_of<typename BaseGhost::raw_type, raw_type>::value,
367 BaseGhost* base = BaseGhost::getSingletonPtr();
371 // Both ways of retrieving the address of a static member function
372 // should be legal but not all compilers know this.
373 // g++-4.4.7+ has been tested to work with both versions
374 #if defined(GCC_VERSION) && GCC_VERSION < 40407
375 // The old version of g++ used on Jenkins (16.11.2012) only compiles
377 &getTypeFor<BaseGhost>
379 // VS (2008, 2010, ... ?) only allow this version.
380 &Ghost::getTypeFor<BaseGhost>
384 // Replace any getter that is not available in the current class.
385 // TODO check if this is the correct behavior of function overriding
386 for( typename BaseGhost::MemberMap::const_iterator member =
387 base->_members.begin();
388 member != base->_members.end();
391 if( _members.find(member->first) == _members.end() )
392 _members[member->first] = member_t
394 member->second.getter,
395 member->second.setter,
404 * Register a base class for this ghost. The base class needs to be
405 * registers on its own before it can be used as base class.
407 * @tparam Base Type of base class (Base as used in Ghost<Base>)
410 * Ghost<MyBase>::init("MyBase");
411 * Ghost<MyClass>::init("MyClass")
416 typename boost::enable_if_c
417 < !boost::is_base_of<GhostMetadata, Base>::value
418 && boost::is_base_of<typename Ghost<Base>::raw_type, raw_type>::value,
423 return bases< Ghost<Base> >();
427 * Register an existing Nasal class/hash as base class for this ghost.
429 * @param parent Nasal hash/class
431 Ghost& bases(const naRef& parent)
433 addNasalBase(parent);
438 * Register a member variable by passing a getter and/or setter method.
440 * @param field Name of member
441 * @param getter Getter for variable
442 * @param setter Setter for variable (Pass 0 to prevent write access)
446 Ghost& member( const std::string& field,
447 Var (raw_type::*getter)() const,
448 void (raw_type::*setter)(Var) = 0 )
453 naRef (*to_nasal_)(naContext, Var) = &nasal::to_nasal;
455 // Getter signature: naRef(naContext, raw_type&)
456 m.getter = boost::bind(to_nasal_, _1, boost::bind(getter, _2));
461 Var (*from_nasal_)(naContext, naRef) = &nasal::from_nasal;
463 // Setter signature: void(naContext, raw_type&, naRef)
464 m.setter = boost::bind(setter, _2, boost::bind(from_nasal_, _1, _3));
467 return member(field, m.getter, m.setter);
471 * Register a write only member variable.
473 * @param field Name of member
474 * @param setter Setter for variable
477 Ghost& member( const std::string& field,
478 void (raw_type::*setter)(Var) )
480 return member<Var>(field, 0, setter);
484 * Register a member variable by passing a getter and/or setter method.
486 * @param field Name of member
487 * @param getter Getter for variable
488 * @param setter Setter for variable (Pass empty to prevent write access)
491 Ghost& member( const std::string& field,
492 const getter_t& getter,
493 const setter_t& setter = setter_t() )
495 if( !getter.empty() || !setter.empty() )
496 _members[field] = member_t(getter, setter);
502 "Member '" << field << "' requires a getter or setter"
508 * Register a member function.
510 * @note Because only function pointers can be registered as Nasal
511 * functions it is needed to pass the function pointer as template
512 * argument. This allows us to create a separate instance of the
513 * MemberFunctionWrapper for each registered function and therefore
514 * provides us with the needed static functions to be passed on to
517 * @tparam func Pointer to member function being registered.
523 * naRef myMethod(naContext c, int argc, naRef* args);
526 * Ghost<MyClass>::init("Test")
527 * .method<&MyClass::myMethod>("myMethod");
530 template<member_func_t func>
531 Ghost& method(const std::string& name)
533 _members[name].func = &MemberFunctionWrapper<func>::call;
538 * Register a free function as member function. The object instance is
539 * passed as additional first argument.
541 * @tparam func Pointer to free function being registered.
543 * @note Due to a severe bug in Visual Studio it is not possible to create
544 * a specialization of #method for free function pointers and
545 * member function pointers at the same time. Do overcome this
546 * limitation we had to use a different name for this function.
550 * naRef myMethod(MyClass& obj, naContext c, int argc, naRef* args);
552 * Ghost<MyClass>::init("Test")
553 * .method_func<&myMethod>("myMethod");
556 template<free_func_t func>
557 Ghost& method_func(const std::string& name)
559 _members[name].func = &FreeFunctionWrapper<func>::call;
563 // TODO use variadic template when supporting C++11
565 * Create a Nasal instance of this ghost.
567 * @param c Active Nasal context
569 static naRef create( naContext c )
571 return makeGhost(c, Ghost::createInstance());
575 * Create a Nasal instance of this ghost.
577 * @param c Active Nasal context
578 * @param a1 Parameter used for creating new instance
581 static naRef create( naContext c, const A1& a1 )
583 return makeGhost(c, Ghost::createInstance(a1));
587 * Nasal callback for creating a new instance of this ghost.
589 static naRef f_create(naContext c, naRef me, int argc, naRef* args)
594 static bool isBaseOf(naGhostType* ghost_type)
599 return getSingletonPtr()->GhostMetadata::isBaseOf(ghost_type);
602 static bool isBaseOf(naRef obj)
604 return isBaseOf( naGhost_type(obj) );
608 * Convert Nasal object to C++ object. To get a valid object the passed
609 * Nasal objects has to be derived class of the target class (Either
610 * derived in C++ or in Nasal using a 'parents' vector)
612 static pointer fromNasal(naContext c, naRef me)
614 // Check if it's a ghost and if it can be converted
615 if( isBaseOf( naGhost_type(me) ) )
616 return Ghost::getPtr( naGhost_ptr(me) );
618 // Now if it is derived from a ghost (hash with ghost in parent vector)
619 // TODO handle recursive parents
620 else if( naIsHash(me) )
622 naRef na_parents = naHash_cget(me, const_cast<char*>("parents"));
623 if( !naIsVector(na_parents) )
625 SG_LOG(SG_NASAL, SG_DEBUG, "Missing 'parents' vector for ghost");
629 typedef std::vector<naRef> naRefs;
630 naRefs parents = from_nasal<naRefs>(c, na_parents);
631 for( naRefs::const_iterator parent = parents.begin();
632 parent != parents.end();
635 if( isBaseOf(naGhost_type(*parent)) )
636 return Ghost::getPtr( naGhost_ptr(*parent) );
648 typedef naGhostType* (*type_checker_t)(const raw_type*);
649 typedef std::vector<type_checker_t> DerivedList;
650 DerivedList _derived_types;
652 void addDerived( const internal::GhostMetadata* derived_meta,
653 const type_checker_t& derived_info )
655 GhostMetadata::addDerived(derived_meta);
656 _derived_types.push_back(derived_info);
659 template<class BaseGhost>
661 typename boost::enable_if
662 < boost::is_polymorphic<typename BaseGhost::raw_type>,
665 getTypeFor(const typename BaseGhost::raw_type* base)
667 // Check first if passed pointer can by converted to instance of class
670 < typename BaseGhost::raw_type,
671 typename Ghost::raw_type
673 && dynamic_cast<const typename Ghost::raw_type*>(base) != base )
676 // Now check if we can further downcast to one of our derived classes.
677 for( typename DerivedList::reverse_iterator
678 derived = getSingletonPtr()->_derived_types.rbegin();
679 derived != getSingletonPtr()->_derived_types.rend();
682 naGhostType* ghost_type =
683 (*derived)( static_cast<const typename Ghost::raw_type*>(base) );
688 // If base is not an instance of any derived class, this class has to
689 // be the dynamic type.
690 return &getSingletonPtr()->_ghost_type;
693 template<class BaseGhost>
695 typename boost::disable_if
696 < boost::is_polymorphic<typename BaseGhost::raw_type>,
699 getTypeFor(const typename BaseGhost::raw_type* base)
701 // For non polymorphic classes there is no possibility to get the actual
702 // dynamic type, therefore we can only use its static type.
703 return &BaseGhost::getSingletonPtr()->_ghost_type;
706 static Ghost* getSingletonPtr()
708 return getSingletonHolder().get();
711 static raw_type& requireObject(naContext c, naRef me)
713 raw_type* obj = Ghost::getRawPtr( fromNasal(c, me) );
714 naGhostType* ghost_type = naGhost_type(me);
720 "method called on object of wrong type: is '%s' expected '%s'",
721 ghost_type ? ghost_type->name : "unknown",
722 getSingletonPtr()->_ghost_type.name
729 * Wrapper class to enable registering pointers to member functions as
730 * Nasal function callbacks. We need to use the function pointer as
731 * template parameter to ensure every registered function gets a static
732 * function which can be passed to Nasal.
734 template<member_func_t func>
735 struct MemberFunctionWrapper
738 * Called from Nasal upon invocation of the according registered
739 * function. Forwards the call to the passed object instance.
741 static naRef call(naContext c, naRef me, int argc, naRef* args)
743 return (requireObject(c, me).*func)(CallContext(c, argc, args));
748 * Wrapper class to enable registering pointers to free functions (only
749 * external linkage). We need to use the function pointer as template
750 * parameter to ensure every registered function gets a static function
751 * which can be passed to Nasal. Even though we just wrap another simple
752 * function pointer this intermediate step is need to be able to retrieve
753 * the object the function call belongs to and pass it along as argument.
755 template<free_func_t func>
756 struct FreeFunctionWrapper
759 * Called from Nasal upon invocation of the according registered
760 * function. Forwards the call to the passed function pointer and passes
761 * the required parameters.
763 static naRef call(naContext c, naRef me, int argc, naRef* args)
765 return func(requireObject(c, me), CallContext(c, argc, args));
769 typedef std::auto_ptr<Ghost> GhostPtr;
772 explicit Ghost(const std::string& name):
773 GhostMetadata( name )
775 _ghost_type.destroy = &destroyGhost;
776 _ghost_type.name = _name.c_str();
777 _ghost_type.get_member = &getMember;
778 _ghost_type.set_member = &setMember;
781 static GhostPtr& getSingletonHolder()
783 static GhostPtr instance;
787 static naRef makeGhost(naContext c, void *ptr)
789 if( !Ghost::getRawPtr(ptr) )
792 naGhostType* ghost_type = 0;
793 if( Ghost::returns_dynamic_type::value )
794 // For pointer policies already returning instances of an object with
795 // the dynamic type of this Ghost's raw_type the type is always the
797 ghost_type = &getSingletonPtr()->_ghost_type;
799 // If wrapping eg. shared pointers the users passes an already
800 // existing instance of an object which will then be hold be a new
801 // shared pointer. We therefore have to check for the dynamic type
802 // of the object as it might differ from the passed static type.
803 ghost_type = getTypeFor<Ghost>( Ghost::getRawPtr(ptr) );
808 return naNewGhost2(c, ghost_type, ptr);
811 static void destroyGhost(void *ptr)
817 * Callback for retrieving a ghost member.
819 static const char* getMember(naContext c, void* g, naRef key, naRef* out)
821 const std::string key_str = nasal::from_nasal<std::string>(c, key);
822 if( key_str == "parents" )
824 if( getSingletonPtr()->_parents.empty() )
827 *out = getSingletonPtr()->getParents(c);
831 typename MemberMap::iterator member =
832 getSingletonPtr()->_members.find(key_str);
834 if( member == getSingletonPtr()->_members.end() )
837 if( member->second.func )
838 *out = nasal::to_nasal(c, member->second.func);
839 else if( !member->second.getter.empty() )
840 *out = member->second.getter(c, *Ghost::getRawPtr(g));
842 return "Read-protected member";
848 * Callback for writing to a ghost member.
850 static void setMember(naContext c, void* g, naRef field, naRef val)
852 const std::string key = nasal::from_nasal<std::string>(c, field);
853 typename MemberMap::iterator member =
854 getSingletonPtr()->_members.find(key);
856 if( member == getSingletonPtr()->_members.end() )
857 naRuntimeError(c, "ghost: No such member: %s", key.c_str());
858 if( member->second.setter.empty() )
859 naRuntimeError(c, "ghost: Write protected member: %s", key.c_str());
861 member->second.setter(c, *Ghost::getRawPtr(g), val);
867 #endif /* SG_NASAL_GHOST_HXX_ */