#Himalaya: A harmonic composition

No, this page is not turning into a music theory blog. Instead, I’m gonna tell you a little something about the newly introduced component system of the Himalaya game engine.

Remember the original design approach I posted when the framework was still very early in development?

GameElements

My original idea was to have an abstract class as a template for all entities in the game. An entity, such as the player character, would then simply derive from the GameEntity class and implement all the additional functionality that it needs. The “Actor” class was supposed to be a GameEntity that provides additional features for visual representation of the object on the screen. But as the Himalaya engine grew bigger, I realized that this design was good, but not necessarily ideal.

What are you made of?

I came to the conclusion that a component-based approach, similar to the one in the Unity engine, was a much nicer way to describe the functionality of a game entity. What do I mean by “component”? Well…an entity component is basically responsible for handling one specific part of an object in our game. They enable us to easily implement similar behavior in two entities, just by using the same components. An example: For our player character we could create a game entity with one component that handles user input, one that handles collisions, one that renders a sprite on the screen and one that animates said sprite.

Take a look at this chart for clarification:

HimalayaComponents

As you can (hopefully) see, a lot of the classes that I talked about in previous posts have been converted to entity components to conform to the new system. Of course this new design renders the aforementioned “Actor” class obsolete, since it would basically just be a GameEntity with a Sprite and a SpriteAnimator attached to it. Currently, I still keep the Actor class in the library, but I marked it as “obsolete”. It will be removed very soon, though.

Entity Components that need their logic updated each frame implement the IUpdate interface. The GameEntity the component belongs to then makes sure to actually call the update logic regularly. Similarly, components that contain render logic use the IDraw interface and have their draw method called by their entity at the appropriate time.

The Transform component is a special little snowflake, because it is used by every single entity and cannot be removed. I mean, every object needs to be able to be positioned at least, right? Also, some entity components allow only one instance of them to be attached to a game entity. That is the case for our special little friend Transform, but also applies to the CollisionController, the Sprite and the SpriteAnimator for example. With this system, we can easily pick from all the features we need and add them to a specific game entity.

youJustBlewMyMind.gif

How about some code?

Alright, let’s take a look at the EntityComponent class first:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yetibyte.Himalaya.GameElements;

namespace Yetibyte.Himalaya.GameElements {

    public abstract class EntityComponent {

        #region Fields

        protected bool _isActive = true;
        protected GameEntity _gameEntity;

        #endregion

        #region Properties

        public virtual bool AllowMultiple => false;
        public virtual bool IsRemovable => true;

        public GameEntity GameEntity {

            get => _gameEntity;

            set {

                GameEntity futureGameEntity = value;

                if (IsAttached)
                    _gameEntity.RemoveComponent(this);

                futureGameEntity?.AddComponent(this);

                _gameEntity = futureGameEntity;

            }

        }

        /// <summary>
        /// Whether or not this component has been attached to a <see cref="GameElements.GameEntity"/>.
        /// </summary>
        public bool IsAttached => _gameEntity != null;

        /// <summary>
        /// Determines whether or not this component is currently active. This also takes into account the active state of
        /// the <see cref="Yetibyte.Himalaya.GameElements.GameEntity"/> this component is attached to. If the GameEntity is not active, this will return false
        /// regardless of the local active state of this component. A component that is not attached to any GameEntity is always considered inactive.
        /// </summary>
        /// <seealso cref="IsActiveSelf"/>
        public bool IsActive {

            get => _gameEntity != null && _gameEntity.IsActive && this.IsActiveSelf;
            set => this.IsActiveSelf = value;

        }

        /// <summary>
        /// The local active state of this component. This ignores the active state of the <see cref="Yetibyte.Himalaya.GameElements.GameEntity"/> this component is attached to.
        /// Pleae note that, even if this is set to true, the component may still be considered inactive by the <see cref="Scene"/> because the GameEntity is not active or this
        /// component has not been attached to a GameEntity at all.
        /// </summary>
        /// /// <seealso cref="IsActive"/>
        public bool IsActiveSelf { get => _isActive; set => _isActive = value; }

        /// <summary>
        /// Determines the order in which <see cref="EntityComponent"/>s are processed. The processing order goes from
        /// high priority to low priority components. Note: This does not affect the draw order for drawable components.
        /// </summary>
        public int Priority { get; set; }

