Friday, 20 November 2015

Low-Level Programming_Post9

Low-Level Programming: Post 9 19/11/2015

November 19th 2015 is the date of the ninth lesson on Low-Level Programming.

As per usual, at the start of the lecture, we were shown some bullet points on what we were going to learn today. Below are the all the points from the lesson...

  • Design Patterns: Design Patterns continued, round up of previous lesson.
  • Creational Patterns: The Factory and Singleton Patterns.
  • Sequencing Patterns: Facade, Game Loop and Update Patterns.
  • Object Pooling: Object Pooling, Implementations, Advantages and Disadvantages.
Unlike in most previous lessons, I am going to do a recap of Design Patterns from last week. This is due to the Design Patterns and the newer patterns mentioned above being linked together. Before we went into any detail on the Design Pattern, we were shown/told of a book that could help us in the module. The book was called 'Game Programming Patterns' by Robert Nystrom and published by Genever Benning. It covers all of what we were going to learn in the lesson on patterns and there was also an online version of the book.

Design Patterns (Recap)
  • Tool: Design Patterns are a powerful tool for software development, but they are not prescriptive specifications.
  • Concepts: They prevent us conceptual ways of modelling behaviour that we might want inside our software.
  • Misuse: Incorrectly using design patterns for a given situation will over-complicate your code and make it more difficult to maintain.
  • OOP: Object Oriented Design collates a collection of concepts and references them under a single paradigm
  • Appropriate Usage: Apply patterns appropriately, don't attempt to find a problem that requires a patterned solution.
  • Gang Of Four: The Gang Of Four have set out a series of patterns, which most modern day ones are based on, but their prose can be inaccessible.
Singleton Pattern: Ensure a class has only one instance, and provide a global point of access to it.
  • Single Instance: The first point to note is that a singleton is designed to enforce only a single instance of an object.
  • Global Access: The second is that using a singleton requires a global point of access. This in turn means the object itself is global and global is bad.
  • Consideration: The following three criteria;
  1. Ownership of the instance is unknown.
  2. Lazy initialisation is desirable.
  3. Global Access is not provided elsewhere.
  • Static: Singletons make use of the static keyword and manage their own instance to make sure it's only constructed once.
  • Overuse: The singleton's pattern is one of the most disliked because it breaks rules regarding global variables.
  • Laziness: There are very few occasions when passing the object around the game world is not possible, making it global is lazy.
Implementation
  1. Define a static attribute 'instance'.
  2. Define a static get function.
  3. Lazy initialise the object i.e. on first usage.
  4. Define constructors/destructors as private.
  5. Access is controlled via the get function.
  • Instance: Lazy initialisation means the object/data in the class is only created when needed. Ironically, we may want to control when.
  • Runtime: It's created at runtime, where a static class could be used instead and they aren't dependent on runtime scenarios.
  • Static Initialisation: The compiler initialises static variables before the program runs, which means we can't guarantee the order they've initialised.
  • Subclass: You can subclass a singleton object. This helps with cross-platform implementation, where the interface can be platform agnostic.
  • Patterns: Patterns such as Abstract Factory, Builder and Prototype often use the singleton pattern. So do state machines.
  • Single Instance: Singletons are overused, they should only be used when we only need a single instance that has global access.
Single Pattern (Bad)
  • Globals: Global variables are bad. They make it harder to reason code as well as encourage higher levels of coupling. Then there's threads.
  • Two Problems Solved: It solves two problems (not one).
  1. The Single Only Instance.
  2. The Global Access.
  • Lazy Initialisation: Whilst one of it's greatest advantages, using singletons restrict how and when we control allocations. This could lead to poor performances. 
  • Classes: Often developers can get carried away with the creation of manager classes, are they really needed? Could it not reside in the class?
  • Limit Classes: To limit a class to a single instance we can use a static bool to determine if the class has already been initialised.
Singleton Pattern
  • Static Class: As mentioned, a static boolean sits on the class. The first time it's accessed and constructed, the boolean is set to true.
  • Access: With this implementation, it's important to note that you will need to keep a variable or pointer to the one instantiated class object so you can utilise it throughout the codebase.
  • Parameters: Well designed software will allow us to flow data and objects between functions and classes, we should look to pass it in, rather than access it globally.
