Thursday, 17 March 2016

Low-Level Programming_Post20

Low-Level Programming: Post 20 17/03/2016

March 17th 2016 is the date of the twentieth and last lesson on Low-Level Programming (in which I will need to post on this blog needed for the module).

Note: This post is the updated version of the last lesson on Low-Level Programming, as I now have the slides from the lesson to show to you.

Below are the main points taken from the lesson...
  • Bitmasks: What are they and how to use them. 
  • Memory Padding/Alignment: What they are and how they compare to exceptions.
  • Custom Allocations: How to maximize storage of flags or conditions. 
  • Summary: End of!
Bitmasks

Bitmasks
  • Last Week: Last week, we experimented with Bitfields which allow us to store booleans as a single bit inside a data type i.e. an int has 32 bit, so we can have 32 conditions.
  • Another Approach: We can actually approach the same problem from a different perspective. Bitmasking allows the use of logical operators to determine the bit’s status.
  • Padding: If we’re not concerned with controlling the padding or alignment of our data, it’s possible to store the data in a standard variable, either locally or globally.

Example Usage

  • Space Conscious: As with bitfields, reducing the number of booleans used to store conditionals in our code saves memory (due to minimum addressable types) over several booleans.
  • Arbitrary Args: Imagine a situation where we need to pass many args through to a function and we don’t want to wrap it in a struct, we could chose a field of bits instead. Each bit or bits representing a value or state.
  • Component Flags: Game objects are often formed of different component types. Using a mask, an object can store all of it’s component types effectively i.e. an object could be a renderable and movable component.

Vector of Bool

  • STL: The STL actually has a special container type for storing arrays of bits. It's the STL::Vector<bool> container class.
  • Non-Standard: It works differently to standard containers in the STL and actually breaks some of the generic ways of interacting with containers.
  • Disliked: For this reason, it's a useful but disliked container class.
Custom Allocators

New/Delete
  • Replacements: New & Delete are the functions that are responsible for allocating dynamic memory when you instantiated an object on the heap. We can replace these functions, but why?
  • Usage Errors: Using more than one delete on new memory yields undefined behaviour. If the new operator keeps a list of allocated addresses & the delete operator removes them for the list, it's easy to detect this use case & prevent undefined behaviour.
  • Underruns/Overruns: Programming mistakes can lead to data overruns (writing beyond the allocated memory) or underruns (writing prior to the allocation). The allocate can place markers at the beginning and end of the memory block and log these.

New/Delete Continued

  • Efficiency: The versions of new & delete that ship with compiles are general-purpose allocators & deallocators. The allocators therefore apply a middle of the road approach not favouring any one particular usage pattern of memory.
  • Usage Patterns: If you have an impressively good understanding of your program’s memory usage patterns, a custom new and delete operator may outperform the default shipped versions.
  • Performance Increase: You can, if correctly implemented gain some significant performance benefits by adapting the allocation memory model to match your programs memory signature.
  • Usage Statistics: How do we determine our programs memory usage patterns? We can accomplish this through logs.
  • Allocators: We can customise the allocators & deallocators can be used to collect information regarding memory usage.
  • Max Memory: Using this technique it’s possible to establish the baseline for memory usage but also the maximum dynamic memory usage requirement for your game.
Custom Allocators Continued
  • Alignment: The previous example demonstrates how easy it is to create a custom allocator. However, there's a couple issues with it and one in particular worth mentioning. Alignment.
  • Memory Placement: Many computer architectures require that data of particular types are placed in memory at particular kinds of addresses i.e. pointers should occur at addresses that are multiples of 4 (four-byte aligned) or that doubles multiples of 8.
  • Issues: This could lead to exceptions at runtime. Some architectures are more forgiving, but will offer better performance if alignment is maintained. Malloc is byte aligned, but adding the signature could throw off alignment.
C++ Custom Memory
  • Summary:
  1. To detect usage errors.
  2. Collect statistics about dynamically allocated memory.
  3. Increase speed of allocation & deallocations.
  4. To reduce the space overhead of default memory management.
  5. Compensate for sub-optimal alignment in default allocator.
Memory Alignment
  • Access: A computer accesses memory by a single memory word at a time. As long as the memory word size is at least as large as the smallest primitive data type, aligned accesses will always be accessed within a single word.
  • Split: If the highest and lowest bytes in a block of data are not within the same word, the computer must split the data access into multiple memory accesses.
  • TLB/Page Faults: To handle data split across multiple words, the processor must verify both pages before execution or be able to handle a TLB (translation lookaside buffer) miss or page fault during memory access as the instructions are executed.
Atomics
  • Remember those: When a single word is accessed, the operation is atomic. Other devices need to wait until the read or write has been fully completed.
  • Across the words: This is not necessarily the case when accessing multiple words e.g. the first word can be read by one device, both words written by another device and then the second word read by the first device. This is bad, as the data has now been altered mid-way through a read. Think of concurrency issues in threading.
  • X86: X86 is a platform that can handle both aligned and misaligned memory access. However, alignment is preferred for performance reasons.
  • Atomic Instructors: Modern CPUs provide atomic instructions (covered in previous lessons). This prevents issues with concurrent access to the same address.
  • Turn a Bit On: For atomic operations to operate correctly, the address you pass them must be at least four-byte aligned. This is due to atomic instructions and virtual memory.
  • Misaligned: If the address is misaligned, the operation requires at least two memory access operations. If data spanned two pages of virtual memory, this could lead to one part loaded and a page fault being generated when loading the second. The fault would destroy the atomicity of the operation. Because of this addresses must be at least four-byte aligned.
Padding
  • Alignment Concerns: You can see from the previous slides how ensuring data is correctly aligned in memory is essential to performance & stability.
  • Compilers: Compilers will ensure this behaviour for you. Forcing data types to be padded out to ensure they can be read in alignment. This can potentially lead to memory wastage.
  • Padding: It’s possible to create custom data structures and re-assign the basic types memory bits (last week). We can then pad out our structure to ensure optimum performance and memory usage.
