# Implementation

This page gives an overview of how Behaviors can be implemented.

#### **How to implement a Behavior**

There is very little difference between implementing a Widget and implementing a Behavior. Though there are some difference which will be explained below.

##### Base Class

The major difference is that Behaviors need to be derived from the [Candera::Behavior](http://dev.doc.cgistudio.at/APILINK/class_candera_1_1_behavior.html "Behaviors are small re-usable functional blocks that communicate via events. Behaviors are based on W...") base class instead of the [Candera::WidgetBase](http://dev.doc.cgistudio.at/APILINK/class_candera_1_1_widget_base.html "Abstract base class for Candera Widgets.") class. Incidentally the [Candera::Behavior](http://dev.doc.cgistudio.at/APILINK/class_candera_1_1_behavior.html "Behaviors are small re-usable functional blocks that communicate via events. Behaviors are based on W...") base class is internally derived from [Candera::WidgetBase](http://dev.doc.cgistudio.at/APILINK/class_candera_1_1_widget_base.html "Abstract base class for Candera Widgets.") further demonstrating the similarities between both.

<div class="contents" id="bkmrk-"><div class="contents"><div class="textblock">  
</div></div></div>##### Methods

<div drawio-diagram="2350"><img src="https://doc316en.candera.eu/uploads/images/drawio/2023-02/drawing-7-1677203692.png" alt=""/></div>

From the [Candera::WidgetBase](http://dev.doc.cgistudio.at/APILINK/class_candera_1_1_widget_base.html "Abstract base class for Candera Widgets.") the already known Init() and Update() methods are inherited.

<div class="contents" id="bkmrk-init%3A-called-once-wh"><div class="contents"><div class="textblock">- **Init:** Called once when the Widget/Behavior is created, after all Widget/Behavior properties have been set. This is used to initialize the Widget/Behavior.
- **Update:** Called once per iteration (frame). Here normally the Widget/Behavior performs its actual functionality.

</div></div></div>Newly added are the methods from [Candera::Behavior](http://dev.doc.cgistudio.at/APILINK/class_candera_1_1_behavior.html "Behaviors are small re-usable functional blocks that communicate via events. Behaviors are based on W...") which are related to event handling and the attached node:

<div class="contents" id="bkmrk-dispatchevent%3A-start"><div class="contents"><div class="textblock">- **DispatchEvent:** Starts dispatching an event with a specified strategy
- **OnEvent:** Called when an event is received by a Behavior
- **SetNode/GetNode:** Allows access to the node this behavior is attached to. Note that this uses a new data type called [Candera::AbstractNodePointer](http://dev.doc.cgistudio.at/APILINK/class_candera_1_1_abstract_node_pointer.html "The class AbstractCameraPointer is an wrapper class to abstract 2D and 3D camera nodes.") which abstracts between 2D and 3D nodes. This allows creating behaviors that work und 2D and 3D without duplicating code.

</div></div></div>##### META INFO

The Meta-Info is essential to provide generic access to all properties of the widget/behavior as well as special information for Scene-Composer about the available properties, their types and functionality. The available macros to define the Meta-Info are very similar to those used by widgets.

The first set of Macros defines a Behavior either for 3D, 2D or both (mixed):

```
    ...
    <a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___behavior_base.html#gac11e42b36cc6ee1a4814d07df4abff9b">CdaBehaviorDef</a>(<<ClassName>>, <<BaseClassName>>)
        [Information][Properties][Events] 
    <a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___behavior_base.html#ga1d66b72219f10490bc1faf9e1c2445bf">CdaBehaviorDefEnd</a>() 
    ... 
```

```
    ...  
    <a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___behavior_base.html#ga0df74c6a17b4313fffc1084d9fb4e60d">CdaBehavior2DDef</a>(<<ClassName>>, <<BaseClassName>>)
        [Information][Properties][Events] 
    <a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___behavior_base.html#ga1d66b72219f10490bc1faf9e1c2445bf">CdaBehaviorDefEnd</a>() 
    ...
```

```
    ...  
    <a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___behavior_base.html#gaa6c7bb84ac98320b27829f415f095ed9">CdaBehaviorMixedDef</a>(<<ClassName>>, <<BaseClassName>>)
        [Information][Properties][Events] 
    <a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___behavior_base.html#ga1d66b72219f10490bc1faf9e1c2445bf">CdaBehaviorDefEnd</a>()
    ...  
```

All other macros are the same as where used by Widgets. This includes the macros to add additional information:

```
    ...  
    CdaReadableName("Name")
    CdaCategory("Category")  
    CdaDescription("Description")
    ...  
```

As well as the macros to define properties:

```
... 
CdaProperties() 
...     [Property List] 
<a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___widget_base.html#gaadabeed44f0653634b664191cd875742">CdaPropertiesEnd</a>() 
...
```

```
... 
CdaProperty(<<Name>>, <<Type>>, <<Setter>>, <<Getter>>) 
CdaDescription("Column used by this Item inside the Area") 
CdaCategory("Area") 
<a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___meta_info.html#ga119bef57449bd05d8b3c40d7d514e375">CdaPropertyEnd</a>() 
... 
```

The new macros for events will be described in the <span style="color: rgb(230, 126, 35);">[Event Handling](https://doc316en.candera.eu/link/570#bkmrk-event-handling)</span> chapter.   
For further information about the Meta Info please also see chapter <span style="color: rgb(230, 126, 35);">[Behavior Definition](https://doc316en.candera.eu/link/568#bkmrk-page-title)</span>.

##### RUNTIME TYPE INFORMATION

CGI-Studio uses its own RTTI system for major parts instead of relying on the RTTI of the compiler. For this a set of macros is added to each class that uses this system. In case of Behaviors only a single macro is required to be added to the code:

```
... 
<a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___behavior_base.html#gade83d69bfb6ff6767119bbc71d3b76de">CGI_BEHAVIOR_RTTI_DEFINITION</a>(<<ClassName>>) 
... 
```

<div class="contents" id="bkmrk--1"><div class="contents"><div class="textblock"><div class="fragment">---

</div></div></div></div>#### **Event Handling**

Events are one of the major new features introduced via Behaviors. This chapter shows how they can be utilized from within the Behavior code.

##### Meta Info

The first requirement is to add all events that should are either received or sent to the Meta-Info via the following macros:

```
... 
<a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___behavior_base.html#gacffa930ff589666f40b4cfe1101e82fe">CdaEvents</a>()    
   <a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___behavior_base.html#gaf18af8294463f4c87092b0dd719ce807">CdaEvent</a>(<a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___behavior_base.html#ga1f87d4147378125fc817898dd84e98eb">CdaOutputEvent</a>, <<EventType>>, "Description")    
   <a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___behavior_base.html#gaf18af8294463f4c87092b0dd719ce807">CdaEvent</a>(CdaInputEvent, <<EventType>>, "Description") 
<a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___behavior_base.html#gaca0f18f1742e7e52edc48d782d902a7b">CdaEventsEnd</a>() 
...
```

##### Sending Events

An Event can be sent by multiple different approaches.

The first is achieved by calling the DispatchEvent() method of the Behavior or any of the other available alternatives. It requires providing the dispatch strategy and event itself. When using this method the dispatching will start from the current node of the Behavior.

```
... 
    CgiStudioControl::Event event;     
    EventDispatchResult dispatchResult;     
    EventDispatchStrategy dispatchStrategy; 
 
    DispatchEvent(dispatchStrategy, event, dispatchResult); 
... 
```

<div class="header" id="bkmrk-note-that-the-event-"><div class="header"><div class="headertitle"><div class="title"><div class="contents"><div class="contents"><div class="textblock"><div class="fragment">  
</div><dl class="note"><dd></dd><dd><p class="callout info">Note that the Event and EventDispatchStrategy need to be replaced with the concrete implementations.</p>

</dd><dd></dd><dd>The second options is to directly call the DispatchEvent() method of the Event-Dispatch-Strategy. This allows to define the node from which the dispatching should start:</dd><dd></dd></dl></div></div></div></div></div></div></div>```
... 
    Candera::EventDispatchResult eventDispatchResult; 
    <a class="code" href="http://dev.doc.cgistudio.at/APILINK/class_candera_1_1_broadcast_event_dispatch_strategy.html" title="Broadcast strategy: the event will be dispatched first for the node with a Direct strategy and then f...">Candera::BroadcastEventDispatchStrategy</a> dispatchStrategy; 
    <a class="code" href="http://dev.doc.cgistudio.at/APILINK/class_cgi_studio_control_1_1_change_value_event.html" title="Received by a ValueBehavior to change the value. Value can be absolute or relative (will be added)...">CgiStudioControl::ChangeValueEvent</a> valueChangedEvent(<a class="code" href="http://dev.doc.cgistudio.at/APILINK/class_feat_std_1_1_variant.html">FeatStd::Variant</a>(listDataEvent->GetData()),                                                            
                                                         CgiStudioControl::ChangeValue::Absolute); 
    dispatchStrategy.<a class="code" href="http://dev.doc.cgistudio.at/APILINK/class_candera_1_1_broadcast_event_dispatch_strategy.html#a2147a1a0a6eb0d4f93cd32dcd9404698">DispatchEvent</a>(GetNode(), valueChangedEvent, eventDispatchResult); 
... 
```

##### Receiving Events

Receiving of events is done via the OnEvent-Method. Here normally the incoming events are type-cast to check the Event-Type and processed if applicable. Further it is possible to stop further dispatching of the event via the Dispatch-Result. In case a custom Dispatch-Result is used (again type-casting can be used) then additional information can be returned to the sender.

```
... 
void ListItemEventBehavior::OnEvent(const <a class="code" href="http://dev.doc.cgistudio.at/APILINK/class_feat_std_1_1_event.html" title="Event serves as a base class for user derived events.">FeatStd::Event</a>& event, Candera::EventDispatchResult& dispatchResult) 
{     
    const ListDataEvent* listDataEvent = Candera::Dynamic_Cast<const ListDataEvent*>(&event); 
 
    if (0 != listDataEvent) {         
        if (m_index == listDataEvent->GetIndex()) {             
            dispatchResult.StopDispatchingImmediately(); 
 
            // Do something with the data of the event         
        }     
    } 
} 
... 
```

If derived from Behaviors that also do event processing also the Base-Class OnEvent method should be called.

```
... 
Base::OnEvent(event, dispatchResult); 
... 
```

##### Custom Events

It is possible to define custom events by simply deriving from [FeatStd::Event](http://dev.doc.cgistudio.at/APILINK/class_feat_std_1_1_event.html "Event serves as a base class for user derived events.") class. An Event can contain any number custom data.

```
... 
class ListDataEvent : public FeatStd::Event 
{     
    public:         
        FEATSTD_RTTI_DECLARATION(); 
 
        ListDataEvent(FeatStd::Int32 index, FeatStd::Int32 value) :             
            m_index(index),            
            m_value(value)         
        {         
        } 
 
        FeatStd::Int32 GetIndex() const         
        {             
            return m_index;         
        } 
 
        FeatStd::Int32 GetData() const         
        {             
            return m_value;         
        } 
 
    private:         
        FeatStd::Int32 m_index;         
        FeatStd::Int32 m_value; 
}; 
...
```

```
... 
FEATSTD_RTTI_DEFINITION(ListDataEvent, <a class="code" href="http://dev.doc.cgistudio.at/APILINK/class_feat_std_1_1_event.html" title="Event serves as a base class for user derived events.">FeatStd::Event</a>) 
... 
```

##### FINDING BEHAVIORS

The second major advantage compared to widgets is that it is now possible to determine if any and which Behaviors are attached to a node. This can be done by iterating over all behaviors of a node via the code snipped shown below.

```
... 
<a class="code" href="http://dev.doc.cgistudio.at/APILINK/class_candera_1_1_behavior.html" title="Behaviors are small re-usable functional blocks that communicate via events. Behaviors are based on W...">Candera::Behavior</a>* behavior = <a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___behavior_base.html#ga69a5dc63c0630e3ee64ada60854041bb">Candera::Behavior::GetFirstBehavior</a>(node); 
 
while (0 != behavior) {     
    // do something 
 
    behavior = behavior-><a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___behavior_base.html#gaeb8b1c6d391f8a18e57bf8b3a570239c">GetNextBehavior</a>(); 
} 
...
```

For a better understanding of how events work, please see chapter <span style="color: rgb(230, 126, 35);">[Predefined Behaviors](https://doc316en.candera.eu/link/566#bkmrk-page-title)</span>.

---

#### **How to integrate a Behavior into an Application**

Behaviors are integrated into the Application similar to Widgets by adding them to the Widget-Set. How this is exactly done depends on the application.

##### Adding Behaviors manually

If the application doesn't generate a Widget-Set automatically (e.g. MLC-Templates) the Behavior needs first to be added to the Build-System by modifying the existing CMake-files

<div class="contents" id="bkmrk-widgets.cmake-%28of-ml"><div class="contents"><div class="textblock"><table border="0"><tbody><tr><td>**Widgets.cmake (of MLC-Template App)**</td></tr><tr><td>```
... 
CourierAddProjectFiles(     
    OnOffWidget.cpp     
    OnOffWidget.h     
    WidgetSet.cpp 
 
    CustomBehavior.cpp     
    CustomBehavior.h 
)
```

</td></tr></tbody></table>

</div></div></div>And then added to the Widget-Set manually via the CdaWidget-Macro:

<div class="contents" id="bkmrk-widgetset.cpp-%28of-ml"><div class="contents"><div class="textblock"><table border="0"><tbody><tr><td>**WidgetSet.cpp (of MLC-Template App)**</td></tr><tr><td>```
... 
#include "OnOffWidget.h" 
#include "CustomBehavior.h" 
... 
<a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___widget_base.html#gaf22698a7899d856911f78b17f154dcb2">CdaWidgetSet</a>(MatlabConnectorApplicationWidgetSet)     
    CdaDescription("MatlabConnectorApplication <a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___c_o_u_r_i_e_r___m_e_s_s_a_g_i_n_g.html#ggac4e3f0853af916ef773e65d02a15c95dac1224e2f0bf57d4eede7026521a13aa8">Widget</a> Set")     
    <a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___widget_base.html#gada111508ebf4b6014fe2564083936d3e">CdaWidgets</a>()         
        <a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___widget_base.html#ga311ed10f0878a04c24365fa67fd7e152">CdaWidget</a>(OnOffWidget)         
        <a class="code" href="http://dev.doc.cgistudio.at/APILINK/group___widget_base.html#ga311ed10f0878a04c24365fa67fd7e152">CdaWidget</a>(ListDataSimBehavior) 
... 
```

</td></tr></tbody></table>

</div></div></div>##### Adding Behaviors to Default Behavior Project

If the Widget-Set is generated (Player application) then under normal conditions it is sufficient to add the code files to the Build-System (CMake). Here they are added to the "Default Behavior Project" (ControlBehaviors\_1).

To do this, create a folder (e.g. "Custom") in "cgi\_studio\_controls\\src\\Behaviors" containing the Custom-Behavior's code and a FileList.txt file containing the related code files.

<div class="contents" id="bkmrk--3"><div class="contents"><div class="textblock"><div drawio-diagram="2351"><img src="https://doc316en.candera.eu/uploads/images/drawio/2023-02/drawing-7-1677204085.png" alt=""/></div>

</div></div></div><div class="contents" id="bkmrk-filelist.txt-set%28fil"><div class="contents"><div class="textblock"><table border="0"><tbody><tr><td>**FileList.txt**</td></tr><tr><td>```
set(FILE_LIST     
    CustomBehavior.cpp     
    CustomBehavior.h 
) 
```

</td></tr></tbody></table>

</div></div></div>Then add the folder to the CMakeLists.txt found in "cgi\_studio\_controls\\src\\Behaviors"

<div class="contents" id="bkmrk-cmakelists.txt-...-s"><div class="contents"><div class="textblock"><table border="0"><tbody><tr><td>**CMakeLists.txt**</td></tr><tr><td>```
... 
set(PRV_WIDGET_SUBDIRS     
    Animation 
...     
    Custom 
) 
... 
```

</td></tr></tbody></table>

</div></div></div>##### Adding Behavior to new Project

Another way to add the Behavior, if the Widget-Set is generated (Player application), is to create a new project containing the custom behaviors. This approach is preferred to changing the default behavior project as no code from CGI-Studio itself is modified. Also it is easy to include these custom behaviors into other projects as well.

To start create a folder with the custom behavior code, a FileList.txt file and a CMakeLists.txt file.

<div class="contents" id="bkmrk--5"><div class="contents"><div class="textblock"><div drawio-diagram="2352"><img src="https://doc316en.candera.eu/uploads/images/drawio/2023-02/drawing-7-1677204106.png" alt=""/></div>

</div></div></div>  
In the FileList.txt file add the required code files.

<div class="contents" id="bkmrk-filelist.txt-set%28fil-0"><div class="contents"><div class="textblock"><table border="0"><tbody><tr><td>**FileList.txt**</td></tr><tr><td>```
set(FILE_LIST      
    FileList.txt     
    CustomSwitchRangeProcessValueBehavior.h     
    CustomSwitchRangeProcessValueBehavior.cpp 
)
```

</td></tr></tbody></table>

</div></div></div>In the CMakeList.txt file specify the name of the new project (here "ControlBehaviors\_2") and optional all subfolders which should be searched.

<div class="contents" id="bkmrk-cmakelists.txt-%23-dec"><div class="contents"><div class="textblock"><table border="0"><tbody><tr><td>**CMakeLists.txt**</td></tr><tr><td>```
# declared directories to include these directories 
# must provide a "FileList.txt" which lists all files 
set(PRV_WIDGET_SUBDIRS     
    . 
) 
 
CgiGetCurrentDir(PRV_CUR_DIR) 
CgiAddIncludeDirs(${PRV_CUR_DIR}/..) 
 
set(PRV_APP_NAME "ControlBehaviors_2") 
source_group(PRV_ALL_SRCS FILES ${PRV_WIDGET_SUBDIRS}) 
CgiCollectListedFiles(PRV_ALL_SRCS ${PRV_APP_NAME} "" LIST ${PRV_WIDGET_SUBDIRS}) 
 
CgiAddStaticLibrary(PRV_APP_TARGET_NAME ${PRV_APP_NAME} ${PRV_ALL_SRCS}
```

</td></tr></tbody></table>

</div></div></div>Finally in the "AdditionalBehaviorsPaths.txt" of the application add the new folder.

<div class="contents" id="bkmrk-additionalbehaviorsp"><div class="textblock"><table border="0"><tbody><tr><td>**AdditionalBehaviorsPaths.txt**</td></tr><tr><td>```
# Additional Behaviors 
# declare all directories to include (one directory per line) 
# these directories must provide a "FileList.txt" file which lists all files 
# all subdirectories containing a "FileList.txt" file will also be included 
# path must be relative to Default widget directory 
# lines starting with # will be ignored 
# 
 
../../../cgi_studio_controls/src/Behaviors 
../CustomBehaviors 
```

</td></tr></tbody></table>

</div></div>