Style & Design Principles 03 - Component-Based Entity Systems

Post on 19-May-2015

3.291 views 3 download

Tags:

description

Chapter 03 of the lecture Style & Design Principles taught at SAE Institute Hamburg. Drawbacks of inheritance-based game models and introduction to aggregation-based game models.

Transcript of Style & Design Principles 03 - Component-Based Entity Systems

Style & Design PrinciplesChapter 03: Component-Based Entity Systems

Nick Prühs

5 Minute Review Session

• What’s the difference between inheritance and aggregation?

• Explain the three types of polymorphism!

• What’s the difference between cohesion and coupling?

• What are software design patterns?

• Explain three types of software design patterns, and name an example for each one!

2 / 58

Assignment Solution #2

DEMO

3 / 58

Objectives

• To understand the disadvantages of inheritance-based game models

• To learn how to build an aggregation-based gamemodels

• To understand the advantages and disadvantages of aggregation-based game models

4 / 58

“Say you’re an engineer…

… set out to create a new Game Object System from scratch, and you’re going to ‘do it right the first time’. Youtalk to your designer and say ‘What kind of content are we going to have in this game?’

They respond with ‘Oh lots of stuff, trees, and birds, and bushes, and keys and locks and … <trailing off>’

And your eyes glaze over as you start thinking of fancy C++ ways to solve the problem.

The object oriented programming sages tell you to try to determine Is-A relationships and abstract functionalityand all that other fun stuff. You go to the book store and buy a C++ book just to be sure, and it tells you to fireup your $5000 UML editor. [...]”

- Scott Bilas

5 / 58

Entities

6 / 57

Entities

7 / 57

Entities

8 / 57

Entities

9 / 57

Entities

10 / 57

Entities

11 / 57

Entities

• Object in your game world

• Can (or cannot)…• be visible

• move around

• attack

• explode

• be targeted

• become selected

• follow a path

• Common across all genres

12 / 58

Entities

13 / 58

Approach #1: Inheritance

14 / 57

Approach #1: Inheritance

• Entity base class

• That class and its subclasses encapsulate the main game logic

15 / 58

Example #1: Unreal Engine 3

• Base class Actor• Rendering

• Animation

• Sound

• Physics

• Almost everything in Unreal is an Actor• Pawn extends by taking damage

• Projectile extends by spawning impact effects

16 / 58

Drawbacks ofinheritance-based game models• Diamond of Death

17 / 58

Drawbacks ofinheritance-based game models

• Code added to the root of the inheritance tree causes big overhead

• Code added to the leafs of the tree tends to get copied

• Root and leaf classes tend to get very big

18 / 58

Where is Waldo?

public override void Update(float dt)

{

this.SystemManager.Update(dt);

this.EventManager.ProcessEvents(dt);

}

19 / 58

Where is Waldo?

public override void Update(float dt)

{

this.SystemManager.Update(dt);

this.EventManager.ProcessEvents(dt);

}

20 / 58

Where is Waldo?

public override void Update(float dt)

{

base.Update(dt);

this.SystemManager.Update(dt);

this.EventManager.ProcessEvents(dt);

}

21 / 58

Drawbacks ofinheritance-based game models

• Always need to understand all base classes along the inheritance tree

• Impossible to enforce calling base class functions• Someone will forget it. Trust me.

• And you’re gonna spend your whole evening finding that one missing base.Update().

• Deep class hierarchies will more likely run into call order issues

22 / 58

Inheritance-based gamemodels are…

• … difficult to develop

• … difficult to maintain

• … difficult to extend

23 / 58

“There are probablyhundreds of ways…

… you could decompose your systems and come up with a set ofclasses […], and eventually, all of them are wrong. This isn’t to saythat they won’t work, but games are constantly changing,constantly invalidating your carefully planned designs. [...]

So you hand off your new Game Object System and go work onother things.

Then one day your designer says that they want a new type of“alien” asteroid that acts just like a heat seeking missile, except it’sstill an asteroid.”