Memory Padding

Padding Continued
  • Backwards Compatibility: As some architectures and older CPUs would crash when accessing data on odd memory addresses, the compiler will ensure all fields start on an even memory address.
  • Performance: As demonstrated earlier, accessing data in larger granularities and correctly aligned fields mean a huge boost to the CPU’s performance when accessing memory.
  • Placement: Padding can be added in between members to ensure the individual data items are on aligned boundaries. Data structures will often have members with different alignment requirements.
  • End-Of: The other area in which padding can be added is at the end of the structure. The compiler will add a final unnamed member. This allows each member of an array of structures to aligned.
  • Reordering: Consider reordering to make maximum use of the space. For example: two chars next to each other, followed by a short.
  • No Except: Packed structures (forcing the alignment) is normally used to conserve memory, they can also be used to force the size of data before transmitting it over a network. There’s no need to waste extra space with padding.
  • Performance Trade-off: Of course, whenever we use packed structures in this manner, there’s a space/time compromise being made. Slower performance for less memory.
  • Typical Alignments [32 Bits]:
  1. A char (one byte) will be 1-byte aligned.
  2. A short (two bytes) will be 2-byte aligned.
  3. An int (four bytes) will be 4-byte aligned.
  4. A long (four bytes) will be 4-byte aligned.
  5. A float (four bytes) will be 4-byte aligned. 
  6. A double (eight bytes) will be 8-byte aligned on Windows and 4-byte aligned on Linux 
  7. Any pointer (four bytes) will be 4-byte aligned. (e.g.: char*, int*)  
For the practical in the lesson, we were given two simple options, work on the Chat Program, or leave the lesson early. I decided to try and work on the Chat Program and generally look at how SFML works. Sadly, I couldn't really work on the Chat Program since it had some errors. I will be attempting to work on them over the holiday. Despite this, however, I managed to complete the battleship game and made a good start on the Supporting Document needed for the assignment, with the objective being trying to fit the game into the Chat Program.

Thursday, 10 March 2016

Low-Level Programming_Post19

Low-Level Programming: Post 19 10/03/2016

March 10th 2016 is the date of the nineteenth lesson on Low-Level Programming.

This week's lesson started of in the same fashion as many of the other previous lesson, in that, we were shown what we were going to be covering in the lesson via bullet points. The main points taken from the lesson are listed below...

  • Exceptions: What are they and how to use them.
  • Assertions: What they are and how they compare to exceptions.
  • Bitfields: How to maximise storage of flags or conditions.
However, before we began looking into the parts from the points, we were shown a schedule of the time remaining that we had in the module. In it, it said that this week's lesson and next week's lesson were the last that had lecture slide in them, so in short, next week's post will be the last in this module. The other weeks listed were to focus on the assignments given to us and the Easter break.

Exceptions

Exceptions
  • What are they?: Exceptions provide a way to react to exceptional circumstances (runtime errors) in programs by passing control to a special handler.
  • Catch: When an exception occurs and if we want to handle this exception we need to ‘catch’ it.
  • Try-Block: The code that could generate an exception can be captured in a try block. When an exception occurs in that block, control is transferred to the exception handler.
Handling
  • Thrown: An exception is thrown using the throw keyword within a try block and exception handlers are declared with the keyword ‘catch’.
The Three Keywords
  • Throw: A program throws an exception when a problem shows up. To do this we need to use the ‘throw’ keyword.
  • Catch: A program catches an exception with a handler, at the place in the program where you want to handle the problem. For this we use the ‘catch’ keyword.
  • Try: The try block identifies the block of code for which particular exceptions will be activated. You follow this with one or more catch blocks.
  • Catch Blocks: Multiple catch statements can be used to catch different type of exceptions in case your try block raises more than one possible exception.
Catch Them All
  • Ellipsis: If you want a catch block that handles all exception types thrown or acts as a default, use the ellipsis operator.
  • Nested: It is even possible to nest try blocks. You can then forward a catch block to an external (higher up) catch block. To do this use the throw keyword.
C++ Standard Exceptions
  • C++: Provides a list of standard exceptions (classes) defined in . They are arranged in the following hierarchy.

Throwing
  • When: The general consensus and main use for exceptions is to report when external pre-conditions or invariants, such as disk space or memory are not available. In these cases the program is normally terminated and the exception is the mechanism for transmitting that information.
  • Guidance: Throw exceptions sparingly, when there’s an actual error and no way to deal with it.
  • Catch: Always endeavour to catch exceptions as close to the thrown statement as possible.
  • In Essence: If your code can detect an error and handle it, then do so. If the error is uncorrectable and outside of your scope, thrown an exception.
  • Performance: Exceptions can have a dramatic performance overhead. But this varies depending on the implementation by the compiler. The standard states how an exception must work, but the compilers are free to choose how to implement that functionality.
  • Performance Critical: Generally, if a code path is mission critical and performance is of the upmost concern you wouldn't want to use a throw during any of it.
  • Zero-Cost Model Exceptions:  A newer exception model is now commonly in use. It’s based around the idea that instead of setting up guards and checking for exceptions, the compiler generates a side table that maps any point that may throw to a list of handlers.
Zero Cost Exceptions Cont
  • Exception: Once the exception table is mapped and an exception is thrown, the list is checked to see which handler should be used and the call stack unwound.
  • Overhead:
  1. The zero model is free when no exception occurs.
  2. It can be ~20x slower to call an exception than to use an if check instead.  
  • Measuring Costs:  Measuring the difference is not easy i.e. cache misses:
  1. The side table is generally not loaded in memory.
  2. Determining the right exception handler involves RTTI and complex operations to run a test for the handler’s suitability i.e. a dynamic cast operation.
