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 * Get the argument with given index if it exists. Otherwise returns the
234 * passed default value.
236 * @tparam T Type of argument (converted using ::from_nasal)
237 * @param index Index of requested argument
238 * @param def Default value returned if too few arguments available
241 T getArg(size_t index, const T& def = T()) const
246 return from_nasal<T>(c, args[index]);
250 * Get the argument with given index. Raises a Nasal runtime error if there
251 * are to few arguments available.
254 T requireArg(size_t index) const
257 naRuntimeError(c, "Missing required arg #%d", index);
259 return from_nasal<T>(c, args[index]);
268 * Class for exposing C++ objects to Nasal
271 * // Example class to be exposed to Nasal
278 * naRef myMember(naContext c, int argc, naRef* args);
281 * void exposeClasses()
283 * // Register a nasal ghost type for MyClass. This needs to be done only
284 * // once before creating the first ghost instance.
285 * Ghost<MyClass>::init("MyClass")
286 * // Members can be exposed by getters and setters
287 * .member("x", &MyClass::getX, &MyClass::setX)
288 * // For readonly variables only pass a getter
289 * .member("x_readonly", &MyClass::getX)
290 * // It is also possible to expose writeonly members
291 * .member("x_writeonly", &MyClass::setX)
292 * // Methods use a slightly different syntax - The pointer to the member
293 * // function has to be passed as template argument
294 * .method<&MyClass::myMember>("myMember");
300 public internal::GhostMetadata,
301 protected boost::mpl::if_< typename GhostTypeTraits<T>::is_shared,
302 SharedPointerPolicy<T>,
303 RawPointerPolicy<T> >::type
306 typedef T value_type;
307 typedef typename GhostTypeTraits<T>::raw_type raw_type;
308 typedef typename Ghost::pointer pointer;
309 typedef naRef (raw_type::*member_func_t)(const CallContext&);
310 typedef naRef (*free_func_t)(raw_type&, const CallContext&);
311 typedef boost::function<naRef(naContext, raw_type&)> getter_t;
312 typedef boost::function<void(naContext, raw_type&, naRef)> setter_t;
315 * A ghost member. Can consist either of getter and/or setter functions
316 * for exposing a data variable or a single callable function.
324 member_t( const getter_t& getter,
325 const setter_t& setter,
326 naCFunction func = 0 ):
332 member_t(naCFunction func):
341 typedef std::map<std::string, member_t> MemberMap;
344 * Register a new ghost type.
346 * @note Only intialize each ghost type once!
348 * @param name Descriptive name of the ghost type.
350 static Ghost& init(const std::string& name)
352 assert( !getSingletonPtr() );
354 getSingletonHolder().reset( new Ghost(name) );
355 return *getSingletonPtr();
359 * Register a base class for this ghost. The base class needs to be
360 * registers on its own before it can be used as base class.
362 * @tparam BaseGhost Type of base class already wrapped into Ghost class
366 * Ghost<MyBase>::init("MyBase");
367 * Ghost<MyClass>::init("MyClass")
368 * .bases<Ghost<MyBase> >();
371 template<class BaseGhost>
372 typename boost::enable_if_c
373 < boost::is_base_of<GhostMetadata, BaseGhost>::value
374 && boost::is_base_of<typename BaseGhost::raw_type, raw_type>::value,
379 BaseGhost* base = BaseGhost::getSingletonPtr();
383 // Both ways of retrieving the address of a static member function
384 // should be legal but not all compilers know this.
385 // g++-4.4.7+ has been tested to work with both versions
386 #if defined(GCC_VERSION) && GCC_VERSION < 40407
387 // The old version of g++ used on Jenkins (16.11.2012) only compiles
389 &getTypeFor<BaseGhost>
391 // VS (2008, 2010, ... ?) only allow this version.
392 &Ghost::getTypeFor<BaseGhost>
396 // Replace any getter that is not available in the current class.
397 // TODO check if this is the correct behavior of function overriding
398 for( typename BaseGhost::MemberMap::const_iterator member =
399 base->_members.begin();
400 member != base->_members.end();
403 if( _members.find(member->first) == _members.end() )
404 _members[member->first] = member_t
406 member->second.getter,
407 member->second.setter,
416 * Register a base class for this ghost. The base class needs to be
417 * registers on its own before it can be used as base class.
419 * @tparam Base Type of base class (Base as used in Ghost<Base>)
422 * Ghost<MyBase>::init("MyBase");
423 * Ghost<MyClass>::init("MyClass")
428 typename boost::enable_if_c
429 < !boost::is_base_of<GhostMetadata, Base>::value
430 && boost::is_base_of<typename Ghost<Base>::raw_type, raw_type>::value,
435 return bases< Ghost<Base> >();
439 * Register an existing Nasal class/hash as base class for this ghost.
441 * @param parent Nasal hash/class
443 Ghost& bases(const naRef& parent)
445 addNasalBase(parent);
450 * Register a member variable by passing a getter and/or setter method.
452 * @param field Name of member
453 * @param getter Getter for variable
454 * @param setter Setter for variable (Pass 0 to prevent write access)
458 Ghost& member( const std::string& field,
459 Var (raw_type::*getter)() const,
460 void (raw_type::*setter)(Var) = 0 )
465 naRef (*to_nasal_)(naContext, Var) = &nasal::to_nasal;
467 // Getter signature: naRef(naContext, raw_type&)
468 m.getter = boost::bind(to_nasal_, _1, boost::bind(getter, _2));
473 Var (*from_nasal_)(naContext, naRef) = &nasal::from_nasal;
475 // Setter signature: void(naContext, raw_type&, naRef)
476 m.setter = boost::bind(setter, _2, boost::bind(from_nasal_, _1, _3));
479 return member(field, m.getter, m.setter);
483 * Register a write only member variable.
485 * @param field Name of member
486 * @param setter Setter for variable
489 Ghost& member( const std::string& field,
490 void (raw_type::*setter)(Var) )
492 return member<Var>(field, 0, setter);
496 * Register a member variable by passing a getter and/or setter method.
498 * @param field Name of member
499 * @param getter Getter for variable
500 * @param setter Setter for variable (Pass empty to prevent write access)
503 Ghost& member( const std::string& field,
504 const getter_t& getter,
505 const setter_t& setter = setter_t() )
507 if( !getter.empty() || !setter.empty() )
508 _members[field] = member_t(getter, setter);
514 "Member '" << field << "' requires a getter or setter"
520 * Register a member function.
522 * @note Because only function pointers can be registered as Nasal
523 * functions it is needed to pass the function pointer as template
524 * argument. This allows us to create a separate instance of the
525 * MemberFunctionWrapper for each registered function and therefore
526 * provides us with the needed static functions to be passed on to
529 * @tparam func Pointer to member function being registered.
535 * naRef myMethod(naContext c, int argc, naRef* args);
538 * Ghost<MyClass>::init("Test")
539 * .method<&MyClass::myMethod>("myMethod");
542 template<member_func_t func>
543 Ghost& method(const std::string& name)
545 _members[name].func = &MemberFunctionWrapper<func>::call;
550 * Register a free function as member function. The object instance is
551 * passed as additional first argument.
553 * @tparam func Pointer to free function being registered.
555 * @note Due to a severe bug in Visual Studio it is not possible to create
556 * a specialization of #method for free function pointers and
557 * member function pointers at the same time. Do overcome this
558 * limitation we had to use a different name for this function.
562 * naRef myMethod(MyClass& obj, naContext c, int argc, naRef* args);
564 * Ghost<MyClass>::init("Test")
565 * .method_func<&myMethod>("myMethod");
568 template<free_func_t func>
569 Ghost& method_func(const std::string& name)
571 _members[name].func = &FreeFunctionWrapper<func>::call;
575 // TODO use variadic template when supporting C++11
577 * Create a Nasal instance of this ghost.
579 * @param c Active Nasal context
581 static naRef create( naContext c )
583 return makeGhost(c, Ghost::createInstance());
587 * Create a Nasal instance of this ghost.
589 * @param c Active Nasal context
590 * @param a1 Parameter used for creating new instance
593 static naRef create( naContext c, const A1& a1 )
595 return makeGhost(c, Ghost::createInstance(a1));
599 * Nasal callback for creating a new instance of this ghost.
601 static naRef f_create(naContext c, naRef me, int argc, naRef* args)
606 static bool isBaseOf(naGhostType* ghost_type)
611 return getSingletonPtr()->GhostMetadata::isBaseOf(ghost_type);
614 static bool isBaseOf(naRef obj)
616 return isBaseOf( naGhost_type(obj) );
620 * Convert Nasal object to C++ object. To get a valid object the passed
621 * Nasal objects has to be derived class of the target class (Either
622 * derived in C++ or in Nasal using a 'parents' vector)
624 static pointer fromNasal(naContext c, naRef me)
626 // Check if it's a ghost and if it can be converted
627 if( isBaseOf( naGhost_type(me) ) )
628 return Ghost::getPtr( naGhost_ptr(me) );
630 // Now if it is derived from a ghost (hash with ghost in parent vector)
631 else if( naIsHash(me) )
633 naRef na_parents = naHash_cget(me, const_cast<char*>("parents"));
634 if( !naIsVector(na_parents) )
636 SG_LOG(SG_NASAL, SG_DEBUG, "Missing 'parents' vector for ghost");
640 typedef std::vector<naRef> naRefs;
641 naRefs parents = from_nasal<naRefs>(c, na_parents);
642 for( naRefs::const_iterator parent = parents.begin();
643 parent != parents.end();
646 pointer ptr = fromNasal(c, *parent);
660 typedef naGhostType* (*type_checker_t)(const raw_type*);
661 typedef std::vector<type_checker_t> DerivedList;
662 DerivedList _derived_types;
664 void addDerived( const internal::GhostMetadata* derived_meta,
665 const type_checker_t& derived_info )
667 GhostMetadata::addDerived(derived_meta);
668 _derived_types.push_back(derived_info);
671 template<class BaseGhost>
673 typename boost::enable_if
674 < boost::is_polymorphic<typename BaseGhost::raw_type>,
677 getTypeFor(const typename BaseGhost::raw_type* base)
679 // Check first if passed pointer can by converted to instance of class
682 < typename BaseGhost::raw_type,
683 typename Ghost::raw_type
685 && dynamic_cast<const typename Ghost::raw_type*>(base) != base )
688 // Now check if we can further downcast to one of our derived classes.
689 for( typename DerivedList::reverse_iterator
690 derived = getSingletonPtr()->_derived_types.rbegin();
691 derived != getSingletonPtr()->_derived_types.rend();
694 naGhostType* ghost_type =
695 (*derived)( static_cast<const typename Ghost::raw_type*>(base) );
700 // If base is not an instance of any derived class, this class has to
701 // be the dynamic type.
702 return &getSingletonPtr()->_ghost_type;
705 template<class BaseGhost>
707 typename boost::disable_if
708 < boost::is_polymorphic<typename BaseGhost::raw_type>,
711 getTypeFor(const typename BaseGhost::raw_type* base)
713 // For non polymorphic classes there is no possibility to get the actual
714 // dynamic type, therefore we can only use its static type.
715 return &BaseGhost::getSingletonPtr()->_ghost_type;
718 static Ghost* getSingletonPtr()
720 return getSingletonHolder().get();
723 static raw_type& requireObject(naContext c, naRef me)
725 raw_type* obj = Ghost::getRawPtr( fromNasal(c, me) );
726 naGhostType* ghost_type = naGhost_type(me);
732 "method called on object of wrong type: is '%s' expected '%s'",
733 ghost_type ? ghost_type->name : "unknown",
734 getSingletonPtr()->_ghost_type.name
741 * Wrapper class to enable registering pointers to member functions as
742 * Nasal function callbacks. We need to use the function pointer as
743 * template parameter to ensure every registered function gets a static
744 * function which can be passed to Nasal.
746 template<member_func_t func>
747 struct MemberFunctionWrapper
750 * Called from Nasal upon invocation of the according registered
751 * function. Forwards the call to the passed object instance.
753 static naRef call(naContext c, naRef me, int argc, naRef* args)
755 return (requireObject(c, me).*func)(CallContext(c, argc, args));
760 * Wrapper class to enable registering pointers to free functions (only
761 * external linkage). We need to use the function pointer as template
762 * parameter to ensure every registered function gets a static function
763 * which can be passed to Nasal. Even though we just wrap another simple
764 * function pointer this intermediate step is need to be able to retrieve
765 * the object the function call belongs to and pass it along as argument.
767 template<free_func_t func>
768 struct FreeFunctionWrapper
771 * Called from Nasal upon invocation of the according registered
772 * function. Forwards the call to the passed function pointer and passes
773 * the required parameters.
775 static naRef call(naContext c, naRef me, int argc, naRef* args)
777 return func(requireObject(c, me), CallContext(c, argc, args));
781 typedef std::auto_ptr<Ghost> GhostPtr;
784 explicit Ghost(const std::string& name):
785 GhostMetadata( name )
787 _ghost_type.destroy = &destroyGhost;
788 _ghost_type.name = _name.c_str();
789 _ghost_type.get_member = &getMember;
790 _ghost_type.set_member = &setMember;
793 static GhostPtr& getSingletonHolder()
795 static GhostPtr instance;
799 static naRef makeGhost(naContext c, void *ptr)
801 if( !Ghost::getRawPtr(ptr) )
804 naGhostType* ghost_type = 0;
805 if( Ghost::returns_dynamic_type::value )
806 // For pointer policies already returning instances of an object with
807 // the dynamic type of this Ghost's raw_type the type is always the
809 ghost_type = &getSingletonPtr()->_ghost_type;
811 // If wrapping eg. shared pointers the users passes an already
812 // existing instance of an object which will then be hold be a new
813 // shared pointer. We therefore have to check for the dynamic type
814 // of the object as it might differ from the passed static type.
815 ghost_type = getTypeFor<Ghost>( Ghost::getRawPtr(ptr) );
820 return naNewGhost2(c, ghost_type, ptr);
823 static void destroyGhost(void *ptr)
829 * Callback for retrieving a ghost member.
831 static const char* getMember(naContext c, void* g, naRef key, naRef* out)
833 const std::string key_str = nasal::from_nasal<std::string>(c, key);
834 if( key_str == "parents" )
836 if( getSingletonPtr()->_parents.empty() )
839 *out = getSingletonPtr()->getParents(c);
843 typename MemberMap::iterator member =
844 getSingletonPtr()->_members.find(key_str);
846 if( member == getSingletonPtr()->_members.end() )
849 if( member->second.func )
850 *out = nasal::to_nasal(c, member->second.func);
851 else if( !member->second.getter.empty() )
852 *out = member->second.getter(c, *Ghost::getRawPtr(g));
854 return "Read-protected member";
860 * Callback for writing to a ghost member.
862 static void setMember(naContext c, void* g, naRef field, naRef val)
864 const std::string key = nasal::from_nasal<std::string>(c, field);
865 typename MemberMap::iterator member =
866 getSingletonPtr()->_members.find(key);
868 if( member == getSingletonPtr()->_members.end() )
869 naRuntimeError(c, "ghost: No such member: %s", key.c_str());
870 if( member->second.setter.empty() )
871 naRuntimeError(c, "ghost: Write protected member: %s", key.c_str());
873 member->second.setter(c, *Ghost::getRawPtr(g), val);
879 #endif /* SG_NASAL_GHOST_HXX_ */