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.

Thursday, 28 January 2016

Low-Level Programming_Post13

Low-Level Programming: Post 13 28/01/2016

January 28th 2016 is the date of the fourteenth lesson on Low-Level Programming.

After clearing up last weeks confusion regarding missing a post on a lesson, everything should be back to normal for the next few weeks.

In this week's lesson, we were taught about Const Correctness & Networking. Below are the main points from the lesson...

  • Const Correctness: What is it and how does it work?
  • Const & Non-Const Functions: How do const and non-const functions work in tandem.
  • Networking: What are data packets and how do we send/receive them?
Const

Constness
  • Const Correctness: Const correctness is fundamentally based on treating data and objects as constant unless we intend to modify it’s value.
  • Semantics: Const allows you to specify a semantic constraint – a particular object should not be modified. Compilers will obey this constraint.
  • Meaning: Const tells both the compiler and programmers that a value should remain invariant. Whenever that’s the case, you should say so i.e. const.
  • Scope: 
  1. Outside of classes; Static at file, function or block scope.
  2. Inside of classes; Both static and non static data members
  • Const Pointers: It is possible to have constant pointers to data, pointer to constant data or even a constant pointer to a constant data address.
  • Syntax: If the word const appears to the left of * it’s constant data, else it’s a constant pointer.
  • Iterators: As covered previously, iterators are just abstracted pointers to data. This means it’s constness is similar to that of pointers.
  • Const Iterator: An iterator that can’t point to a different memory address.
  • Iterator to Const Data: An iterator that can point to any memory address but not amend data.
  • Parameters: When passing user defined types into functions, always use the const declaration where possible.
  • Benefits:
  1. Tells the programmer that the data won’t be modified.
  2. Stops accidental errors such as ‘=‘ when you meant “==“.
  3. Const “may” improve performance with ROM caching.
  • Member Functions: Const member functions identify which functions can be called on const objects.
  • Clarity: They show a clear interface for the class’s interaction with const objects.
  • Const Objects: You can’t work with const objects in non-const functions.
  • Overloading: A member function can be overloaded by it’s constness.
Bitwise Constness
  • Bitwise: A member function is only const if it doesn't modify any of the object’s data members, excluding static variables. i.e. it doesn't modify any of the ‘bits’.
  • Violations: Just look for assignments to data members. Bitwise is C++’s definition of constness. A member function can’t modify any of the nonstatic members.
  • Issue: Functions that aren't const can sometimes pass the bitwise test.
Logical Constness
  • Logical: A const member function might modify some of the bits in it’s object, but only in way clients can’t detect.
  • Example: Caching a value is an interesting process. The cache may be read-only but it needs to be generated first. It would make sense for us to calculate the cache on first run of the function; but it will fail bitwise constant.
  • Mutable: Mutable allows us to evade the limitations of a const variable. Mutable variables can be changed in either const or non-const functions.
Duplication
  • Multiple Functions: The problem with const functions can be code duplication. You can end up duplicating identical code for both const and the non-const function.
  • Approach: We could instead, call the const version of the function, cast away the “constness” of the object and return it from the non-const version.
ConsteXPR
  • Compile Time: Even const variables aren't necessarily created at compile-time even though their value is known. Instead space may be allocated at run-time.
  • Constant Expression: We can actually declare a variable as a constant expression which is evaluated at compile-time. It can therefore be used as constants to determine array sizes etc.
After going over a few of the points in the lesson, it was time for a mini-practical session. Once again, we had to take what we had learnt from the current lesson. The guide from the practical was as followed...

  1. Create a class called GameObjects that stores a vector of GameObject.
  2. Create two functions (one const) that return the GameObject at pos [i] as a reference.
  3. Create a function in GameObject that takes another GameObject& as const.
  4. Return true if the object being tested has more health than the other.
  5. Create a function that takes two GameObjects& as const and returns the one with least health.
I found this particular task fairly tricky, due to my lack of knowledge in this area. I had only managed to complete task 1 and added the code snippets provided from the lesson slides. When the answer was revealed to us about 15 minutes later however, it made some sense to me as to where I went wrong.

Networking

Networking
  • Communications: Networking covers the concept of using multiple hosts/nodes to share data with each other. They can keep each other updated on any game logic changes.
  • Ease: Actually getting computers to talk to each other is a fairly easy task, but making sense of the bits sent/received isn’t.
Interwebs
  • Transport: The internet works by encoding packets of data and transporting them across the internet. A session can be thought of the mechanism for allowing the two to communicate.
  • Host Layers: Host layers are concerned with software, where the media layers are focused on the physical hardware responsible for transmitting data i.e. bits.