Exception-Safe Code
  • Strive: Always strive for exception-safe code. When an exception is thrown, exception safe functions should:
  1. Leak no resources.
  2. Prevent data structures to become corrupted. 
  • Safe Functions: Exception safe functions offer one of the following three guarantees:
  1. Basic guarantee.
  2. Strong guarantee.
  3. The no throw guarantee.
  • Resource Leak: The code breaks the resource leak rule, because if the memory allocation throws an exception, the mutex will never get unlocked.
  • Data Corruption: If memory allocation throws, bgImage is left pointing to a deleted object. In addition the background change count has been increased even though no new image has been setup.
  • Resolutions: How do we resolve these issues;
  1. Acquire a scope terminating mutex.
  2. Use a scoped smart pointer for creating the new image.
  • Basic Guarantees: The example we fixed now offers basic guarantee i.e. if an exception is thrown, everything in the program remains in a valid state. No data is corrupted and all objects remain in a consistent state.
  • Strong Guarantee: Functions that offer the strong guarantee, promise that if an exception is thrown the state of the program is unchanged. Calls to such functions are atomic i.e. they either completely succeed or completely fail.
  • No Throw: Functions that will never thrown an exception can be also be thought of as exception safe.
Exception Summary
  • Safe: Exception safe functions do not leak resources when an exception is thrown and no data structures should become corrupt as a part of this process.
  • Strong: The strong guarantee, means resources do not leak and no data should be changed. This can be achieved by copy-and-swap approaches, but has overheads.
  • Max Guarantee: The max level guaranteed by a function is no stronger that then weakest guarantee of the functions it goes on to call.
Asserts

Assertions
  • What are they?: Assertions are use to abort your program if the a specific assertion is not met. In essence it’s a way of explicitly stating something should hold true in your code base, otherwise something is wrong or more succinctly ‘make sure’.
  • Expression: If an asserted expression does not evaluate true, an error message displaying the expression being checked, along with source information can be printed to the console out or window.
  • Termination: The program will then terminate with no clean-up. A crash dump may also be generated.
  • Debugging (1): Assertions are commonly used to help track down program bugs. They can be used to track down conditions which aren't sensible during run time.
  • Additional Info: Using asserts, it’s possible to construct a string that contains information about the program’s running state and display it as part of the assert.
  • Debugging (2): If a debugger is attached to the running process and an assert is triggered, there’s the possibility to break into the program just as if a break point had been reached.
  • Debug Builds: Default release build settings will strip out asserts from the codebase. This in turn reduces the size of the final executable. When the compile option is disabled, you can be guaranteed that assert checks won’t be performed in release mode.
  • Asserts: Asserts are used to aid in debugging code that we have written and can react accordingly. They are primarily only used for debug builds but can be used in release builds if desired.
  • Exceptions: Exceptions are used when a set of circumstances outside of our program’s control is encountered and is detrimental to the programs function i.e. disk space issues.
  • Summary: Both asserts and exceptions are runtime. Asserts are useful for debugging the code we've written and managed. Exceptions are most useful when an issue has occurred outside of our control and allows us to communicate the exception to the user.
Static Asserts
  • C++11: Traditional asserts are performed at runtime. C++11 allows us to perform static asserts i.e. checks performed at compile time. If they fail the program will not compile.
Bitfields

Bitfields
  • Flags: Imagine that somewhere in your codebase that you wanted to store a series of conditions or flags on an object.
  • Bool (1): The simplest approach would be to utilise Boolean’s. One Boolean for each condition or flag.
  • Bool (2): For the space conscious amongst us, there’s an alternative approach to using Booleans (3xbytes).
  • Bitfields: Instead of Booleans as shown on the previous slide, let’s consider what a flag or condition is trying to represent; simply a state, either on or off just like binary.
  • Bits: It makes sense then that if only a single bit is required to show state, that we should be able to divide up a larger data type into bits and access each bit individually i.e. an integer which is 32bit large, can have 32 fields. One per bit.
  • Define: Defining a custom size for a field (struct/class only) is possible and supported and has the following syntax: declarator : constant-expression.
Following the end of the lecture slides, we then moved onto the practical side of the lesson. For this lesson, it was effectively carrying on from the past week(s) in trying to create a Chat Server & Chat Client. However, once I re-added the LibCaca files necessary for the project, I made a start in listing the various features in the Battleships game for the assignment. I realise that I went a little off-track on the practical, but it was important work nether-the-less.

Thursday, 3 March 2016

Low-Level Programming_Post18

Low-Level Programming: Post 18 03/03/2016

March 3rd 2016 is the date of the eighteenth lesson on Low-Level Programming.

This week's lesson was a particularly important one, as we were set the details for our second assignment, which I will talk about later in this post. The following main points that were taken from the lesson are listed below...

  • Dump Files: How to use them.
  • PDB Files: How to load symbols for debugging.
  • Assignment: In detail.
Dump Files

Dump Files
  • MSDN: States, a dump file is a snapshot of an app at the point in time the dump is taken. It shows what processes were executing and what modules are loaded. A copy of the heap can also be stored, allowing examination of the memory.
  • Crashes: When applications crash a crash dump is often generated. These can be essential in debugging the root cause of the crash. A copy of the heap is generally required.
  • Visual Studio: Opening a file in VS is like stopping at a breakpoint in a debug session. You can not continue execution but you can examine threads, stacks and variables.
Debugging Symbols
  • Symbols: Depending on the type of dump, symbol files may be required to enable proper debugging. You can easily load symbol files using modules inside visual studio.
  • Heaps: Visual Studio can load the symbols even if the application binary is not found. Includes a copy of the heap and stack.
  • No Heaps: The debugger has to load the app binaries to find the symbol information. The binaries must be an exact match.
Symbols/PDB Files

Symbols
  • Placeholders: Symbols are placeholders or mappings of variable and function names to respective memory addresses. This mapping is used to determine the location in memory when specific data or functions are used.
  • Linkage: Symbols are used during the linkage phase of your programs build process. This is why you will often get errors involving unknown external symbols i.e. the symbol’s mapping could not be determined.
  • Symbol Tables: When the symbols are being generated they placed in a table, there are symbol tables created as part of the compilation process and tables as part of the linkage phase as well.