- Scott Bilas

24 / 58

“alien” asteroid

25 / 57

Approach #2: Aggregation

26 / 57

Approach #2: Aggregation

27 / 57

Approach #2: Aggregation

• Popular since Gas Powered Games’ Dungeon Siege

• Introduced long before

• Entities are aggregations of components• Which in turn encapsulate independent functionality

• Corresponds to recommendations by the Gang of Four• “favor object composition over class inheritance”

• Similar approach is used by the Unity3D game engine• Just for clarification: Unreal uses components as well, called

ActorComponent• Got much more prominent in latest UDK release

28 / 58

Approach #2a

• Create an Entity class

• Add references to all available components

• Has obvious disadvantages:• Many component references will be null pointers for

most entities

• Big unnecessary memory overhead

• Entity class has to be updated each time a new component is introduced

29 / 58

Approach #2b

• Create an Entity class

• Introduce a common base class for components

• Entities hold a collection of Component objects• Reduced the memory overhead

• Increased extensibility

• Already gets close to an optimal solution• easy to build, maintain and debug

• easy to implement new design ideas without breaking existing code

30 / 58

However, we can do better.

31 / 58

Approach #2c: Entity Systems

32 / 57

Approach #2c: Entity Systems

33 / 58

Approach #2c: Entity Systems

• Game entities are nothing more than just an id

• Thus, no data or methods on entities

• No methods on components, either: all functionality goes into what is called a system• PhysicsSystem

• HealthSystem

• FightSystem

• Entirely operate on their corresponding components

34 / 58

“All the data goes into the Components.

All of it. Think you can take some “really common”data, e. g. the x-/y-/z-coordinates of the in-gameobject, and put it into the Entity itself? Nope. Don’tgo there. As soon as you start migrating data into theEntity, you’ve lost. By definition the only valid placefor the data is inside the Component.”

- Adam Martin

35 / 58

Example #2: Simple Fight

36 / 58

Example #2: Simple Fight

37 / 58

Example #2: Simple Fight

38 / 58

Example #2: Simple Fight

39 / 58

Example #2: Simple Fight

40 / 58

Example #2: Simple Fight

41 / 58

Example #2: Simple Fight

42 / 58

Example #2: Simple Fight

43 / 58

Example #2: Simple Fight

44 / 58

Example #2: Simple Fight

45 / 58

Inter-System Communication

Systems communicate by the means of events, only.

• No coupling between systems• Easy to add or remove systems at any time

• Great architectural advantage for general gamefeatures• Need multiplayer? Just send the events over the network!• Need AI? Just make it create events which are handled just

like player input is!• Need replays? Just write all events with timestamps to a file!

46 / 58

Inter-System Communication

47 / 57

Entity Systems –Implementation

DEMO

48 / 58

Advantages of Entity Systems

• Update order is obvious

• Components can easily be pooled and re-used

• Independent systems can be updated by separate threads

• Data can easily be serialized and stored in a database

49 / 58

Disadvantages ofEntity Systems (?)• Lookups cause performance hit

• Resist the urge to add cross-component references – this would make you lose all of the advantages mentioned before

• Just don’t flood your system with unnecessary component types – just as you would always do

• Misbelief that it takes longer to “get the job done”• Used at the InnoGames Game Jam #3 for creating a

multi-platform multi-player real-time tactics game in just 48 hours – spending the little extra effort at the beginning pays off• Always.

50 / 58

Future Prospects

• Attribute Tables• store arbitrary key-value-pairs

• used for initializing all components of an entity

51 / 57

<AttributeTable>

<Attribute keyType="System.String" valueType="System.Single">

<Key>EnemyHealthModificationComponent.EnemyHealthModifier</Key>

<Value>-3</Value>

</Attribute>

<Attribute keyType="System.String" valueType="System.String">

<Key>ActionComponent.Name</Key>

