450 likes | 621 Views
CS 378: Computer Game Technology. Game Engine Architecture Spring 2012. What is a Game Engine?. Runtime system Low-level architecture 3-d system Physics system GUI system Sound system Networking system High-level architecture Game objects Attributes Behaviors Game mechanics
E N D
CS 378: Computer Game Technology Game Engine Architecture Spring 2012
What is a Game Engine? • Runtime system • Low-level architecture • 3-d system • Physics system • GUI system • Sound system • Networking system • High-level architecture • Game objects • Attributes • Behaviors • Game mechanics • World editor • Tool(s) for defining world chunks (e.g. levels) and static and dynamic game objects University of Texas at Austin CS 378 – Game Technology Don Fussell
Game Engine Subsystems • Runtime object model • Realtime object model updating • Messaging and event handling • Scripting • Level management and streaming • Objectives and game flow management University of Texas at Austin CS 378 – Game Technology Don Fussell
What are Game Objects? • Anything that has a representation in the game world • Characters, props, vehicles, missiles, cameras, trigger volumes, lights, etc. • Created/modified by world editor tools • Managed at runtime in the runtime engine • Need to present an object model to designers in the editor • Need to implement this object model at runtime efficiently University of Texas at Austin CS 378 – Game Technology Don Fussell
Runtime Object Model Architectures • Object-centric • Objects implemented as class instances • Object’s attributes and behaviors encapsulated within the class(es) • Game world is a collection of game object class instances • Property-centric • Object attributes are implemented as data tables, one per attribute • Game objects are just IDs of some kind • Properties of an object are distributed across the tables, keyed by the object’s id • Object behaviors implicitly defined by the collection of properties of the object • Properties may be implemented as hard-coded class instances • Like a relational database system in some ways University of Texas at Austin CS 378 – Game Technology Don Fussell
Object-centric Architectures • Natural taxonomy of game object types • Common, generic functionality at root • Specific game object types at the leaves GameObject MovableObject DrawableObject PacMan Ghost Pellet PowerPellet Hypothetical PacMan Class Hierarchy University of Texas at Austin CS 378 – Game Technology Don Fussell
Monolithic Class Hierarchies Actor • Very intuitive for small simple cases • Tend to grow ever wider and deeper • Virtually all classes in the game inherit from a common base class Light … Brush … Inventory Controller Ammunition AIController Powerups PlayerController … … Weapon Info HUD … GameInfo … Pickup Pawn Ammo Vehicle ArmorPickup UnrealPawn WeaponPickup RedeemerWarhead Part of object class hierarchy from Unreal Tournament 2004 … … Scout University of Texas at Austin CS 378 – Game Technology Don Fussell
Problems with Monolithic Hierarchies • Hard to understand, maintain, and modify classes • Need to understand a lot of parent classes • Hard to describe multidimensional taxonomies • What if you want to classify objects along more than one axis? • E.g. how would you include an amphibious vehicle in the class hierarchy below? Vehicle LandVehicle WaterVehicle Car Motorcycle Truck Yacht Sailboat Cruiser University of Texas at Austin CS 378 – Game Technology Don Fussell
Tempted to use Multiple Inheritance? • NOOOO!!!!! • There’s a reason languages like Java don’t have it • Derived classes often end up with multiple copies of base class members • Better to use composition or aggregation than inheritance • Mix-in classes (stand alone classes with no base class) are particularly useful here (even with multiple inheritance) Vehicle LandVehicle WaterVehicle AmphibiousVehicle University of Texas at Austin CS 378 – Game Technology Don Fussell
Mix-ins Perhaps? GameObject (transform, refcount) AnimatedMixin (animation controller) Drawable (renderable model) Trigger (volume) Simulated (rigid body model) Animated ? AnimatedWithPhysics University of Texas at Austin CS 378 – Game Technology Don Fussell
Observations • Not every set of relationships can be described in a directed acyclic graph • Class hierarchies are hard to change • Functionality drifts upwards • Specializations pay the memory cost of the functionality in siblings and cousins University of Texas at Austin CS 378 – Game Technology Don Fussell
Components vs. Inheritance GameObject • A simple generic GameObject specialized to add properties up to full blown physical simulation • What if (as in your current games) you want to use physical simulation on objects that don’t use skeletal animation? MovableObject DrawableObject CollisionObject AnimatedObject PhysicalObject University of Texas at Austin CS 378 – Game Technology Don Fussell
Components vs. Inheritance • One “hub” object that contains pointers to instances of various service class instances as needed. Transform MeshInstance GameObject AnimationController RigidBody University of Texas at Austin CS 378 – Game Technology Don Fussell
Component-based example class GameObject { protected: // My transform (position, rotation, scale) Transform m_transform; // Standard components MeshInstance* m_pMeshInst; AnimationController* m_pAnimController; RigidBody* mpRigidBody public: GameObject() { // Assume no components by default. Derived classes will override m_pMeshInst = NULL; m_pAnimController = NULL; m_pRigidBody = NULL; } ~GameObject() { // Automatically delete any components created by derived classes delete m_pMeshInst; delete m_pAnimController; delete m_pRigidBody; // … }; University of Texas at Austin CS 378 – Game Technology Don Fussell
Component-based example class Vehicle : public GameObject { protected: // Add some more components specific to vehicles Chassis* m_pChassis; Engine* m_pEngine; // … public: Vehicle() { // Construct standard GameObject components m_pMeshInst = new MeshInstance; m_pRigidBody = new RigidBody; m_pAnimController = new AnimationController(*m_pMeshInst); // Construct vehicle-specific components m_pChassis = new Chassis(*this, *m_pAnimController); m_pEngine = new Engine(*this); } ~Vehicle() { // Only need to destroy vehicle-specific components delete m_pChassis; delete m_pEngine; } }; University of Texas at Austin CS 378 – Game Technology Don Fussell
Example properties • “Hub” class owns its components (it manages their lifetimes, i.e. creates and destroys them) • How does it know which components to create? • In this simple case, the GameObject class has pointers to all possible components, initialized to NULL • Only creates needed components for a given derived class • Destructor cleans up all possible components for convenience • All optional add-on features for derived classes are in component classes University of Texas at Austin CS 378 – Game Technology Don Fussell
More flexible (and complex) alternative • Root GameObjectcontains a linked list of generic components • Derive specific components from the component base class • Allows arbitrary number of instances and types of components Component +GetType() +isType() +ReceiveEvent() +Update() GameObject Transform RigidBody AnimationController MeshInstance University of Texas at Austin CS 378 – Game Technology Don Fussell
Why not get rid of GameObject? • If a GameObject instance becomes just an empty container of pointers to components with an object ID, why not just get rid of the class entirely? • Create a component for a game object by giving the component class instance for that object the object’s unique ID. • Components logically grouped by an ID form a “game object” • Need fast component lookup by ID • Use factory classes to create components for each game object type • Or, preferably use a “data driven” model to read a text file that defines object types • How about inter-object communication? How do you send a message to an “object” and get the proper response? • Know a priori which component gets a given message • Multicast to all of the components of an object University of Texas at Austin CS 378 – Game Technology Don Fussell
Property-centric Architectures • Think in terms of properties (attributes) of objects rather than in terms of objects • For each property, build a table containing that property’s values keyed by object ID • Now you get something like a relational database • Each property is like a column in a database table whose primary key is the object ID • Where are the object’s behaviors defined? • Each type of property can be implemented as a property class • Do it with scripts, have one of an object’s properties by ScriptID • Scripts can also be the target of messages University of Texas at Austin CS 378 – Game Technology Don Fussell
Pros and cons • Pros • More memory-efficient • Only store properties in use, no unused data members in objects • Easier to construct in a data-driven way • Define new attributes with scripts, less recoding of class definitions • Can be more cache-friendly • Data tables loaded into contiguous locations in cache • Struct of arrays (rather than array of structs) principle • Cons • Hard to enforce relationships among properties • Harder to implement large-scale behaviors if they’re composed of scattered little pieces of fine-grained behavior • Harder to debug, can’t just put a game object into a watch window in the debugger and see what happens to it. University of Texas at Austin CS 378 – Game Technology Don Fussell
Component-Based Approach • Related to, but not the same as aspect-oriented programming • One class, a container for: • attributes (data) • behavior(logic) • Attributes := list of key-value pairs • Behavior:= object with OnUpdate() and OnMessage() University of Texas at Austin CS 378 – Game Technology Don Fussell
Components vs Hierarchies GameObject GameObject * * Prop Attribute<T> Behaviour University of Texas at Austin CS 378 – Game Technology Don Fussell
Hulk:Ultimate Destruction Object Model University of Texas at Austin CS 378 – Game Technology Don Fussell
Alex Helicopter Pedestrian(HLOD) Pedestrian(LLOD) PhysicsBehaviour TouchBehaviour CharacterIntentionBehaviour MotionTreeBehaviour CollisionActionBehaviour PuppetBehaviour CharacterMotionBehaviour MotionStateBehaviour RagdollBehaviour CharacterSolverBehaviour HealthBehaviour RenderBehaviour SensesInfoBehaviour HitReactionBehaviour GrabSelectionBehaviour GrabbableBehaviour TargetableBehaviour AudioEmitterBehaviour FightVariablesBehaviour ThreatReceiverBehaviour PhysicsBehaviour TouchBehaviour CharacterIntentionBehaviour MotionTreeBehaviour CollisionActionBehaviour PuppetBehaviour CharacterSolverBehaviour HealthBehaviour RenderBehaviour HitReactionBehaviour GrabbableBehaviour GrabBehavior TargetableBehaviour AudioEmitterBehaviour FightVariablesBehaviour EmotionalStateBehaviour ThreatReceiverBehaviour FEDisplayBehaviour PhysicsBehaviour CharacterIntentionBehaviour MotionTreeBehaviour PuppetBehaviour HealthBehaviour RenderBehaviour GrabbableBehaviour GrabBehaviour TargetableBehaviour AudioEmitterBehaviour EmotionalStateBehaviour FEDisplayBehaviour CharacterPedBehaviour SensesInfoBehaviour TargetableBehaviour PedBehaviour Prototype Game Objects University of Texas at Austin CS 378 – Game Technology Don Fussell
Data-Driven Creation Text or binary Loaded from pipeline Load and go Delayed instancing Dedicated tools Data-driven inheritance University of Texas at Austin CS 378 – Game Technology Don Fussell
Data-Driven Advantages • Endowing with new properties is easy • Creating new types of entities is easy • Behaviours are portable and reusable • Code that talks to game objects is type-agnostic • Everything is packaged and designed to talk to each other • In short: you can write generic code University of Texas at Austin CS 378 – Game Technology Don Fussell
Data-Driven Disadvantages • In short: you have to write generic code • Game objects are typeless and opaque • Can’t ask, e.g. if object has AttachableBehaviour then attach to it • Code has to treat all objects identically This is wrong! University of Texas at Austin CS 378 – Game Technology Don Fussell
Messaging AttachMessage msg(this); object->OnMessage(&msg); • Dispatched immediately to all interested behaviours (synchronous operation) • Fast, but not as fast as a function call • Use for irregular (unscheduled) processing • Collisions, state transitions, event handling • Can be used for returning values University of Texas at Austin CS 378 – Game Technology Don Fussell
Attribute Access • The game object must be notified if you modify an attribute • Constaccessor • Read-only access • Cacheable • Non-constaccessor • Permits writing • Not cacheable • Sends a notification message to the game object • Free access from object’s own behaviours University of Texas at Austin CS 378 – Game Technology Don Fussell
An attribute or not an attribute? • Attribute if • accessed by more than one behaviour, or • accessed by external code • Otherwise a private member of the behaviour • If not sure, make it an attribute University of Texas at Austin CS 378 – Game Technology Don Fussell
Game Object Update • GameObject::OnUpdate(pass, delta) for b in behaviours b.OnUpdate(pass, delta) • OnUpdate() and OnMessage() are the only two entry points to a behaviour. University of Texas at Austin CS 378 – Game Technology Don Fussell
Health BehaviorExample void HealthBehaviour::OnMessage(Message* m) { switch (m.type) { case APPLY_DAMAGE: Attribute<float>* healthAttr = GetAttribute(HEALTH_KEY); healthAttr->value -= m.damage; if (healthAttr->value < 0.f) mGameObject->SetLogicState(DEAD); break; case ATTR_UPDATED: if (m.key == HEALTH_KEY){ Attribute<float>* healthAttr = GetAttribute(HEALTH_KEY); if (healthAttr->value < 0.f) mGameObject->SetLogicState(DEAD); } break; } } University of Texas at Austin CS 378 – Game Technology Don Fussell
Components in Practice Behaviours and Attributes in [PROTOTYPE] University of Texas at Austin CS 378 – Game Technology Don Fussell
Adoption • Some coders were resistant: • Too complicated • Don’t know what’s going on • Too cumbersome • Calling a function is easier than sending a message • Reading a data member is easier than retrieving an attribute • Don’t like typeless objects • Ongoing education University of Texas at Austin CS 378 – Game Technology Don Fussell
Post-Mortem Survey University of Texas at Austin CS 378 – Game Technology Don Fussell
Post-Mortem Comments • Data-driven creation was the biggest win • Prototyping is the biggest win once you have a library of behaviors • Modularity of behaviorswas the biggest win • Data inheritance was the biggest win • Components are nothing new - no modern game could be built without them University of Texas at Austin CS 378 – Game Technology Don Fussell
Performance • GameObject::OnUpdate and OnMessage are easy targets • For the critic • For the optimiser • Existing optimisations: • Message masks • Update masks • Logic state masks • Time-slicing • Attribute caching • Leaving the back door open University of Texas at Austin CS 378 – Game Technology Don Fussell
Performance Lessons • Best optimizations are algorithmic: • Avoid unnecessary messages, e.g. object->OnMessage(&message1); if (message1.x) object->OnMessage(&message2); • Prefer attributes over messages • Avoid unnecessary updates • Better instrumentation • Legalize the back door entrance University of Texas at Austin CS 378 – Game Technology Don Fussell
Future Improvements • Stateless behaviours • Submit batches of objects to stateless behaviours • Better suited for parallel architectures • Message queuing University of Texas at Austin CS 378 – Game Technology Don Fussell
Prototype’s Data Types • 1544 game object definitions • 145 unique behaviours • 335 unique data types • 156 unique prop types alone
BehaviorUsage University of Texas at Austin CS 378 – Game Technology Don Fussell
Implicit “Class Hierarchy” University of Texas at Austin CS 378 – Game Technology Don Fussell
Implicit “Class Hierarchy” University of Texas at Austin CS 378 – Game Technology Don Fussell
Prop Hierarchy University of Texas at Austin CS 378 – Game Technology Don Fussell
Summary • Designs change • Class hierarchies don’t like change • Components do, but not without some sacrifices University of Texas at Austin CS 378 – Game Technology Don Fussell