Symbol Tables
  • Data Structure: The symbol table is an important data structure created and maintained by compilers in order to store information about the occurrence of entities such as variable names, function names, objects, classes interfaces etc.
  • Purposes: May serve the following purposes depending upon language:
  1. To store the name of all entities in a structured form at one place.
  2. To verify if a variable has been declared.
  3. Type checking, verifying assignments and expressions are correct.
  • Table: A symbol table should provide both an insert and a lookup function.
  • Insert: Used more frequently at the analysis stage of compilation. The operation is used to add information in to the table about unique names occurring in the source code (i.e. symbols).
  • Lookup: The lookup operation is used to search a name in the symbol table to determine:
  1. If the symbol exists and has been declared before it’s used.
  2. If the symbol is initialized.
  3. If it’s been declared multiple times and whether or not it’s in scope.
Compilation
  • Object Files: During the compilation process, source files are compiled and stored in resultant object files often with .obj or .o extensions. A symbol table is also included.
  • Output: The object file’s symbol table is a data structure and it maps the different items (variables, functions etc.) in the object file to names that the linker can understand.
  • Calls: If you call a function from your code, the compiler uses a placeholder value that tells the linker to look up the reference in the all available symbol files, looking for a match. This will have the address details required.
Libraries
  • Shared Libs: Shared libs or DLL also have a symbol table. This is a linker stage generated process. It names and exposes all the functions and data that are visible to users of the library. The static library in dungeon death is doing exactly this.
  • Runt-Time: Using the exposed symbol table, runtime linkage can be performed i.e. map the placeholder to it’s address. In essence this allows references to the memory location of the library which isn’t known until runtime.
DLLS
  • Shared Code: DLL’s (dynamic link libraries) are used to share code between developers. They also allow upgrade of library functionality without re-linking or re-compiling.
  • EXES: When programs rely on DLLs the executable informs the OS of the DLLs name. The loader than searches for the DLL file and loads it. Inside the DLL there is an export list.
  • Export List: The export list functions like the symbol list. When your executable calls a libraries function, the symbol is searched for and the memory address of the function is returned.
Address Space
  • Address Space: When windows loads the program, it creates a whole new “address space” for the program. This is the same process for DLL files. The DLLs addresses for exported functionality is dependent on where the OS has loaded the DLL in memory.
  • Relocatable: Unless you use special data inside DLL or the 3rd party company does, only a single instance of that DLL can be loaded at any given time. It’s not possible to load multiple versions of the same DLL in different address spaces.
PDB Files
  • Program Database: When debugging crash dumps, if we don’t have access to the symbol table, we’ll see a list of memory addresses in the call stack. To aid debugging we can utilise program database files.
  • PDB: PDB files are collections of all the symbol based information used in the program and libraries. They are directly linked to the version they were built against.
  • Debug: Debug build targets inside VS normally automatically created the PDB files for you.
  • Release: Release builds can create PDB files but often need to be manually enabled depending on build defaults.
After showing us about PDB files, we had to complete a mini tutorial. In this tutorial, we had to load and examine two 'dump' files, one where we needed to debug without a heap and debug with a heap. After a little bit of guidance, I managed to load up both files in two separate VS projects. The only difference I could see between the one with a heap and the one without a heap. One of them had some unknown values, whereas the other had it's value's set to 0. I couldn't remember which was which, unfortunately, nor do I know if I did it 100% correctly.

Assignment

Exercise 2 Overview
  • Multi-Player Game: Your assignment will be to create a multi-player game that is playable over a network. You will be responsible for creating both the client and server with respective logic.
  • In this exercise you will be recreating a version of Battleships. The exercise assignment details how the game is expected to play.
  • As the UWE network is firewalled, running the client and the server on the same PC during development is advisable i.e. use localhost for network address. 
Brief
  • Pirate Themed: You are asked to complete a faithful recreation of Battleships, however, rather than the traditional ships, the theme of your game should be pirates.
  • Game Grid: Fundamentally you will need to utilize a game grid that allows the player to position their ships and keep track of cannonballs fired.
Points of Interest
  • Pairs: The coursework will be in pairs. Where a pairing is not feasible a single person may complete the exercise at expense of the additional features. Each member of the pair will tackle their own extra feature.
  • Git: You will need to use git as your version control software. The git repository will need your submission.
  • SFML: It is expected that the networking functionality of your game is to be provided using the SFML library.
  • Games Mechanics: The games mechanics will be tested the game should run as expected. The rules have been provided within the assignment specification.
  • Essentials: Ship placement rules must also be implemented alongside the games turn based logic. Placement, firing, hit/miss stages and winning or losing the game are essentials.
  • Focus: Marks will be focused on the quality and suitability of the code in tandem with whether or not the game runs as expected.
  • Game/Server/Client: The solution should be broken down into three projects. One project for common code, one for the client and one for the project. Client and Server should be exes i.e. (DD)
  • Client: Should show two grids, one for player’s own ships and one for attacking. Consider how best to display this. Only a console UI is required for this.
  • Server: The server should show both player’s grids and any shots that have been fired. It will also need to include a list of all players connected. Clients should be able to send messages to each other. Again a console application is fine.
  • Ping: Implement a working ping/pong system. The client should display the latency to the server. The server should show the latency of all connected clients.
  • Disconnections: Make sure to handle disconnections gracefully, either when a client exits expectedly as well as when a client’s connection drops unexpectedly.
  • Remaining Clients: The remaining client should be shown a game won message as well as the reason for their victory i.e. dropped connection or rage quit.
  • Multiple Choice: You have a choice of one of the following three features:
  1. GUI: Using SFML create a graphical based version of your game. SFML provides basic OpenGL and window management support. Sprites may be a good choice.
  2. A.I: Implement a computer based opponent. Consider how they would place their ships and also how they explore the grid.
  3. Save/Loads: Create a profile system which allows games to be saved and resumed when both users reconnect. Should have choice to resume or create a new game.
  • UML: Provide class diagrams and explain relationships between classes. Why inheritance or composition?
  • Design: Evidence of planning and design stages either through discussion or diagrams. Researching a game’s requirements before writing the codebase will make it easier to implement.