Protocols
  • Protocols: The internet sends data via protocols. Two of the most common in games is UDP and TCP/IP. They both allow data to be sent over the internet. But offer radically different approaches to how they accomplish this.
  • TCP (1): Transport Control Protocol; Creates a connection via two hosts. TCP is a guaranteed full duplex protocol. The connection is reliable and ordered.
  • UDP (1): User Datagram Protocol; Data is simply sent as packets. The receiver listens for these packets. Does not guarantee delivery of data.
  • TCP (2): Forms the backbone of the internet. It’s a reliable connection based protocols. I t forms a connection between two nodes.
  • Reliability: TCP provides reliable and guaranteed delivery of data.
  • Ordered: The data sent by TCP will be received in the same order.
  • Performance (1): All this extra error checking involves the receiver acknowledging receipt of complete and non-corrupt packets. i.e. ACK. Corrupt packets causes a queue to resolve the out of order issues.
  • IP: IP sits beneath the TCP stack. There is no concept of connections, packets are just passed from one computer to the next.
  • Duration: IP passes the data between nodes, but the route is unknown.
  • Recipent: There’s no guarantee that the packet is ever received by the intended host.
  • Routing: IP will do it’s best to get data from a to b via any possible route necessary. This means data can arrive out of order if the 2nd packet takes a different route to the 1st. It’s like a postal system.
  • UDP (2): Just like TCP it’s built on top of IP. However, it doesn’t provide layers of complexity and features. It’s a thin wrapper over the IP protocol.
  • Delivery: There’s no guarantee of delivery, nor attempt to confirm it.
  • Split: If the data get’s split into multiple packets, you won’t know.
  • Performance (2): Because it’s lightweight it’s quick but the lack of guaranteed delivery, or the ordering of packets make’s it an unreliable connection protocol.
TCP Vs UDP


  • TCP Innards: TCP is a stream protocol, you just write bytes to a stream formed by the connection. TCP breaks your stream of data into packets before sending them via the IP protocol.
  • Queues: This actually means there needs to be a queue for sending and buffer for receiving.
  • Delay: This process causes a delay, we can disable it, but TCP is still slow.
  • Guidance: Never use TCP for time critical applications. Real-time requirements dictate the usage of UDP. The truth is probably UDP and TCP connections should be used in tandem. Send real-time data via UDP, everything else by TCP.
IP Addresses
  • Hosts: Every networked PC has TCP/IP installed which provides an IP. The IP address uniquely identifies the PC’s ‘address’.
  • Classes: Some ranges of IP addresses are for private use only and the others for public i.e. internet.
  • Routing: A series of routers are responsible for forwarding packets to these IP addresses. Consider your IP address as your mailbox, with IP responsible for delivering items.
  • TCP Innards: The IPv4 address is a 4-byte number. IP addresses are normally in decimal format. It’s formed of two parts. The network ID and host ID.
  • LAN: Local area networks sit behind a router, that serves data from and to the internet.
DNS
  • Domain Name System: Clearly, even though every host has an IP address, we don’t browse the web using those IP’s. Instead we resolve an alias that points to that IP.
  • Resolve: The DNS servers around the world are responsible for converting a human readable name to an IP address.
  • Abstraction: It’s clear that this layer of abstraction is of benefit. Imagine trying to remember the IP addresses of all your favourite sites?
Once the theoretical side of the lesson ended, we moved onto the main practical of the lesson. Our task was to create our own Chat Server using Visual Studio 2013. Although my set-up was when following the instructions was fine, it came up with compiler errors nevertheless. There were also sections in the code where we would need our own input to make it work. Sadly, before I started to try and fix the errors, I ran out of time in the lesson.

Friday, 22 January 2016

Low-Level Programming_Post12

Low-Level Programming: Post 12 21/01/2016

January 21st 2016 is the date of the thirteenth lesson on Low-Level Programming.

The reason as to why I skipped a post last time out on December 10th 2015, since that was the date of the twelfth lesson on Low-Level Programming, was due to the extremely low attendance in that lesson, which was most likely due to the coursework deadline for this course being on the same day. This resulted in the lesson being cancelled and we were sent on our ways.

Below are the points as to what we were taught in the lesson...


  • Template Functions/Classes: How to implement template functions and template classes.
  • Generics: Templates, what are they and how do they work?
  • Compiler Directives: How to implement template functions and template classes.
Directives

Directives
  • Compiler Instruction: Directives are designed to dictate the compiler’s behaviour and do not form part of the language’s syntax.
  • C++: C and C++ support a simple macro pre-processor. Lines which start with the # symbol indicate a directive.
  • Directive: They are responsible for ‘directing’ the compilation process.