<Value>Take that!</Value>

</Attribute>

</AttributeTable>

Future Prospects

• Blueprints• consist of a list of components and an attribute table• created with some kind of editor tool by designers• used for creating entites at run-time

52 / 57

<Blueprint><ComponentTypes>

<ComponentType>FreudBot.Logic.Components.ActionComponent</ComponentType> <ComponentType>FreudBot.Logic.Components.EnemyHealthModificationComponent</ComponentType>

</ComponentTypes>

<AttributeTable>

<Attribute keyType="System.String" valueType="System.Single">

<Key>EnemyHealthModificationComponent.EnemyHealthModifier</Key>

<Value>-3</Value>

</Attribute>

<Attribute keyType="System.String" valueType="System.String">

<Key>ActionComponent.Name</Key>

<Value>Take that!</Value>

</Attribute>

</AttributeTable>

</Blueprint>

Future Prospects

53 / 57

StarCraft II Galaxy Editor

Future Prospects

54 / 57

StarCraft II Galaxy Editor

Future Prospects

• Hierarchical Attribute Tables• used for overloading blueprints with specific entity attribute

values• e.g. reduced initial health

55 / 57

Future Prospects

56 / 57

StarCraft II Galaxy Editor

Future Prospects

public int CreateEntity(Blueprint blueprint, IAttributeTable configuration){

int entityId = this.CreateEntity();

// Setup attribute table.HierarchicalAttributeTable attributeTable = new HierarchicalAttributeTable();attributeTable.AddParent(blueprint.GetAttributeTable());attributeTable.AddParent(configuration);

// Add components.foreach (Type componentType in blueprint.GetAllComponentTypes()){

// Create component.IEntityComponent component = (IEntityComponent)Activator.CreateInstance(componentType);

// Add component to entity. this.AddComponent(entityId, component);

// Initialize component with the attribute table data.component.InitComponent(attributeTable);

}

// Raise event.this.game.EventManager.QueueEvent(FrameworkEventType.EntityInitialized, entityId);

return entityId;}

57 / 57

Takeaway

• inheritance-based game models show a lot of disadvantages

• entity systems are easy to maintain and debug• provide great extensibility without the necessity of

modifying existing code

• show better performance characteristics for both memory and CPU load

• easy to implement commonly used features• scripting

• serialization

• logging

58 / 57

References

• Mick West. Evolve Your Hierarchy. http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/, January 5, 2007.

• Levi Baker. Entity Systems Part 1: Entity and EntityManager.http://blog.chronoclast.com/2010/12/entity-systems-part-1-entity-and.html, December 24, 2010.

• Kyle Wilson. Game Object Structure: Inheritance vs. Aggregation.http://gamearchitect.net/Articles/GameObjects1.html, July 3, 2002.

• Adam Martin. Entity Systems are the future of MMOG development – Part 1. http://t-machine.org/index.php/2007/09/03/entity-systems-are-the-future-of-mmog-development-part-1/, September 3, 2007.

• Adam Martin. Entity Systems: what makes good Components? good Entities? http://t-machine.org/index.php/2012/03/16/entity-systems-what-makes-good-components-good-entities/, March 16, 2012.

• Scott Bilas. A Data-Driven Game Object System.http://scottbilas.com/files/2002/gdc_san_jose/game_objects_slides_with_notes.pdf, Slides, GDC 2002.

• Scott Bilas. A Data-Driven Game Object System.http://scottbilas.com/files/2002/gdc_san_jose/game_objects_paper.pdf, Paper, GDC 2002.

• Insomniac Games. A Dynamic Component Architecture for High Performance Gameplay.http://www.insomniacgames.com/a-dynamic-component-architecture-for-high-performance-gameplay/, June 1, 2010.

59 / 57

Thank you for your attention!

Contact

Mail

dev@npruehs.de

Blog

http://www.npruehs.de

Twitter

@npruehs

Github

https://github.com/npruehs

60 / 58