Thursday, 25 February 2016

Low-Level Programming_Post17

Low-Level Programming: Post 17 25/02/2016

February 25th 2016 is the date of the seventeenth lesson on Low-Level Programming.

Before the start of the lesson, in that we were shown some slides on the topics at hand, we were reminded of the overview of the course, in that, we were shown how our overall study in the course should be. In short, the reason we were shown this was an indication that some of us in the course needed to work and attend more.

After that, we were shown the main points that we were going to cover in the next couple of hours...

  • Threading: Job Scheduling.
  • Mutexes: What are they and how do they work?
  • Atomics: Atomic instructions.
  • C++11 Threads/Tasks: Threads VS tasks, pros and cons.
Threading

Threading
  • What is it?: Threading is the execution of parallel tasks running outside of a single point of execution.
  • Why?: Modern day CPU architecture is completely based around the ideal of using multiple CPU cores running unique tasks at the same time.
  • Multi-Threaded: Programs that utilise this type of technology are often known as being ‘multi-threaded’. In this modern day of development, you can’t get away from working with threads.
The Problem
  • Single Threaded Game Loop: Traditionally, we break the engine into sub tasks, run them in order and rinse and repeat.
  • Sequential: This approach was fine before the use of multi-core CPUs, but on a modern day system this would leave all the other x number of cores unused.
Thread Control
  • Master Thread: In this scenario, we require a master thread that that controls and synchronises the secondary subsystem threads and handles the game’s high level logic i.e. the game loop.

Pipe-Lining
  • Pipeline Parallelism: Running two parts of the same pipeline in synchronised threads. This is known as lockstepping. i.e. we need the first part to finish before the second starts.
  • Graphics: The graphics rendering can be started on a different thread, as long as the update of game logic has been completed.
Task-Schedulers
  • Desire: Task scheduling was designed to meet the desire for more fine-grained levels or parallelism (similar to fork and join).
  • Tasks: The tasks themselves i.e. logic, physics etc. can be broken down in to smaller tasks. If safe to do so, these subtasks can be run in parallel.
  • Scheduler: The task scheduler approach is a system that allows us to ‘throw’ these smaller subtasks on to threads and process them in parallel.
Sub-System Threads
  • Dedicated?: Each worker thread is a kind-of dedicated thread. Instead of one subsystem it handles tasks. It works through them. 
  • Concurrent Queue: Just like our lockstepping example, the we can use a concurrent queue, add jobs to it and the worker threads process them.
  • Agnostic: The worker threads are agnostic. We don’t care which thread handles which jobs, just so long as the queue is processed.
  • Event Thread: There is one event for each worker thread. Those threads then listen to their designated events and start working when the signal is triggered.
Task Groups
  • Grouping: A more advanced version of this system involves creating a task group for each system.
  • Threads: Multiple threads work on the same task group. Obviously they would need to manage the queue amongst themselves.
Dependencies
  • Task Groups: It may not be safe or sensible for threads to process tasks groups as and when. Task groups allow us to setup dependencies.
  • Threads:  The thread that finishes the last item in the task group schedules the next one.
Improvements
  • Centralised: Centralised or per-thread specific task lists.
  • Priorities/Affinities: Allow some tasks to have higher priorities and certain tasks or groups to be assigned to a designated hardware thread.
  • Batching: Batch up a series of similar tasks (fork and join) and dispatch using the thread scheduler system. You could also pin specific job threads to cores as well.
Mutexes

Mutex
  • What is it?: A mutex is a program object that allows multiple threads to access the same resource.
  • Shared Data: It’s designed as a synchronisation primitive with the intention of protecting shared data that’s accessed concurrently.
  • Exclusive: A mutex offers exclusive, non-recursive ownership semantics.
  1. A calling thread owns a mutex from the time it successfully calls lock through to unlock.
  2. All other threads trying to access a locked mutex will fail.
  3. A calling thread must not own the mutex prior to calling lock or try_lock.
Mutex Requirement
  • When: A mutex quite simply is required when shared data is under concurrent read and writes i.e. when one thread may read and another write at the same time.
  • Safety: The mutex ensures that we don’t access the shared data unless no other thread currently accesses it. If the mutex is currently locked, the thread will need to wait.
  • Semaphore: A mutex is a type of semaphore. An object designed for concurrent usage. Generally suitable when a shared object isn't under a huge amount of contention.
Atomics

Atomics
  • Contention: When a concurrent object is under high contention, than implementing the use of atomics over things like mutex’s is a good design decision.
  • Atomic Stores: On some platforms store and loading values are already atomic i.e. their operations only generate a single instruction.
  • Platform: Each platform has its own ways of exposing atomic operations. Before C++11 game engines would need to create an abstraction to allow ease of use.
  • Operations: An atomic operation is an operation or set of operations that appears for all intents and purposes to occur instantaneously.
  • Options: To ensure ordering you can utilise fencing. There are two types, lightweight and full fences.
  • Lightweight: Orders load from memory & Orders store from memory.
  • Full Fence: Lightweight plus Commits stores before next load.
  • What are they?: A memory barrier, also known as a member, memory fence or fence instruction, is a type of barrier instruction that causes a central processing unit (CPU) or compiler to enforce an ordering constraint on memory operations issued before and after the barrier instruction.
  • Necessity: Memory barriers are necessary because most modern CPUs employ performance optimizations that can result in out-of-order execution.
  • Re-Ordering Issues: This reordering of memory operations (loads and stores) normally goes unnoticed within a single thread of execution, but can cause unpredictable behaviour in concurrent usage.
  • Portable: As mentioned previously; C++11 now provides developers with an atomic library that operates at the platform layer allowing portable code.
  • Concurrent objects: Objects under heavy contention should make use of the C++11 atomic library.
  • Forbids data races: C++11 atomics forbids data races, when the same object is being written to concurrently.
  • Guidance: The rule; If multiple threads access the same variable concurrently, and at least one thread modifies it, all threads must use C++11 atomic operations.