Pre-Processor
  • Pre-Processor (1): The pre-processor is responsible for substituting these expressions into text that alters the source code that’s about to be compiled.
  • Abilities (1): They can replace tokens in the text, insert the content of other files into the source file or even remove lines of code that may otherwise had been compiled.
  • Placement (1): Pre-processor directives can appear anywhere in a source file, but they apply only to the remainder of the source file.
  • Supported #: The following pre-processor directives are supported; #define, #error, #import, #undef, #elif, #if, #include, #using, #else, #ifdef, #line, #endif, #ifndef, #pragma.
  • #Define/#Undef: Used to define or un-define a pre-processor tag.
  • #Include: Includes the source from another file.
  • #Pragma: Allows machine/OS specific code which retains overall compatibility.
  • #If/#Else/#Elif: IF / ELSE style clauses for the pre-processor.
  • #Ifdef: Checks to see if a tag is defined.
  • #Error: Emits a user-error at compile time and fails compilation process.
  • Pre-Processor (2): The pre-processor is responsible for substituting these expressions into text that alters the source code that’s about to be compiled.
  • Abilities (2): They can replace tokens in the text, insert the content of other files into the source file or even remove lines of code that may otherwise had been compiled.
  • Placement (2): Pre-processor directives can appear anywhere in a source file, but they apply only to the remainder of the source file.
Some Guidance...
  • Pre-Processor: Do not use #defines. They are text substitution and complicate debugging.
  • Macros: Do not use macros, they start with #define and often lead to complicated bugs.
  • Platform: Do use them for platform specific code.
Templates

Generics
  • Templates: As discussed previously it’s possible to write code that operates independently of the type it’s working with.
  • Blueprint: A template acts as a blueprint for creating a generic class of function. The STL is based around this principle.
  • Type Safe: Even though this is generic programming, the type safety is maintained when using templated code.
Template Code
  • Duplication: Function templates allow the creation of functions that can adapt to the type or class being worked with, without repeating the code for each type.
  • Parameters: This is achieved through the use of template parameters. These are special types of parameter, but the class can use them like any regular parameter.
  • Compile-Time: As discussed last year, it’s important to understand that the template code is evaluated at compile time.
  • Function Templates/Declaration: There are two ways of declaring a template function, the difference is the keyword. There are semantically identical.
  • Syntax: Functions are one of the most common usages in generic programming i.e. the idea that a function can use the same code on any given type.
  • Interface: When we use templates the interface is implicit. The templated object’s interaction determines it’s interface even though it’s type is unknown.
Classes
  • Template Classes: Just like templates, it’s possible to create templated classes. The typename defined can then be used throughout the class’s functions and variables.
  • Member Definitions: The advantage of the template class over template function is due to the fact member variables can be stored in the class of type T.
  • Type Specification: When using a class that utilise templates, it becomes necessary to provide the type we want to use with the class via the <> brackets.
After the first few slides, we were given a practical task. It was essentially what we had just learnt in the lesson. The stages in the practical were as followed...

1. Create a function called min that takes a template argument named T
2. The function will need to take two args of type T
3. Set the return type as type T
4. Return the result of the two args added together.
5. Test by printing to result to the console.
6. Create a function called max that determines the greater of the two.
7. Create a function called create that returns a newly allocated block of said type. Hint: the function does not require any parameters.

Unfortunately, due to not having enough experience and knowledge in this field, I didn't get very far in the task. Although I managed to add up the args together and show it, it was via a different method.

After a 5 minute break, we resumed the theoretical side of the lesson.

Varadic Templates
  • Arguments: Wouldn’t it be good if; templates could take a variable number of arguments.
  • C++11: C++ 11 standard provides the ability to use variadic templates, which allows this. Logic is resolved at compile-time.
Explicit Interfaces
  • Generic Code: Using templated functions allow the usage of the same code regardless of the types being used.
  • Specialization: Occasionally, it becomes necessary to handle certain types in an alternative way. We can explicitly define this in the codebase, thus creating an explicit specialization.
  • Partial or Full: If a class template is specialized by a subset of it’s parameters it’s partial otherwise it’s known as full specialization.
Inheritance
  • Template Classes: A template class that inherits from another template class. Inheritance from a template class. A template class that inherits from a non-template class. A template class that uses multiple inheritance.
  • Member Definitions: The advantage of the template class over template function is due to the fact member variables can be stored in the class of type T.
  • When using a class that utilise templates, it becomes necessary to provide the type we want to use with the class via the <> brackets.
After finishing the theoretical side of the lesson, we moved onto another practical session. This time, we had to create a UML diagram showing all the classes and their relationship to each other in the form of the game Snake, which was one of the parts of the assignment we were tasked to do.

I listed down all the features in the Snake game, such as the player, the walls, the points and so on and then extended it by adding the variables in each of their respective classes. I didn't have enough time left to connect them together, however.

Thursday, 3 December 2015

Low-Level Programming_Post11

Low-Level Programming: Post 11 03/12/2015

December 3rd 2015 is the date of the eleventh lesson on Low-Level Programming.

