Jump to content

  • Log In with Google      Sign In   
  • Create Account






My Component Base Entity System, Part 3

Posted by BeerNutts, 23 December 2011 · 1,006 views

You probably notice I'm flying through these articles. Mainly, it's because I want to get these Component articles out of the way and get to writing a new game.

So, this time I'm going to go over some of the SmashPC specific Components. You can get the full Source code here:
SmashPcComp-12-23-11


So, here's a list of the components I have for the game, and what they do:
Camera - This component signifies where the center of the camera should be drawn within the game world. CUrrently, it's always on the Player, but, you could do cool things with it, like moving it to a remote-controlled entity for a short time.
Enemy - This component handles the logic for the enemy. It has 2 timers, one to control how often he turns towards the player, and one to control how often he fires his weapon.
EnemySpawn - This handles the releasing of the enemies into the world. When it's timer expires, it creates an ADD_ENTITY_EVENT for the Enemy.
GraphicsObject - Handles drawing it's entity if it's a sprite. It gets it's entity's physical component and finds the current camera location so it knows where to draw itself.
GraphicsShape - Same as GraphicsObject, except it deal with entities that are shapes, not sprites.
Input - Handles sending Input event to it's owner entity. Currently, only player is controlled, but, as with camera, could be moved around to other entities to do fun stuff.
PhysicalObject - Handles representing an entity in the physical world. It contains the location and the shape of the object. This object is given force, angle, and location. It is this object that all collisions originate via a callback from the physics library. The SetCollision() is used to detail what other type of entities it should get notified of collisions.
Player - Handles all the logic for controlling the player. It get input events and tells others where the player is (like the enemy).
Sound - Handles playing sounds on certain events. This component is controversial. I'm really not sure what it adds, since I typically can just play a sound whenever the event happens. But, I added it, and I'm using it, via the SetSound(), which plays a sound on a specific event.
Weaponry - Handles firing bullets, and, for a player, handles acquiring new weapons. Has a refire timer that, when expires, allows a new bullet to be fired.

Well take a look at the Input and Player Components here to get a better understanding of how it would work.

First, Input:

class TInput : public TComponent
{
public:

    struct TInputData
    {
        uint32_t KeyMask;
        uint32_t MouseX;
        uint32_t MouseY;
    };

    TInput();
    ~TInput();

    /******************************************************************
    *
    *  OnFrameTick - Callback for a frame tick
    *
    *******************************************************************/
    static void OnFrameTick(TEvent &Event, void *pThis);

    /******************************************************************
    *
    *  OnFrameTick - Callback for a frame tick
    *
    *******************************************************************/
    void FrameTick(TEvent &Event);

protected:
    virtual void Cleanup();
    virtual void Initialize();

private:
    sf::RenderWindow *mpApp;
    bool mbWasKeyPressed;
    uint32_t mMouseX, mMouseY;

};

The header is pretty simple. We create the TInputData struct to send during events. Otherwise, it gets notified every frame tick, and keeps the current mouse location and the main SFML Window.

Here's the source code.

/******************************************************************
*
*  TInput - Constructor, simple
*
*******************************************************************/
TInput::TInput() :
  TComponent(INPUT_COMPONENT)
{


    mMouseX = 0;
    mMouseY = 0;

    mbWasKeyPressed = false;
}

/******************************************************************
*
*  ~TInput - DeConstructor
*
*******************************************************************/
TInput::~TInput()
{

}


/******************************************************************
*
*  OnFrameTick - Callback for a frame tick
*
*******************************************************************/
void TInput::OnFrameTick(TEvent &Event, void *pThis)
{
    TInput *pInput =
        reinterpret_cast<TInput *>(pThis);

    pInput->FrameTick(Event);
}

/******************************************************************
*
*  OnFrameTick - Callback for a frame tick
*
*******************************************************************/
void TInput::FrameTick(TEvent &Event)
{
    const sf::Input& Input = mpApp->GetInput();
    uint32_t Key;
    TInputData InputData;
    InputData.KeyMask = 0;
    bool bMouse = false;

    // Loop through the possible keys, and check what's
    // being pushed
    for (Key = (uint32_t)GAME_KEY_FIRST; Key < (uint32_t)GAME_KEY_MAX; Key++) {
        if (Utilities::KeyIsDown(Input, (etGameKeys)Key)) {
            InputData.KeyMask |= (1 << Key);
            mbWasKeyPressed = true;
        }
    }

    // Check for mouse movement
    InputData.MouseX = Input.GetMouseX();
    InputData.MouseY = Input.GetMouseY();

    if (mMouseX != InputData.MouseX || mMouseY != InputData.MouseY) {
        mMouseX =InputData.MouseX;
        mMouseY = InputData.MouseY;
        bMouse = true;
    }

    if (InputData.KeyMask || bMouse) {
        TEvent InputEvent(INPUT_EVENT, this, "Action");

        InputEvent.SetData(&InputData);
        mpOwnerEntity->SetEvent(InputEvent);
    }
    else if (mbWasKeyPressed) {
        mbWasKeyPressed = false;
        TEvent InputEvent(INPUT_EVENT, this, "Action");

        InputEvent.SetData(&InputData);
        mpOwnerEntity->SetEvent(InputEvent);
    }

    // Check for number key's being pressed
    // Check for user choosing weapon (number pad)
    sf::Key::Code KeyDown = Utilities::CheckKeyRange(
                                Input, sf::Key::Num0, sf::Key::Num9);

    if (KeyDown != sf::Key::Count)
    {
        std::stringstream ss;
        ss << (uint32_t)(KeyDown - sf::Key::Num0);
        std::string Filter = ss.str();

        TEvent InputEvent(INPUT_EVENT, this,
                          Filter);

        mpOwnerEntity->SetEvent(InputEvent);
    }

}