C++ Atomics API
  • Sequentially Consistent:
  1. Similar to Java volatiles.
  2. Used in books / literature.
  3. Slower with modern architectures. 
  • Low-Level Atomics:
  1. Similar to C/C++ volatiles.
  2. Much like the game atomics.
  3. Translate more closely to native instructions.
C++11 Threads

C++11 Threads
  • How to create one: std::thread is the libraries version of a thread. You can use it to construct a new thread. The constructor can be passed the function to run as a function pointer.
  • Join: If you want to wait for the thread to finish executing, you can call join on it.
  • ID: How do we distinguish between threads, well they have IDs. The std::thread class has a get_id() function. The ID is obviously unique.
C++11 Tasks
  • How to create one: C++11, allows us to create threaded tasks and store the result of the thread’s execution in a std::future.
  • Futures: You can retrieve the exit value of a thread, or even wait on a thread’s execution via it’s future handle.
Prefer Tasks over Threads
  • Return Value: Tasks allow us easy access to a thread’s return value via the future object it creates. This is far from straightforward with a std::thread.
  • Exceptions: Exceptions in threads cause all threads to terminate. With tasks we can actually interrogate any exceptions that are thrown and the program does not terminate.
  • Thread Management: Using std::threads mean you need to manage the number of threads and oversubscription numbers. Too many threads will slow the system down via context switching. With async tasks it does not guarantee the launch of a new thread, thus protection against oversubscription. It can even schedule the thread to run later.
After the couple of hour long slides, we than proceeded to the practical task for this week. In this week, we had to add various components to the DungeonDeath game. Unfortunately, this was a bit of a struggle, since we had to add the LibCaca files into the downloaded folder via Gitlab. However, despite this and with a little bit of help from the tutor, I completed the first task given to us. I couldn't complete any more, however, as I ran out of time to attempt the other tasks.

Thursday, 18 February 2016

Low-Level Programming_Post16

Low-Level Programming: Post 16 18/02.2016

February 18th 2016 is the date of the sixteenth lesson on Low-Level Programming.

In today's lesson, we (sort-of) went back to the normal routine of the theoretical part of the lesson and the practical side of the lesson. Although it was mostly practical based, there were still some lesson slides to have a look at. Below are the main points taken from the lesson...

  • Networking: How to handle disconnected or slow clients.
  • Threading: Basic principles of threading.
  • Dungeon Death: Continue working on the client development.
Connections

Disconnections
  • Client: How should we handle client disconnections?
  • Heartbeat Monitoring: One option is to continually poll the clients and see if they respond. This is known as heartbeat monitoring. i.e. listening for a heartbeat.
  • On Demand: Maybe we could perform the check only when we want to send data, but this can cause delays in the thread and means we have stale sockets.
  • Messages: The best approach is to get the client to send a disconnect message to the server, indicating when it’s disconnected. Then the server can remove the connection.
  • SF: The SFML library also sends a disconnected message as well. This can be used to detect disconnections by clients.
Pings/Latency
  • Latency: As discussed before, the latency refers to the delay in data being sent and received between two hosts.
  • Ping: The ping is the amount of time it takes to send a message and receive a response. This is an easy to measure value.
  • On Demand: Clients with high latency should be disconnected in games where real-time updates are essential, as they can negatively impact all users experience.
Ping in Action
  • Ping: Save the start time and send message to the server. This is the ping. The server will respond will reply with a pong response.
  • Pong: When that pong arrives at the client side we can calculate the difference i.e. 𝑑𝑢𝑟 = 𝑒𝑡 − 𝑠t.

Once we finished the 'Connections' based slides, we started to work on our first practical session of the lesson. 