After looking through some of the lesson slides, we were then given an unexpected practical session. For this task, we had to design the DungeonDeath's game level layout. This included 10 bottom floors and 5 top floors. We also had to design various enemies and a boss enemy in the game, with them having different variables/values (health, damage etc). We also had to design where to place them in the game. I decided that out of the 5 enemies (including the boss) in the floor(s), three of them would be optional fights, but if the player defeats them, they get an item(s) to help fight against the boss.

Factory Pattern: Define an interface for creating an object, but let subclasses decide which class to instantiate
  • Factory: A factory relates to a class or a function whom's job it is to create objects of a derived class, often returning a reference to the base.
  • Instantiation: Factory method allows the base class to define all common and basic behaviours i.e. it's interface and delegates creation to subclasses.
  • Runtime Support: Factory methods are useful when it's not known what objects are required. Potentially we load the objects from a file and use an ID to create the correct subclass.
  • Allocation: Our factory's method can use special allocators during construction as well as taking ownership of the object.
  • Storage: A factory class can also manage the objects internally, storing them in a container and returning a reference to the new objects.
  • Game Objects: Implementing the previous factory requires the addition of a new type and a new switch statement for each new class added.
  • Factory: It's possible to edit the factory, so that a lookup value can be used to determine the object to be created. After which, for new classes we just need to register it in the factory.
  • Inheritance: Factory implementations are used with inheritance, unlike prototyping (another design pattern).
  • Sub-Classing: Prototyping does not require sub-classing but factories do, conversely they don't use initialise functions.
  • Approaches: There are multiple other approaches. We can use abstract factories or even generic programming to reduce the verbosity of types.
  • Return Type: The factory method is capable of returning the same instance more than once, or in this case, a subclass rather than the exact return type.
Facade Pattern: A facade is an object that provides a simplified interface to a larger body of code
  • Simplification: The facade pattern is designed to simplify interactions with complex parts of the codebase.
  • Understanding: It is often true that in order for us to accomplish our goal, we don't need to understand what's happening in great depth i.e. system("cls").
  • Implementation: The facade creates a single-class controller that hides the implementation details of the underlying code.
  • Libraries: Libraries are a prime example of a facade. They provide complex functionality through a clearly defined interface.
  • Duplication: If the same code is being duplicated, or the same behaviour, then combining then into a controller class is sensible i.e. a facade.
  • Layers: Remember the layers in an engine, with the platform layer handling all the platform specific calls, through a single API call.
  • When: 
  1. A simple interface is required to access a complex system.
  2. The abstractions and implementations of a subsystem are tightly coupled.
  3. A system is very complex or difficult to understand.
  • Interaction: The facade abstracts packages 1,2,3 from the rest of the application and the clients use the facade class to interact with these resources.
Game Loops: Decouple the progression of game time from user input and processor speed
  • Loops: Games require feedback loops. If the user inputs an action, we expect a reaction. In order to do this, a loop is created.
  • Modern Day: Even after all these years, games and applications often utilise the humble loop to pool for user input and then react to it.
  • Constant Updates: With games, there is a desire to keep updating and rendering whilst we await user input. The game shouldn't pause but continue to process in the mean time.
  • Input: Game loops fundamentally (threading aside) always check for user input every tick before processing all the game logic.
  • Speed: Our loop is designed to continuously run and not block, therefore our game world is alive and evolves every update or 'tick'.
  • FPS: How quickly or how often the update loop is run can be described, somewhat crudely as the measurement of frames per second.
  • Responsiveness: The FPS controls how smoothly the game input processes input and how quickly it reflects changes on the screen.
  • Hardware/Software: The speed of our loop is a combination of hardware and software. The faster the hardware, the quicker it can process data.
  • Traditional Usage: When working with known hardware configurations, it was easier for the developers to know how long the loop was.
  • Modern Day Loops: These days, it's up to the developer to control the ticks or updates and make sure the game responds accordingly, regardless of hardware.
  • Core: Game Loops are core to all games development. Even if we have an event based system, there's still a loop processing in the background.
  • Fixed Time Steps: Even though we've now slowed the processing time of our game loop, we have a problem when the target FPS isn't met.
  • Performance: Slow down will negatively effect the game's experience, so there's now a requirement to handle updates passes on time passed.
  • The Problem:
  1. Each update advances game time by X.
  2. The time taken to process the update (If two steps take longer than one step etc).
  • A New Problem?: Now, we know the game will run smoothly and advance using the calculated time-step, unfortunately, if two machines have a differing number of updates, we have an issue.
  • Render Async: It is possible to use a fixed time-step for the update game loop, but allow rendering to happen independently of updates.
  • Frame Delta: Conceptually, the frame delta is tracked and added to a counter, when the counter reaches our desired MS, we update the game world.
  • Rendering: If the rendering takes longer than our desired update time, we run the update multiple times until we've caught up on the lag.
  • Rendering Updates: It's possible to render between updates, which can cause judder. We can use interpolation in the render process.
  • Interpolation: The amount interpolated shows how far between two frames the object should be moved. If there's no lag, we need no interpolation.