In a case similar to last week, we started the lesson showing, from the bullet points, what we were going to learn in the lesson. The reason as to why I stated that this lesson is very similar to last week's lesson is that, although there were some bullet points, there wasn't a lot that we were going to be taught today.

Below are the bullet points and what we covered in the lesson today...

  • Operator Overloading: What is Operator Overloading and how can it benefit us?
  • Function Pointers: How do we utilize function pointers?
  • Delegate Functions: What's a delegate function and how do we use them?
Overloading
  • Functions: It's possible to overload functions, we do this by altering the parameters on the function signature.
  • Operators: All objects and classes have a number of operators. These range from constructors through to less than or equality comparisons.
  • Overloading: The compiler where possible will generate simple operator functions. However, these can be overridden or overloaded.
  • Syntax: Overloaded operators are functions and like a normal function, they have return types and parameters.
  • Copying: One example of using operator overloading is when a class allocates memory on the heap.
  • Assignment: When the object is assigned, there's a need to ensure we do need a deep copy of all those heap values and not point to the same ones.
  • Casting: By overloading the construction operators, we can enable implicit and explicit conversions between differing types.
  • Conversions: Before making conversions between different types, it's important to make sure the conversion is logical as to avoid confusion.
  • Equality: One of the most common usages of operator overloading is the equality operation ==. We overload the room equality to do a string comparison on it's description.
  • < Operator: Remember that the STL uses the less than operator for maintaining it's sort order when using associative containers.
  • Operator += & -=: Depending on an object's definition and structure, it may be valid for it's value to increase or decrease.
  • Restrictions: The operators :: (scope resolution), . (member access), .* (member access through pointer to member), and ?: (ternary conditional) cannot be overloaded.
  • Non-Existent Operators: New operators such as **, <>, or &| cannot be created.
  • Common Functionality: The overload of operator -> must either return a raw pointer or return an object (by reference or by value), for which operator -> is in turn overloaded.
  • Precedence: It is not possible to change the precedence, grouping, or number of operands or operators.
  • Short Circuiting: The overloads of operators &&, ||, and , lose their special properties: short-circuit evaluation and sequencing.
Function Pointers
  • Functions: The function identifier is a constant pointer to a function. The pointer holds the address in memory where the code for the function resides.
  • Dereference(): When the function is called via the () operator, execution jumps to the address of the function via it's constant pointer.
  • Syntax: Knowing this, it becomes possible to store the address of a function in a variable, but it's a pretty hideous syntax.
  • Parentheses: They're important due to precedence rules in the language. In this case it would be seen as a function that returns a pointer to an integer.
  • Ptrs to functions: Storing pointers to functions mean we have to dereference the pointer. There are two ways of doing this: Implicit calls and Explicit calls.
  • Callback Functions: Passing a function pointer through to another function is possible. It just needs to be added as an argument to the function signature.
  • Decltype: Evaluates the type of an expression. We can use this to cheat on our declaration of function pointers as a type.
  • Compiler: The compiler evaluates the expression for you and substitutes it's reference when compiling.
  • Auto Keyword: When storing a Ptr to a function inside the code base, it's preferable to use the auto keyword to prevent the convoluted syntax involved.
  • Decltype of Auto: It's even possible to decltype an auto defined variable. However, this may make it less clear when reviewing the code.
  • Factories: We can make use of function pointers when creating a factory class.
  • Each class has a lookup ID that's stored in the pair. The second part stores the function pointer that's responsible for creation.
  • Pointers: Assuming the signature of all the action handling functions were the same, why not use function pointers instead.
  • Predicates: Predicates are another example of function pointers and are used throughout the STL and it's containers and algorithms.
  • Static Predicates: By implementing a static predicate inside a class, it can be provided to the algorithms.
  • Lambda Functions: Lambda or local functions can be used, again these are passed through as a function pointer to the algorithm being utilized.
  • Classes: It's possible to have a pointer to a member function. In order to use these, we need an object and some new syntax.
  • This Pointer: In essence, in order for member functions to be accessed via pointers, they need access to the pointer.
  • Normal Pointer: A normal pointer can only store one address. This is why it's not possible to have a direct pointer to an object and the function.
Functors
  • Functors: Function objects or functionals are object + (). A functor is an object that can be used with () in the same way a function is called.
  • Functions: This includes normal functions, pointers to functions and class objects where the () operator is overloaded.
    • STL: The STL makes extensive usage of function objects, the most obvious example is when a predicate is required.
    • An Object or a Function: It's an object that acts as a function. One of the best usages of a functor is the storage of state.
    • Struct: Define a struct that we will use as a function.
    • Overload the (): Overload the () operator, this way we can call the class as a function and it will perform the code in the () operator.
    • State: This struct is no state. We could easily add member variables to it, if they would help in the function's processing.