        #endregion

        #region Methods

        /// <summary>
        /// Sets the <see cref="Yetibyte.Himalaya.GameElements.GameEntity"/> this component is attached to without
        /// the overhead of recalculating relations. Only use this if you know what you're doing!
        /// </summary>
        /// <param name="gameEntity">The new GameEntity.</param>
        internal void SetGameEntityDirectly(GameEntity gameEntity) => _gameEntity = gameEntity;

        /// <summary>
        /// Called when this <see cref="EntityComponent"/> is attached to a <see cref="GameElements.GameEntity"/>.
        /// </summary>
        public virtual void OnAdded() {

        }

        /// <summary>
        /// Called when this <see cref="EntityComponent"/> is removed from a <see cref="GameElements.GameEntity"/>.
        /// </summary>
        /// <param name="gameEntity">The GameEntity this component was removed from.</param>
        public virtual void OnRemoved(GameEntity gameEntity) {

        }

        #endregion

    }
}

Good thing I (almost) always document my code. That saves me some explaining now, if it’s even necessary since this class is pretty short and straight forward and doesn’t do that much on its own. This is simply an abstract class for the different component types to derive from. Entity Components can be set to “inactive” to temporarily prevent them from being processed. The order in which components are updated can be determined via the Priority property. This is useful and even necessary in some cases. For example, it makes sense to first check for keyboard input with the ControlListener component and then after that process the input in a Behavior component.

Speaking of Behavior component. As I mentioned above, the logic and – well – behavior of a game entity is no longer intended to take place directly in a subclass of GameEntity. This is the job of the Behavior component. It has methods for initialization and updating that we can override to describe the behavior of an object such as the player character. It is where we implement all the logic that handles how an entity interacts with its environment.

Components can be added to or removed from a GameEntity with the following simple methods. I added some comments for explanation.

public void AddComponent(EntityComponent component) {

	/* If we passed null for some reason or a component that was already added
	 * to this GameEntity, return without adding anything. */
	if (component == null || HasComponent(component))
		return;

	// Get the type of the component we want to add.
	Type componentType = component.GetType();

	/* If the component does not allow multiple instances of it in one entity and there
	 * is already a component of the same type in this entity, return without adding the component. */
	if (!component.AllowMultiple && HasComponentOfType(componentType))
		return;

	// If the component is currently already attached to another entity, detach it.
	component.GameEntity?.RemoveComponent(component);

	// Add the component to this entity's collection of components.
	_components.Add(component);

	// Set the GameEntity of the component to this one.
	component.SetGameEntityDirectly(this);

	// Call the OnAdded method of the component we just added.
	component.OnAdded();

	// Fire the ComponentAdded event.
	OnRaiseComponentAdded(new ComponentEventArgs(component));

}

public void RemoveComponent(EntityComponent component) {

	/* If we passed null or the component is not attached to this entity
	 * or it is not removable, return. */
	if (component == null || !HasComponent(component) || !component.IsRemovable)
		return;

	// Remove the component from the collection of components in this entity.
	_components.Remove(component);

	// Set the entity of the component to null.
	component.SetGameEntityDirectly(null);

	// Call the OnRemoved method of the component we just removed.
	component.OnRemoved(this);

	// Fire the ComponentRemoved event.
	OnRaiseComponentRemoved(new ComponentEventArgs(component));

}

To retrieve components attached to a GameEntity, we can use one of the following methods:

/// <summary>
/// Returns a collection of all <see cref="EntityComponent"/>s attached to this <see cref="GameEntity"/> that are of or derive from the given Type.
/// </summary>
/// <typeparam name="T">The type to filter the components by.</typeparam>
/// <returns>A collection of all components attached to this entity that derive from the given type.</returns>
public IEnumerable<T> GetComponents<T>() where T : EntityComponent => _components.OfType<T>();

public IEnumerable<T> GetActiveComponents<T>() where T : EntityComponent => _components.OfType<T>().Where(c => c.IsActive);