In this session, we were given the complete set-up of the Chat Client and Chat Server project that we have been working on for the past few weeks. We then had to add some components into the project (some snippets were provided). However, at the start of the project, the lib files were incorrect (they didn't match with each other), so after the tutor helped me to fix the problem, I was than able to start working on the task at hand. Initially, it was going fine, where I thought I put the code in the correct place(s). However, due to an error in the network system at the University, I couldn't properly run the program. Despite this, however, I still had some code missing from my project, as the tutor than showed us the solution to connect the two together.

Once the first practical was finished, we than went back to the theoretical side of the lesson.

Threading

Threading
  • What is it?: Threading is the execution of parallel tasks running outside of a single point of execution.
  • Why?: Modern day CPU architecture is completely based around the ideal of using multiple CPU cores running unique tasks at the same time.
  • Multi-Threaded: Programs that utilise this type of technology are often known as being ‘mutithreaded’. In this modern day of development, you can’t get away from working with threads.
Multi-Core
  • Why?: The interesting thing about modern day CPUs is that they often run at a slower clock speed than their counterpart from a decade ago.
  • From GHZ To Cores: Unfortunately, increases in GHz became prohibitive due to the amount of additional electrical power required to power them.
  • Parallel: By using multiple cores on one CPU die, but running them at a slower clock speed, the CPU’s became more efficient and less susceptible to these issues. However, now we need to communicate between the cores to unlock their potential.
  • CPUS: Modern day CPU dies are normally constructed from more than one core. Quad core is fairly common place.
  • Cache: These cores tend to have a small dedicated high speed cache and a slower but bigger shared one.
SFML Disconnections
  • Contention: Remember that there can be issues of contention where large data is shared between CPU cores.
  • Coherency: The hardware will maintain the caches for each core. However, this can cause necessary performance loss.
  • Fences: Memory fences can be used to pause execution until values have been written, thus ensuring order.
The Problem
  • Single Threaded Game Loop: Traditionally, we break the engine into sub tasks, run them in order and rinse and repeat.
  • Sequential: This approach was fine before the use of multi-core CPUs, but on a modern day system this would leave all the other x number of cores unused.
Subsystem Threads
  • Simultaneous Actions: Often our game loop is busy polling for actions or inputs from various subsystems. Whilst we poll for these system events, the execution is blocked, until we receive a response.
  • Asynchronous: Let’s consider an approach when we run specific tasks asynchronously i.e. in another independent thread.
  • Candidates:
  1. Network Messages.
  2. Input Polling.
  3. Event Processing.
  • Shared Data: It’s also important to establish the relationship between data being shared and modified by threads.
Pipelining
  • Pipeline Parallelism?: Running two parts of the same pipeline in synchronised threads. This is known as lockstepping. i.e. we need the first part to finish before the second starts.
  • Graphics: The graphics rendering can be started on a different thread, as long as the update of game logic has been completed.
Semaphore
  • Render: The semaphore (our concurrent object) count is increased when the engine update is completed and the decreased once the render phase is over.
  • Engine: It’s good practice to have a semaphore in the opposite direction to stop the engine’s update getting too far ahead of the rendering phase.
Fork & Join
  • What is it?: Divide a unit of work into smaller subunits, distribute (fork) these workloads to multiple threads and merge the result of all the workloads (join).
  • Animation Blending: Animations are blending using skeleton poses. The LERP process can be completed on each joint independently.
After finishing the theoretical side of the lesson, we then moved onto the second practical of the session. Unfortunately, due to the problems with the networking (as mentioned earlier in this post), I was unable to download the ZIP file provided to us from 'tinyURL', thus unable to work on the tutorial. Because of this, we were allowed to finish the lesson early.

Thursday, 11 February 2016

Low-Level Programming_Post15

Low-Level Programming: Post 15 11/02/2016

Febuary 11th 2016 is the date of the sixteenth lesson on Low-Level Programming.

In today's lesson, we took a very different route to normal. In that, rather than going through the lesson's slides and listing the main points from it, today's lesson was basically a lesson-long practical session.

For the practical itself, the objective was to set up a new project onto the website 'GitLab', which coincides with the website 'GitHub'. From there, we got Visual Studio to load up the new project from GitLab into Visual Studio.

Afterwards, we than had to do the same thing for the project of 'DungeonDeath', which was used earlier in the year. Initially, the tutorial(s) were going well, until we noticed that a 'lib' file called 'LibCaca' was missing and we couldn't use the provided method due to the administer forcing us to close the solution.

Fortunately, with some help from a university college, I managed to successfully load the lib/libcaca into the project and from there, the project was able to run successfully.

The next task was to then combine the DungeonDeath game with the Chat Server and the Chat Client projects together, but I didn't managed to get started as I ran out of time in the lesson.

As for the lesson, although at one point it was frustrating being unable to solve the problem about the lib file, I managed to understand a majority of it all due to the videos/tutorials that guided us this lesson. Despite this, however, being unable to solve the problem without receiving help from someone was disappointing, but it made sense when the solution was pointed out.

Thursday, 4 February 2016

Low-Level Programming_Post14

Low-Level Programming: Post 14 04/02/2016

February 4th 2016 is the date of the fifteenth lesson on Low-Level Programming.

Despite being a little late for the lesson, I missed only two slides at the beginning, one of which was the overview for the lesson.

In this week's lesson, we were continuing on the topic about Networking. Below are the main points from the lesson...

  • Networking Cont: Sockets/Packets.
  • Server-Client Setup: How do traditional server client setups function?
  • Peer to Peer Networking: Peer to Peer infrastructure and usages.
Networking

IP Addresses
  • Unique ID: All hosts that support data transfers over a network need an unique address. As covered last week, the IP addresses solves this issue.
  • Public IP: Public IP’s are accessible from the internet, where as private IP’s are reserved for Local hosts. Remember; a private IP will not be routed externally.
Domain Name Systems
  • DNS: IP addresses aren't very user friendly. Instead we have a technology that allows IP -> human readable names.
  • Domain Names: Domain name queries are sent to DNS servers where they return the unique IP of the host associated with it.
Transport Protocols
  • TCP: TCP is a fully fledged error checking protocol. It guarantees delivery, but is slow.
  • UDP: UDP is a best effort solution. It sends the data directly, doesn’t use a connection and doesn’t guarantee delivery.
  • Usages:
  1. When data delivery is essential and speed is not, TCP is most suited.
  2. When real-time response and updates are required than the lightweight nature of UDP makes it ideal!
Sockets

Sockets
  • What are they?: Sockets are used in the transmission between networked devices. They provide the interface between your application and the outside world.
  • Data: Through a socket; data can be both sent and received. Therefore, it’s likely any program involving networks will utilise them.
  • Types: There are multiple types of sockets available, each with their own feature set. I’ll be working with UDP and TCP sockets provided by SFML.
  • TCP: As we know, TCP sockets are connection based. You can’t send or receive data between the hosts until the connection is created. Each client needs it’s own socket.
  • UDP: UDP can send and receive data on the same socket irrespective of the number of clients.
  • Stream: TCP is a stream protocol, there’s no message boundary. Multiple bits of data from different objects can be received as a single ‘packet’ of data.
  • Broadcasting: Additionally, UDP can broadcast data on the network segment. This is often know as multi-casting. TCP can not do this.
  • Server/Client: In order to connect the two nodes via TCP, we’ll need one node listening. In a server client infrastructure you can describe the listening node as the server and the connecting one as the client.
  • Client: The client only requires a SF::TCPSOCKET, which can be used to connect to the server by calling the connect function.
  • Server Sockets: The server needs multiple sockets, one to support each client connected and one to listen for new connections.
  • Listener: We can use the class SF::TCPLISTENER, which is a class specifically designed to listen for incoming connections.
  • Accept: The accept function on the listener is also a blocking call.
  • Connections: As discussed previously, UDP sockets do not need direct connections between the two hosts. However, you need to bind them to a specific port to listen on.
  • Data: The server uses a SF::UDPSOCKET, which once bound can now be used for data.
  • Sending: Sending of data is performed the same way irrespective of the protocol.
  • ARGS: UDP requires two additional args, the address and the port of the recipient.
  • Data: Data can be sent as raw bytes or abstracted into a format known as packets.
Guidance-Sending
  • Sending Data: The send functions take a void* pointer. However, it’s generally a bad idea to send arrays of bytes. Types on different platforms can have different storage requirements.
  • Type Sizes: Types such as int or longs may have different sizes or even different endianness, therefore cannot be sent reliably.
  • Broadcasting: You can also use SF::IPADDRESS::BROADCAST to send a message via UDP to the entire sub-network in a single call.
  • Buffer: The first two args are the data being received and the max size that can be received.
  • Received: The third argument reports how much data was received.
  • UDP: UDP has two additional which show the sender’s IP and port the data arrived from.
Blocking
  • Multiple Clients: A single socket can cause issues when you have multiple clients. You want to be able to listen for any incoming packets from clients and deal with them without first processing other sockets or being held up.
  • Blocking Clients: Instead we should listen on all clients and then process any of the sockets when data is received from a client.
  • Selector: Handily, there’s an SF::SOCKETSELECTOR class that does this for us. It can monitor TCP/UDP sockets as well as the SF::TCPLISTENER for new connections.
  • Wait: The wait function on the selector will return true if there’s data to received by one of the monitored sockets.
  • Socket/Listener: If it’s a socket which is ready it’s a client sending data. If it’s a listener it’s a connection request.
  • Check Monitored: The selector only has handles to the sockets, it does not store them.
Packets

Packets
  • Data Exchange: Exchanging data is more tricky then actually sending it. There’s a need to make sure the data is compatible between hosts. Serialised data sent between hosts is often know as packets.
  • Issues: Endianness, primitive type sizes and TCP packet splitting form the low level problem that can occur.
  • SFML: The SFML library provides ways to circumvent these issues, until you’re more comfortable coding your own solutions.
  • SF Primitive Types: Depending on the platforms being used primitive types can vary in size and endianness. They therefore can not be used for reliably for data exchange.
  • Fixed Types: SFML provides a series of fixed types that are guaranteed to be the same size on other platforms.
SF Packets
  • SF: The sf packet class is designed to get around the remaining two issues i.e. endianness and message boundaries.
  • Streams: sf::Packet works just like a normal stream operator would. You use the << and >> operators.
  • Error Checking: The packet class provides error checking. The result of the stream operator will return false if a reading operation fails.
  • Sending/Receiving Packets (1): Quite simply, replace the call to send with a SF::PACKET instead of void* data.
  • Message Boundaries: Packets solve the message boundary issues, meaning the exact same TCP packet is received as was sent. This comes at the cost of additional bytes which forces the packet to be decoded using the SF::PACKET interface.
  • User Data Types: Overload the stream operators and write / read the classes member’s to it.
  • Sending/Receiving Packets (2): Because of the library’s OOP design, we can easily extend the SF::PACKET class to incorporate additional technology such as encryption or compression.
Infrastructure

Approaches
  • Multi-Player Support: Games that utilise networks can be implemented in one of two ways. Either authoritative or non-authoritative.
  • Client-Server: The client server solution is authoratitive and it’s the structure we’ve already been discussing. i.e. a server and then clients.
  • Peer to Peer: P2P does not use a central entity to manage the game. Every client controls it’s game state and is responsible for updating connected peers.
Authoritative
  • Server: The server controls the whole game world, including logic and client synchronisation.
  • Data: All clients constantly receive and send data directly to the server. The clients have a local representation of the game based on the server’s state.
  • Clients: The clients perform actions, which are then forwarded on to the server. The server then updates it’s game state.
  • Dumb Terminals: The clients themselves can be considered dumb terminals. The client sends the data representing things such as keypresses and mouse input. In response the server replies with a packet containing the state of your game.
  • Interpolation: The client needs to provide some form of interpolation between the updates being sent and received, to give the illusion of smooth movement.
  • Latency: The problem with dumb clients, is the latency between the server saying an action is possible and the client receiving it, leading to a delay in response.
  • Client-Side Prediction: The client in fact, can no longer be just a dumb terminal. Instead it has to predict the movement of your character locally, responding immediately to inputs.
  • Authoritative: The server overrides the client’s prediction at any given time, so the more accurate the better.
Non-Authoritative
  • Peer to Peer: A non-authoritative approach has no central entity to control the game’s state. Every peer must control it’s own and communicate changes to other peers.
  • Simulation: The clients then see two views of the game world. Their own character or avatar and a simulation of all the other player’s game entities.
  • Local: All client actions relating to their own game entity is immediate and responsive. For all other players, the network message needs to be received to update their position or actions.
  • Latency (1): The problem with dumb clients, is the latency between the server saying an action is possible and the client receiving it, leading to a delay in response.
  • Simulation: In order to keep all player’s game world up to date, each client needs to send updates as frequently and as quickly as possible.
  • Delays: Delays in updates being received, may mean the player has moved or performed an action “x” amount of time ago, but the other peers aren't aware.
  • Missing Data: Lost or delay packets can mean player’s appear to teleport on the clients. Local prediction similar to client-server interpolation can be used. The longer the latency, the less accurate the interpolation.
  • Extrapolation: Focuses on moving the local entities based on their current states. It assumes that the entity will not change their route. The entity can then safely be moved according to its current velocity.
  • Latency (2): The key to good interpolation and extrapolation is latency. The lower it is the better they will perform. This is why peers with high pings are often kicked.
After finishing the theoretical side of the lesson, we then moved onto the practical task for this week's lesson. Since there wasn't a mini practical task earlier in the lesson, this practical task was a little longer, to compensate for there not being a mini practical task.

The task for this week was to add a Chat Client to go with our Chat Server from that was started last week.

I tried to fix some errors for the Chat Server program before starting on the Chat Client task. Some I managed to fix, due to basic incorrect user input and where to put the parts of the Chat Server code. Originally, they all went inside of the main for some odd reason, while the main itself was missing some code itself. However, there were still two errors left unfixed in the project. Despite this, however, I managed to do the basic setup for the Chat Client, and added all of the code parts into a new project and set the the project's properties for the Chat Client's liking. Hopefully, I should have all ready for next week.