/******************************************************************
*
*  Cleanup - Cleanup any used resources
*
*******************************************************************/
void TInput::Cleanup()
{
    printf("TInput::Cleanup\n");
}

/******************************************************************
*
*  Initialize - Initialize all resources
*
*******************************************************************/
void TInput::Initialize()
{
    TEvent AppEvent(EVENT_DATA_EVENT, this, "GetApp");
    AppEvent.SetData(&mpApp);
    TEntityManager::GetInstance()->SetEvent(AppEvent);

    // register for a Frame Tick update
    mpOwnerEntity->RegisterForEvent(TInput::OnFrameTick,
                                    (void *)this,
                                    FRAME_UPDATE_EVENT);
}

Starting at the bottom again, Initialize(), we set the event to get the main SFML RenderWindow, which generates the input. We also register to get notified of every tick.

The rest of the work is done in FrameTick(), where we check if any key is down, and check if the mouse moved. If so, we generate events saying so. If a button was down last time, but not now, we send an empty KeyMask Event.

Here's Player.h

class TPlayer : public TComponent
{
public:

    TPlayer(uint32_t Speed);
    ~TPlayer();

    /******************************************************************
    *
    *  OnInput - Callback for handling Input events
    *
    *******************************************************************/
    static void OnInput(TEvent &Event, void *pThis);

    /******************************************************************
    *
    *  OnInput - Callback for handling Input events
    *
    *******************************************************************/
    void Input(TEvent &Event);

    /******************************************************************
    *
    *  OnEventData - Callback for getting the camera location
    *
    *******************************************************************/
    static void OnEventData(TEvent &Event, void *pThis);

    /******************************************************************
    *
    *  OnEventData - Callback for getting the camera location
    *
    *******************************************************************/
    void EventData(TEvent &Event);

protected:
    virtual void Cleanup();
    virtual void Initialize();

    uint32_t mSpeed;
    TPhysicalObject *mpOurPhysicalObj;

    double mCenterX;
    double mCenterY;

};
And the source code:

/******************************************************************
*
*  TPlayer - Constructor, simple
*
*******************************************************************/
TPlayer::TPlayer(uint32_t Speed) :
  TComponent(PLAYER_LOGIC_COMPONENT),
  mSpeed(Speed)
{
    mpOurPhysicalObj = NULL;
}

/******************************************************************
*
*  ~TPlayer - DeConstructor
*
*******************************************************************/
TPlayer::~TPlayer()
{

}

/******************************************************************
*
*  OnEventData - Callback for getting the player's location
*
*******************************************************************/
void TPlayer::OnEventData(TEvent &Event, void *pThis)
{
    if (Event.GetFilter() == "PlayerLoc") {
        TPlayer *pPlayer =
            reinterpret_cast<TPlayer *>(pThis);

        pPlayer->EventData(Event);
    }
}

/******************************************************************
*
*  OnEventData - Callback for getting the player's location
*
*******************************************************************/
void TPlayer::EventData(TEvent &Event)
{
    *((TPhysicalObject **)Event.GetData()) = mpOurPhysicalObj;
}

/******************************************************************
*
*  OnInput - Callback for handling Input events
*
*******************************************************************/
void TPlayer::OnInput(TEvent &Event, void *pThis)
{
    // We don't care about the number keys, only movement here
    if (Event.GetFilter() == "Action") {
        TPlayer *pPlayer =
            reinterpret_cast<TPlayer *>(pThis);

        pPlayer->Input(Event);
    }
}