/// <summary>
/// Returns a collection of all <see cref="EntityComponent"/>s attached to this <see cref="GameEntity"/>'s children that match the given Type or derive from it.
/// </summary>
/// <typeparam name="T">The Type to filter the components by.</typeparam>
/// <param name="includeSelf">Should the root <see cref="GameEntity"/>'s components be included in the collection?</param>
/// <param name="recurse">Should the components attached to grandchildren, great-grandchildren etc. also be included in the collection?</param>
/// <returns>A collection of all components that meet the specified conditions.</returns>
public IEnumerable<T> GetComponentsInChildren<T>(bool includeSelf, bool recurse) where T : EntityComponent {

	IEnumerable<T> ownComponents = includeSelf ? GetComponents<T>() : new T[0];

	if (_childEntities == null) // Just a safety precaution
		return ownComponents.Concat(new T[0]);

	if (!recurse)
		return ownComponents.Concat(_childEntities.SelectMany(e => e.GetComponents<T>()));

	return ownComponents.Concat(_childEntities.SelectMany(e => e.GetComponentsInChildren<T>(true, true)));

}

/// <summary>
/// Returns the first <see cref="EntityComponent"/> attached to this <see cref="GameEntity"/> that matches the given Type or derives from it.
/// </summary>
/// <typeparam name="T">The type of the component to look for.</typeparam>
/// <returns></returns>
public T GetComponent<T>() where T : EntityComponent => GetComponents<T>().FirstOrDefault();

What’s somewhat interesting here is the generic method GetComponentsInChildren that optionally recurses through the entire entity hierarchy and returns all the components of the desired type it can find. By now you should also be able to tell that I’m a big fan of LINQ. 😀

If we wanted to get the Sprite component of a game entity, we would simply do something like: “entity.GetComponent();”

If we know there are multiple components of the same type, let’s say Behavior, and we want to retrieve them all, we’d just go: “entity.GetComponents();”

We’re getting there…

The Himalaya engine is getting richer and richer in features. There’s still a lot to do, but I’m having a lot of fun developing this framework, even though it takes more time than I can afford to spend sometimes. 😀

There are a few more features I haven’t written about yet, but I’ll take care of that shortly. Next time we’ll focus on collision detection and response. I hope you’re looking forward to that.

And as always, let me remind you that the source code of the Himalaya engine can be found in my GitHub repository.

See you around!

Advertisements

#Himalaya: Modeling the basic game elements

Okay, so let’s discuss the plan. What does my game engine need? What game components are essential for building a very simple game? Well, in fact most games that need their game and render logic updated regularly share a similar base structure.

Luckily, MonoGame already does most of the low-level stuff for us and provides us with a Game class that has methods for content loading, updating game logic and rendering that are called at the appropriate time. But of course, we don’t want to put all of our game code into this class. That’d be very poor design and – needless to say – it would make our code quite unmanageable. So we want to structure our code and divide our game into reoccurring components, or “Game Elements” as I will be referring to them, since the term “Game Component” is already defined in MonoGame/XNA. As I said, this is handled similarly in most games. We create some sort of scene or game state class that is responsible for managing all of our game objects like the player, enemies, GUI elements, environmental stuff (like a tiled map), basically everything that makes up one particular part or “scene” of our game. Our scene could be a level, it could be a menu, it could be a loading screen… You get the idea. 😀

But before I start trying to draw a picture with words, here’s an actual picture to gaze your eyes upon. This is a (non-standard) UML diagram of what I (and many others before me) came up with.

wp-image-GameElemetsD

