Custom ScriptingModule

From CEGUI Wiki - Crazy Eddie's GUI System (Open Source)
Jump to: navigation, search

Written for CEGUI 0.5


Works with versions 0.5.x (obsolete)

This article show how to create a custom ScriptingModule that can catch events.

This code has been tested with version 0.5.

A very basic ScriptingModule

This very basic scripting module link any event to a CommandInterpretor class.

 /// Specialized scripting module for CEGUI 
 class ScriptingModule : public CEGUI::ScriptModule
 {
 public:
   
   virtual CEGUI::Event::Connection subscribeEvent(
       CEGUI::EventSet*     target, 
       const CEGUI::String& name, 
       const CEGUI::String& subscriber_name)
   {
     CommandInterpretor command(subscriber_name.c_str()) ;
     return target->subscribeEvent(name,CEGUI::Event::Subscriber(command)) ;
   }
   
   virtual CEGUI::Event::Connection subscribeEvent(
       CEGUI::EventSet*     target,
       const CEGUI::String& name,
       CEGUI::Event::Group  group,
       const CEGUI::String& subscriber_name)
   {
     CommandInterpretor command(subscriber_name.c_str()) ;
     return target->subscribeEvent(name,group,CEGUI::Event::Subscriber(command)) ;
   }
   
   virtual void executeScriptFile(const CEGUI::String &filename, const CEGUI::String &resourceGroup="")
   {}
   
   virtual int executeScriptGlobal(const CEGUI::String& function_name)
   {
     return 0 ;
   }
   
   
   virtual void executeString(const CEGUI::String &str)
   {}
   
   virtual bool executeScriptedEventHandler(
       const CEGUI::String& handler_name,
       const CEGUI::EventArgs &e)
   {
     return true ;
   }
 };

The two important methods are subscribeEvent that link an event to a subscriber that is implemented by a basic event handler.

A very basic event handler

Here the main function is operator() that will be called with an EventArgs parameter. We already have the name of the function

 /// Callback for a event command 
 class CommandInterpretor
 {
 public:
   
   CommandInterpretor(const std::string& name)
   : m_name(name)
   {}
   
   bool operator()(const CEGUI::EventArgs& args) const
   {
     std::cout << m_name ;
     
     const CEGUI::WindowEventArgs* argument = dynamic_cast<const CEGUI::WindowEventArgs*>(&args) ;
     
     if (argument)
     {
       // we have the window that triggered the event
       std::cout << " " << argument->window->getName() ;
     }
     
     std::cout << std::endl ;
     
     return true ;
   }
   
   std::string m_name ;
   
 };

Setup

The ScriptModule can be registered to CEGUI::System either at construction time :

 new CEGUI::System(CEGUIRenderer,0,0,module) ;

or after :

 CEGUI::System::getSingleton().setScriptingModule(module) ;

Example

If you put :

<Event Name="Clicked" Function="play"/>

in the layout of a button named Foo, you will have

play Foo

printed on screen

Misc notes

To also have the name of the event triggered, you can add this name to the constructor of CommandInterpretor.