/******************************************************************
*
*  OnInput - Callback for handling Input events
*
*******************************************************************/
void TPlayer::Input(TEvent &Event)
{
    TInput::TInputData *pInputData;

    // if we don't have our physics component, get it
    if (mpOurPhysicalObj == NULL) {
        mpOurPhysicalObj = dynamic_cast<TPhysicalObject *>(
            mpOwnerEntity->GetComponent(PHYSICAL_OBJECT_COMPONENT));

        if (mpOurPhysicalObj == NULL) {
            printf("Player Object with no Physical Object! ABORT ABORT!!\n");
        }
    }
    pInputData = ((TInput::TInputData *)Event.GetData());

    cpFloat xForce = 0, yForce = 0;
    cpVect Vel;
    bool bChangeVelocity = false;

    mpOurPhysicalObj->GetVelocity(Vel);

    // We'll just assign velocities to a hardcoded value for now
    if (pInputData->KeyMask & (1 << (uint32_t)GAME_KEY_LEFT))
        xForce -= mSpeed*20;
    else if (Vel.x < -0.01f) {
        Vel.x = 0;
        bChangeVelocity = true;
    }

    if (pInputData->KeyMask & (1 << (uint32_t)GAME_KEY_RIGHT))
        xForce += mSpeed*20;
    else if (Vel.x > 0.01f) {
        Vel.x = 0;
        bChangeVelocity = true;
    }

    if (pInputData->KeyMask & (1 << (uint32_t)GAME_KEY_DOWN))
        yForce += mSpeed*20;
    else if (Vel.y > 0.01f) {
        Vel.y = 0;
        bChangeVelocity = true;
    }

    if (pInputData->KeyMask & (1 << (uint32_t)GAME_KEY_UP))
        yForce -= mSpeed*20;
    else if (Vel.y < -0.01f) {
        Vel.y = 0;
        bChangeVelocity = true;
    }

    if (bChangeVelocity) {
        mpOurPhysicalObj->SetVelocity(Vel);
    }

    mpOurPhysicalObj->SetForce(cpv(xForce, yForce));

    // Finally, find location of Mouse and point player towards it
    cpFloat MouseX = (cpFloat)pInputData->MouseX;
    cpFloat MouseY = (cpFloat)pInputData->MouseY;

    cpFloat Angle = atan2(MouseY - mCenterY,
                          MouseX - mCenterX);
    mpOurPhysicalObj->SetAngle(Angle);

}

/******************************************************************
*
*  Cleanup - Cleanup any used resources
*
*******************************************************************/
void TPlayer::Cleanup()
{
    printf("TPlayerCleanup\n");

}

/******************************************************************
*
*  Initialize - Initialize all resources
*
*******************************************************************/
void TPlayer::Initialize()
{
    // Get the render window so w know where center is
    sf::RenderWindow *pApp;
    TEvent AppEvent(EVENT_DATA_EVENT, this, "GetApp");
    AppEvent.SetData(&pApp);
    TEntityManager::GetInstance()->SetEvent(AppEvent);

    mCenterX = (double)(pApp->GetWidth()/2);
    mCenterY = (double)(pApp->GetHeight()/2);

    // We want to get the message for our location from entity manager
    mpOwnerEntity->RegisterForEvent(TPlayer::OnInput,
                                        (void *)this,
                                        INPUT_EVENT);

    mpOurPhysicalObj = dynamic_cast<TPhysicalObject *>(
        mpOwnerEntity->GetComponent(PHYSICAL_OBJECT_COMPONENT));

    if (mpOurPhysicalObj == NULL) {
        printf("TPlayer Object with no Physical Object! ABORT ABORT!!\n");
    }

    // We want to get the message for our location from entity manager
    TEntityManager::GetInstance()->RegisterForEvent(TPlayer::OnEventData,
                                        (void *)this,
                                        EVENT_DATA_EVENT, mpOwnerEntity);

    // Register for sounds on certain events
    TSound *pSound = dynamic_cast<TSound *>(
        mpOwnerEntity->GetComponent(SOUND_COMPONENT));
    if (pSound == NULL) {
        printf("TPlayer Object with no pSound! ABORT ABORT!!\n");
    }

    pSound->RegisterSound("PlayerHit", COLLISION_EVENT,
                          "Bullet");
    pSound->RegisterSound("Armor", COLLISION_EVENT,
                          "Armor");
    pSound->RegisterSound("Weapon", COLLISION_EVENT,
                          "Weapon");
    pSound->RegisterSound("PlayerDead", DEATH_EVENT,
                          mpOwnerEntity->GetType());

}

The constructor takes the speed the player moves. The 2 main things the Player component does is gets input events, and, if it's a direction event, it gives a force to the entity's PhysicalObject. If there's a mouse movement, it gives an angle to the PhysicalObject. (Notice, it doesn't handle firing bullet, that's all done by Weaponry).
It also handles events from other people wanting to know where the player is.

Finally, it tells the Sound component to play certain sounds on certain Events.

Next time we'll finish off the Component System talk when I detail how we put it all together to make the SmashPC game.




That looks really promising!
This event system is part of a library or you are implementing it?
dejaime,

It's my own implementation. Check out My Component Based Entity System Part 1 the 2nd post of this blog. Specifically, check the TEvent.h and .cpp, and TEntity.cpp code, where I show how we handle RegisterForEvent(), and SetEvent().

As I mentioned earlier, I'm using strings as Event filters (after etEventType), which I know is not the most efficient, but, currently, I'm not seeing a performance hit, so I'm leaving it as is.

July 2014 »

S M T W T F S
  12345
6789101112
13141516171819
2021 22 23242526
2728293031  
PARTNERS