Click to enlarge. Created with NClass (http://nclass.sourceforge.net). It’s a cool and handy little tool. Go check it out! I’m serious, go! GO!

 

Of course this is just a first draft and the structure is most likely subject to change a bit. But let me tell you about what you’re seeing real quick.

Scene

As mentioned above, the scene contains all the game objects we currently need in our game and makes sure to update their logic and call their Draw method. We keep track of all game objects that currently live in our scene using a generic List. Also we have two more collections of type Queue. These store the game objects – or “Game Entities” as I refer to them – that are to be added to or removed from the Scene in this update interval. We need those collections because we cannot directly manipulate our List of Game Entities while we are iterating through them in our Update method. Therefore, we keep track of what Entities we want to dynamically add or remove and than do so after all existing entities have been processed.

Game Entity

A Game Entity is basically any object inside our Scene that needs to be updated. This abstract class can be used as a pattern for anything that brings some logic into our messy game world. The basic Game Entity is not intended to have a graphical representation on the screen but it can certainly implement some render logic if the developer (aka me) decides so.

Actor

The Actor class derives from the GameEntity class. The main difference between a simple Game Entity and what I refer to as an “Actor” is that an Actor has a Sprite that makes it visible on the screen. It can also optionally have a Sprite Animator which is used to, well, animate the sprite. More information on Sprites and Sprite Animators are to come… right now.

Sprite

Well, anyone who has ever had something to do with game development knows what a Sprite is. It is basically a certain part of a texture. I feel like explaining it is kind of unnecessary since it is more like a general term. If you really want to know more about sprites and texture atlases… Google is your friend. 😀

boe_tile_set

Here’s an example of a Sprite sheet to give you an idea if you are indeed clueless. Found on: https://de.wikipedia.org/wiki/Sprite_(Computergrafik)

This class is basically my simple implementation of a Sprite. It has a source rectangle which represents the texture coordinates of what part of the texture should be rendered. For reasons of convenience I also implemented the properties Index, Width and Height which are direct links to the source rectangle’s location and size.

I really wasn’t sure if I should also add properties for the Sprite’s position and scale. That way, I could only manipulate those values and used them when the Sprite is drawn to the screen. But eventually I decided against those since the Actor class that is the main user of the Sprite class already has such properties. And since I want the Sprite to sort of graphically represent the Actor, I decided that instead I wanted to pass the Actor’s position and scale to the Sprite’s Draw method. Maybe this will change in the future. I’m not entirely sure. We’ll see.

Sprite Animator and Sprite Animation

The Sprite Animator does exactly what it says. It animates the Sprite that is assigned to it. I. e. according to some predefined data set, it changes the texture coordinates (the index) of the Sprite at a certain interval. This data set can be found in the SpriteAnimation class. The Sprite Animator has methods for playing, pausing and stopping its animation. Originally, I implemented this behavior with a subclass of Sprite called “AnimatedSprite”. However, I quickly found that this was not a good design choice in my case. That is because the Actor class has a property of the type Sprite, remember? I wanted to leave it up to the developer to decide whether the actor should have a Sprite or an Animated Sprite. So far so good, Animated Sprite derives from Sprite, so it wouldn’t have been a problem to assign an instance of AnimatedSprite to the Sprite property of the Actor. The problem however would have been that every time I wanted to use the Sprite as an Animated Sprite, e. g. to update the animation or to play or pause it, I couldn’t have done so easily. Every Animated Sprite is a Sprite, but not every Sprite is an Animated Sprite. I couldn’t just “upcast” the Sprite to an Animated Sprite. So I figured, using an optional Sprite Animator was a better idea.

I created a custom extension for the MonoGame content pipeline that interprets a lua script and creates an instance of the Sprite Animation class from it (see my previous post). I will describe this in more detail in a future post, possibly including a video tutorial on how to create a content pipeline extension, because you wouldn’t believe how poorly documented this subject is. Tutorials about this are very hard to find. So I might possibly create one to fill this gap a bit.

Interfaces

I also use a few interfaces so far and there are most likely more to come. The ITimeScale interface provides a scaling value for all time based operations.  The Scene class implements this interface to provide a global time scaling value, that is passed to all of the Game Entities. I plan to use this to manipulate any calculations that rely on the time that elapsed between the current frame and the previous one (delta time). This way I can easily achieve effects like slow motion or game pause.

The Game Entity class and the Sprite Animator class also implement this interface. This is so that I also have some sort of “local” time scale. In certain cases I might want to slow some entities down while maintaining or increasing the speed of others. That’s what this is for.

There is not much to say about the IDraw and the IUpdate interface. They are used by all the objects that implement the Draw and the Update method the exact same way. I couldn’t name them IDrawable and IUpdatable (to conform to the convention) because, again, those terms are already used by XNA/MonoGame for interfaces with slightly different purposes.

Stick around

That’s it for now. I will be posting about some more details about the Himalaya Game Engine shortly. Remember: The source code of the project, including everything you just read about, can be found in my GitHub repository:

https://github.com/Yeti47/Yetibyte.Himalaya

See ya!