{"id":322,"date":"2016-03-27T00:00:43","date_gmt":"2016-03-27T00:00:43","guid":{"rendered":"http:\/\/BryanWagstaff.com\/?p=322"},"modified":"2016-03-31T00:59:55","modified_gmt":"2016-03-31T00:59:55","slug":"what-goes-in-a-gameobject-class","status":"publish","type":"post","link":"https:\/\/bryanwagstaff.com\/index.php\/what-goes-in-a-gameobject-class\/","title":{"rendered":"What goes in a GameObject class"},"content":{"rendered":"<div class=\"entry\">\n<p>On gamedev.net recently there have been several questions about game objects. What are they? How do they work with the rest of the system? What belongs in the object?\u00a0When should they be created and destroyed? This week I&#8217;ll be addressing a few of these.<\/p>\n<p><!--more--><\/p>\n<h1>SOLID Programming<\/h1>\n<p>Let&#8217;s begin with a reminder of some good programming principles. A few key principles have a convenient acronym: <a href=\"https:\/\/en.wikipedia.org\/wiki\/SOLID_(object-oriented_design)\" target=\"_blank\">SOLID<\/a>. \u00a0Each of these principles has a strong interplay with the others. Following one will make it easier to follow the others, and failing to follow one makes it more difficult to follow the others.<\/p>\n<p>S = Single Responsibility Principle. SRP means a class should always have a single responsibility. \u00a0Having more than one responsibility makes it more confusing to use an object, and more difficult to build extensible systems. Give one primary task for each object. That one responsibility can be to act as a cache, or a loader, or to spawn items, or whatever else the thing needs to do. When applied to bigger modules the entire module should have a single responsibility; a module for 3D rendering, a module for physics, a module for audio, a module for serialization (loading and saving stuff), a module for running the simulation steps. For every thing, let it have only a single responsibility.<\/p>\n<p>O = Open\/Closed Principle. This one trips up a\u00a0many beginner programmers, and sadly many teachers and old reference books don&#8217;t follow the principle. OCP means code should be open for extension, this allows others to implement features in whatever way they want or need. Code should also be closed for modification, meaning you should not be able to modify the interfaces. \u00a0Object families have a single task that is well-defined, subclasses can implement that task as they need.<\/p>\n<p>L = Liskov Substitution Principle. The LSP basically means that your code should be written so objects are interchangeable. If you have any object that implements an interface, every object that has the interface should be interchangeable. \u00a0Users of an object family should be able to substitute freely. For example they should not care if the graphics card is an\u00a0Nvidia GeForce 700 series, and AMD Radeon 7000 series, or an Intel Broadwell integrated chip, all of them implement the Direct3D 12 interface. Substitute one for the other and the code will still work.<\/p>\n<p>I = Interface Segregation Principle. ISP means that interfaces for one set of tasks should be separate from other task interfaces. Closely related to the SRP, it applies to functionality. A set of interfaces for an event listener should only have tasks associated with listening to events. Game Objects have a high risk of becoming a &#8220;God Class&#8221;, a class with an enormous number of interfaces that can do everything; do your best to avoid it because it is a maintenance nightmare.\u00a0A set of interfaces for objects that can be used in an inventory should only have tasks associated with inventory use. A set of interfaces for items that broadcast sound should only have tasks associated with sound broadcasting. \u00a0It is possible for classes to implement multiple interfaces but still have a single responsibility.\u00a0A boombox stereo might\u00a0have interfaces to broadcast sound and interfaces to be placed in an inventory and interfaces to be broken, but still have the single responsibility of implementing the specialized behavior of the boombox object.<\/p>\n<p>D = Dependency Inversion Principle. Systems should depend on the abstractions rather than concrete implementations.\u00a0This follows closely from LSP and ISP. If it doesn&#8217;t matter what the individual types are, and the objects\u00a0have an interface that does what\u00a0is needed, the programmer should depend on the abstraction. I can depend on an abstract IDirect3DDevice abstraction without needing to know if internally the vendor has made a class for D3D12GeForce760GTX, or D3D12HD7970, or D3D12Iris6200.<\/p>\n<h1>SOLID for game objects<\/h1>\n<p>With that in mind, what does SOLID mean when it comes to game objects?<\/p>\n<p>The general purpose &#8220;GameObject&#8221; class in games had an evolution around the year 2000. In most systems I&#8217;ve observed and discussed over the past 15 years, the role of a game object is one of a container.<\/p>\n<p>The single responsibility is to contain all the details needed for other systems to do their jobs. There are a few options in achieving it. \u00a0The most direct is a container class that implements interfaces. The more flexible path is a container for other objects that implement those interfaces. The second is often called an &#8220;ECS&#8221; or &#8220;Entity-Component System&#8221;.<\/p>\n<p>You are probably already familiar with container classes. There are linked lists, dynamic arrays, hash maps, data dictionaries, and others that are quite commonly used.<\/p>\n<p>In the case of modern game engines, the GameObject containers contain &#8220;components&#8221; or &#8220;behaviors&#8221; or similarly-named objects.<\/p>\n<p>The most common component is the transformation, or the object&#8217;s position and orientation in 3D space. Because it is nearly universal\u00a0the transformation is often implemented as a mandatory element, a member variable rather than an item \u00a0linked to inside the container.<\/p>\n<p>There might also be a friendly object name used by programmers, designers, and others developing the game. The name has no relationship to what players see. Some engines don&#8217;t use name fields, others do.<\/p>\n<p>The GameObject next implements simple container operations, probably leveraging an existing structure for most of the work.\u00a0Depending on your object ownership model and lifetime requirements you may want to store different things.<\/p>\n<p>In C++, if your design has the GameObject as the owner of the object&#8217;s life, it may make sense to have the component&#8217;s lifetime completely controlled with a unique_ptr (<em>std::vector&lt;std::unique_ptr&lt;Component&gt; &gt;<\/em>). \u00a0If your design makes components that are always pulled from a place that is guaranteed to outlive any GameObject, you may store a direct pointer to the object (<em>std::vector&lt;Component *&gt;<\/em>). \u00a0If another system is controlling object lifetimes and you are using a more complex pattern of shared ownership, a\u00a0weak_ptr (<em>std::vector&lt;std::weak_ptr&lt;Component&gt; &gt;<\/em>) or\u00a0shared_ptr (<em>std::vector&lt;std::shared_ptr&lt;Component&gt; &gt;<\/em>) may be more appropriate.\u00a0In general shared ownership adds some serious complications, so avoid it if you can.<\/p>\n<p>As a container, you can search for components that match whatever you need.<\/p>\n<p>Finally, many systems will not allow you to directly create a GameObject. The type is often implemented as an abstract class with a hidden implementation class (perhaps called GameObjectPimpl), or there is a parallel interface-only\u00a0class (perhaps called IGameObject). You can use a factory\u00a0method to create the object which ensures the object gets created from the proper memory pools and returns a pointer to the abstract class.<\/p>\n<p>So for SOLID:<\/p>\n<p>S &#8211; Single responsibility principle, they are a container. Game objects don&#8217;t move themselves, load themselves, draw themselves, update themselves, or do anything beyond being a container.<br \/>\nO &#8211; Open\/Closed principle, you generally don&#8217;t need to modify a container. If you happen to need to do so, you aren&#8217;t creating a concrete instance but instead using a factory method to create it, so any private modifications on a subclass should be invisible to other developers.<br \/>\nL &#8211; Liskov Substitution principle, any instance is interchangeable with another, they are all containers together.<br \/>\nI &#8211; Interface Segregation principle, you don&#8217;t need to know if someone has specialized the container. It has a transformation, it has a name, and it has a collection of components.<br \/>\nD &#8211; Dependency Inversion principle. By\u00a0restricting access to direct creation, you are strongly encouraged to do the right thing, working only with the abstract base pointer rather than knowing the exact type of the GameObject or knowing the exact type of the components.<\/p>\n<h1>SOLID for Components<\/h1>\n<p>What does SOLID mean for components?<\/p>\n<p>Components these days do the bulk of the work.\u00a0They usually implement the mandatory functionality required by their Component base, but also usually implement multiple other Interfaces. \u00a0Just like the GameObject discussion above, the Component base class should be abstract so you can&#8217;t create one by itself. You will probably add a bunch of utility functionality to the base class, perhaps a way to find the GameObject it is attached to, perhaps a way to mark if the Component is active or set\/clear other flags.<\/p>\n<p>Let&#8217;s say you&#8217;re building a physics system.<\/p>\n<p>You are going to need a way to compare the objects so you might build a CollisionShape interface. It&#8217;s job is to enable comparisons by your physics engine. It might have abstract functions GetCollisionMesh(), GetPhysicsMaterial().<\/p>\n<p>You might build a CollisionListener interface. It&#8217;s job is to respond to\u00a0physics collisions. The interface does not need much, it handles events. You might have functions\u00a0HandleCollisionEnter(CollisionInfo*), HandleCollisionExit(CollisionInfo*),\u00a0HandleCollisionOverlap(CollisionInfo*), each implemented as virtual functions and passing information about the collision.<\/p>\n<p>With that, you&#8217;re able to put together a\u00a0component. We&#8217;ll call it a BoxCollider.<\/p>\n<p>The BoxCollider should derive from Component so you get whatever juicy implementation has been provided by the base class. It should derive from CollisionShape so the physics system knows how it collides. Also derive from ColliderListener so you can hear the events. \u00a0The physics collision mesh should be a simple box, this can be coded directly. The physics material is something individual objects may want to customize. Some materials will be bouncy and others absorb motion; some materials will have high friction and others will have low friction. For the collision handlers, these will also probably be set as function pointers or event handlers. When something creates a BoxCollider they can assign a function; when a function like HandleCollisionEnter() is called the object can forward the call on to whatever was entered as the response function.<\/p>\n<p>You could make more of these colliders. A SphereCollider is common. You&#8217;ll need a MeshCollider to work with complex shapes. Players are often implemented as capsules, so CapsuleCollider is probably on the list. All of them implement CollisionShape.<\/p>\n<p>Now that you&#8217;ve got components, something needs to use it. Somewhere else in the system, a GameObject is created and initialized, a BoxColleder is created an initialized, then added to the GameObject. Your physics system can test to see if any GameObject has a CollisionShape. \u00a0This example can be improved quite a bit by reducing the search space and caching\u00a0results, but for a small system it would work:<\/p>\n<pre>for( GameObject* go in World.ActiveObjects()) {\r\n  for( Component* c in go-&gt;GetActiveComponents()) {\r\n    if( CollisionShape* cs = dynamic_cast&lt;CollisionShape*&gt;(c) != NULL ) {\r\n      \/\/ Do something with cs. You can use GetCollisionMesh() and GetPhysicsMaterial()\r\n      \/\/ to figure out how the object collides with other collision objects.\r\n    }\r\n  }\r\n}<\/pre>\n<p>Going through SOLID again:<br \/>\nS &#8211; Single responsibility, the component only does one thing. It may be layered with multiple tasks, but it only has one responsibility. \u00a0It is not like the component\u00a0is drawing itself, moving itself, colliding itself, it only does one thing.<br \/>\nO &#8211; Open\/Closed, you can still specialize the behavior further but it strictly follows the interfaces that were given.<br \/>\nL &#8211; By following interfaces, anything using the components\u00a0don&#8217;t care what the concrete class is. They are all substituable. Any collision shape can be swapped out with any other collision shape.<br \/>\nI &#8211; Interfaces are clusters of tasks. A class may have more than one interface, but each interface has been segregated into task clusters.<br \/>\nD &#8211; Dependency inversion is met, we are only dealing with the abstract base interfaces rather than the concrete final types.<\/p>\n<h1>Example<\/h1>\n<p>At this point, an example of how these work together is in order.<\/p>\n<p>We&#8217;ll start by making a locomotion class. \u00a0We&#8217;ll call it MoveTurnIfWithinRange. \u00a0It will derive from Component and Locomotor. We&#8217;ll assume all Locomotor objects\u00a0are pushed forward based on their current speed by the physics system.<\/p>\n<p>We&#8217;ll add a few data members to the MoveTurnIfWithinRange.<\/p>\n<ul>\n<li>target. This points to another game object we should be comparing against.<\/li>\n<li>rangeMin, rangeMax. If the target is within this range, we do the motion.<\/li>\n<li>turnSpeedMin, turnSpeedMax. What are the fastest speeds we can turn. Pick a scale like radians per second.<\/li>\n<li>turnSpeedDelta. How fast we can change the turning speed.<\/li>\n<li>thrustSpeedMin, thrustSpeedMax. How fast we can move. Probably in meters per second.<\/li>\n<li>thrustSpeedDelta. How fast we can change the thrust speed.<\/li>\n<li>turnSpeedCurrent, thrustSpeedCurrent. Where we are now.<\/li>\n<\/ul>\n<p>During updates, the code will need to test the target to see if it is within the acceptable range. If so, it will attempt to apply a turn toward the object, and attempt to add to the speed until it gets to the maximum speed. If outside the range, it will reduce the turning speed and thrust speed until they get to the minimum.<\/p>\n<p>Now let&#8217;s create a component called LaunchProjectileIfWithinRange.<\/p>\n<p>It will have some data members as well.<\/p>\n<ul>\n<li>target. This points to another game object we should be comparing against.<\/li>\n<li>rangeMin, rangeMax. If the target is within this range, we shoot.<\/li>\n<li>projectile. Points to another game object that we are shooting.<\/li>\n<li>shotDelay. Delay between shooting projectiles.<\/li>\n<\/ul>\n<p>If the target is within the range, even if we are not pointed at the target, start shooting. If it is too close or too distant, stop shooting. When shooting, create a new projectile object based on the template, add it to the world, then sit idle for a few moments.<\/p>\n<p>We just created TWO components.<\/p>\n<p>Projectile is a game object with several components. The components will probably include a graphics mesh, a collision object, and its own locomotor.<\/p>\n<h2>Now for the data in our example.<\/h2>\n<p>Two components. Let&#8217;s see what we can make.<\/p>\n<p>Let&#8217;s create a game object called &#8220;Arrows&#8221;. Give it a mesh of some arrows, a collision object of a small capsule, and a straight locomotor. On collision it does some damage.<\/p>\n<p>Let&#8217;s create a game object called &#8220;Cannonball&#8221;. Give it a mesh of a small ball, a collision object of a ball, and a straight locomotor moving quickly. On collision it does big damage.<\/p>\n<p>Let&#8217;s create a game object called &#8220;Fireball&#8221;. Don&#8217;t give this one a mesh, give it a fancy particle system component that makes a fireball and smoke trail. Give it a collision object of a ball. On collision it does small damage and creates fire. These fireballs are smart, so instead of a straight forward locomotor, give them a\u00a0MoveTurnIfWithinRange locomotor. Since this object will be cloned, give a targeting range for the fireball to see the target\u00a0(e.g. 0\u00a0to\u00a020), a slow max turning rate (e.g. 0 to pi\/4 radians per second), a fixed speed range (40 to 40).<\/p>\n<p>FINALLY we can build the fun items.<\/p>\n<p>Let&#8217;s create a game object called ArcherTurret. Add a\u00a0MoveTurnIfWithinRange component. Every update it searches for a new Target, and as long as the target is in range it stays targeting that one. Since the turret just sits there, thrustSpeed has a no speed (0 to 0). The archers in the turret can turn quickly, so\u00a0turn rate (0 to pi) that can turn a half circle per second\u00a0(pi). Add a\u00a0LaunchProjectileIfWithinRange component. \u00a0Give it a range for when to start shooting, point the projectile to the Arrows object, and give it a shot of fire, maybe 2\u00a0shots per second.<\/p>\n<p>Let&#8217;s create a game object called CannonTurret. Same as above,\u00a0MoveTurnIfWithinRange that has no movement, a slow turn speed. A\u00a0LaunchProjectileIfWithinRange component that shoots cannon balls and a slow rate of fire.<\/p>\n<p>Again, MageTurret. Stationary but turns, launches fireballs.<\/p>\n<p>We can also do automated turrets that are constantly firing in a circle. Use the\u00a0MoveTurnIfWithinRange as above, but set the maximum range to infinity (or whatever high number represents infinity in your world) so it is always turning. Then set the turning speed to a fixed range, perhaps pi\/2 so it turns a\u00a0quarter circle per second at a fixed rate.<\/p>\n<p>You can make turrets that never move and never turn, only pointing forward and firing when someone gets in range.<\/p>\n<p>We can do more than turrets.<\/p>\n<p>Let&#8217;s make an object called FollowTank. Give it a\u00a0MoveTurnIfWithinRange component setting speed and turn rates\u00a0appropriate for a tank.<\/p>\n<p>Like the fireballs, you can make objects that move and turn, like a guided missile (or red shell). No turn but a bit of acceleration gives a dumbfire missile (or green shell).<\/p>\n<p>You make projectiles that also shoot projectiles.<\/p>\n<h1>Summing up<\/h1>\n<p>In modern games, a GameObject class is a container object. It holds components, and that&#8217;s it. Components have small, well-defined pieces of behavior. Both can be implemented with good programming practices that keep implementation easy. Other software\u00a0patterns, such as data-driven development patterns, can still be followed with careful thought.<\/p>\n<p>With only two simple Component classes we can leverage the power of game objects as containers to create an enormous number of projectile-shooting, potentially self-aiming,\u00a0potentially moving objects.<\/p>\n<p>Game designers tend to love component based architectures. A small number of well-designed components can be leveraged into seemingly emergent behaviors and thought-provoking complex\u00a0worlds using only a few\u00a0simple rules.<\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>On gamedev.net recently there have been several questions about game objects. What are they? How do they work with the rest of the system? What belongs in the object?\u00a0When should they be created and destroyed? This week I&#8217;ll be addressing a few of these.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[8,5,4],"tags":[],"class_list":{"0":"post-322","1":"post","2":"type-post","3":"status-publish","4":"format-standard","6":"category-gdnet","7":"category-games","8":"category-programming","9":"anons"},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/bryanwagstaff.com\/index.php\/wp-json\/wp\/v2\/posts\/322","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bryanwagstaff.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/bryanwagstaff.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/bryanwagstaff.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/bryanwagstaff.com\/index.php\/wp-json\/wp\/v2\/comments?post=322"}],"version-history":[{"count":3,"href":"https:\/\/bryanwagstaff.com\/index.php\/wp-json\/wp\/v2\/posts\/322\/revisions"}],"predecessor-version":[{"id":329,"href":"https:\/\/bryanwagstaff.com\/index.php\/wp-json\/wp\/v2\/posts\/322\/revisions\/329"}],"wp:attachment":[{"href":"https:\/\/bryanwagstaff.com\/index.php\/wp-json\/wp\/v2\/media?parent=322"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/bryanwagstaff.com\/index.php\/wp-json\/wp\/v2\/categories?post=322"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/bryanwagstaff.com\/index.php\/wp-json\/wp\/v2\/tags?post=322"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}