Update Pattern: Simulate a collection of independent object by telling each to process one frame of behaviour at a time
  • Updating the Game World: Quite frankly, it's unlikely that the game won't have living breathing objects in it. For each object, we need to update or animate it.
  • The Game Loop: The game loop seems like a sensible place to process the game objects that need updating. This way, they update every tick.
  • Maintainability: Very quickly, the loop becomes bloated and difficult to maintain. Sure, a function could still be written for each type of object update.
  • Pattern: The update pattern is simply a layer of abstraction. Instead of processing updates of objects in the loop, we delegate this to the objects.
  • Succinct Loop: Allows us to keep the game loop succinct and much easier to manage, regardless of the number of objects we add.
  • Living Worlds: Not every game entity or world requires a real-time update function. Think of turn-based games, they react to a players move.
  • Ordering: Most games and their entities are often interdependent on each other i.e. with this in mind, the order they are updated in has consequences.
  • A before B: A will see B's current state, but B will see A's newly updated state. There's a disconnect here that needs to be acknowledged.
  • Updating Lists: If there are changes made to the game entities listed in the container, make sure not to miss any or delete needed ones.
  • Inheritance: In modern day development, massive levels of inheritance are shunned away from. Be careful to consider this when using update.
  • Composition: If we prefer composition over inheritance, we can reduce the level of derived classes and create update functionality on the classes' parts.
  • Dormant Objects: Give thought to how you might manage objects that don't need updating.
Object Pooling: Improve performance and memory use by reusing objects from a fixed pool instead
  • Memory Fragmentation: Memory Fragmentation is often the primary reason for object pools. They provide contiguous heap of memory.
  • Instantiation and Destruction: Additionally, there's a cost associated with the creation and destruction of objects in our game. Object Pooling allows us to control it.
  • Heap: As discussed in prior lectures, memory fragmentation causes slower performance but also strangles the available memory.
  • Solution: Object Pooling: Grab the biggest chunk of memory we need and don't free it until the level or game ends.
  • Runtime: Define a pool class that maintains a collection of reusable objects. Each object needs a flag to determine if it's 'alive'.
  • Allocation: When the pool is created, all the objects are initialized up front and marked as 'not alive'.
  • New Objects: When a new objects is required, one is found that is currently 'not alive', reset and then set as 'alive'.
  • Vectors: As discussed in prior posts, vectors give us a chunk of contiguous memory on the heap and are quick to iterate.
  • When:
  1. You need to frequently create and destroy objects.
  2. Objects stored in the pool are of a similar size.
  3. Allocation objects on the heap is slow, or could lead to excessive fragmentation.
  4. The resource being acquired is an expensive operation and a cache is more suited.
  • Free List: An alternative to searching through the list to find a free object might be to have a second list or use a sorted associative container.
  • Properties: Are there other fields or properties that can be used to see if the object's in use, saving on the additional boolean.
  • Coupling: The objects being pooled are often aware of the fact, so we could make the constructor private and force the pool to instantiate them.
  • Initialisation: Either the data needed to setup the object has to be passed through to the pool manager, or the pool manager can return it.

No comments:

Post a Comment