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.

    Thursday, 26 November 2015

    Low-Level Programming_Post10

    Low-Level Programming: Post 10 26/11/2015

    November 26th 2015 is the date of the tenth lesson on Low-Level Programming.

    Keeping with tradition, we were shown an overview of what we were going to learn today. From the bullet points, we were only going to be learning about three (more) types of patterns. Below are the bullet points in more detail...

    • Observer Pattern: What is it and how does it work?
    • Component Pattern: What is it and how does it work?
    • Type Pattern: What is it and how does it work?
    Before we began looking at the patterns, we were given a practical task. The task was to create two Pseudocodes, one for the 'Factory' that creates the GameObjects, which should have consisted of the Player, Three enemies and a Boss, and the other for an Object Pool that creates the enemies. It was a simple task, simply creating a class for, except the player, the enemies. We decided to make a separate pool for the boss as well.

    After the 15 minute practical session, we moved onto the lesson slides again, resuming with learning about Observer Patterns.

    Observer: Define a one-to-many dependency between objects so that when one object updates, others are aware
    • Java & C#: Model-View-Controller architecture utilizes the observer pattern and is built into Java and C# even supports it via the event keyword.
    • Announcement: In this pattern, one part of the code-base will announce an event, this event can be processed elsewhere.
    • Coupling: An event based system allows us to reduce the level of complexity.
    • Achievements: The achievement system used in games is event triggered, rather than pollute the code where the event happens, we notify observers.
    • Register: It's now possible to register observers with our observable object.
    • Events: The observable objects can then send events to all it's observers without any understanding of it's intention. We've maintained low coupling.
    • Performance: We're simply iterating through a list of observers and calling a virtual function to handle the event.
    • Dereferencing: There's an obvious overhead associated with virtual function calls, but it's fairly minimal, especially as we don't need to "poll" or couple.
    • Observers: Care needs to be taken as the thread is paused whilst processing the observers update functions.
    • Allocations: Best practices dictate we reduce the number of allocations during game time, in this case add observers at load time.
    • Linked List: Instead of using a vector of pointers, it's possible to create a linked list using observer nodes, with each one pointing to the next.
    • Multiple Observer: Using a linked list, we can only have the observer itself observing a single object at any given time.
    • Nodes: To circumvent this problem, we can use the concept of a node, which has a link to the next node and a pointer to the observer.
    • Pool: The nodes can then be pooled together, saving on allocations and deallocations. Remember to give them a bool flag for reusage.
    Component: Allows a single entity to span multiple domains without coupling the domains to each other
    • Game Objects: In games, it's not uncommon that objects need to interact with the rendering, update and input systems i.e. multiple domains.
    • Coupling: In a traditional update method, it soon becomes obvious that code between the domains is coupled, with the coder needing an understanding of each component.
    • Divide and Conquer: Let's resolve the issue by dividing the domains in to their own respective managed components.
    • Candidates:
    1. An Input Component.
    2. An Audio Component.
    3. A Rendering Component.
    • Result: The three components are decoupled and can be managed independently. Though it's likely they will need some awareness of each other.
    • Reusable: Components are now reusable and we can prevent objects from having complex inheritance structures.
    • Decoration: Decorations i.e. static objects with no dynamic updates are now composed of graphic components.
    • Composition: Prefer composition over inheritance.
    • Domains: This illustrates the definition in which it's stated that a single entity i.e. zombie spans multiple domains and remains decoupled.
    • Large Classes: When the functionality in a class is becoming large and complex, it may be a good time to implement components to reduce it.
    • Decoupling: If there's a desire to keep a class loosely coupled, then the component design pattern allows this.
    • Common Functionality: If a variety of objects are utilizing similar functionality but inheritance doesn't fit correctly, again components can be used.
    • Complexity: Utilising this design pattern makes the object more complex. It has a number of components, all of which need initialising.
    • Communication: Another consideration is cross-communication between the domains, how do you tie them together if they need each other.
    Type: Allows the flexible creation of new 'classes' by creating a single class, each instance represents a different type
    • Inheritance: When designing classes of objects, there is the desire to create subclasses for each kind of similar object.
    • Breeds: Using the Dungeon Death game as an example; last week I mentioned three enemies, most likely only different in base attributes.
    • Subclass: Each subclass has more health than the other, due to the enemies' increased perception of strength.
    • Additional Enemies: For every additional enemy, we end up writing short and annoying classes that only consist of a few lines.
    • Inheritance: Inheritance works in this example, but it means we end up with all these small classes, but there's another option.
    • Composition: Each monster class or enemy has a breed object. The breed object determines how a monster attacks or it's health.
    • Challenges: The ability to override functions to determine behaviour are now not possible, instead the type data is attached to the class.
    • Behaviour: Type patterns are good for defining the data relevant to an instance but are more difficult to encompass different behaviours at different times.
    • States: We could store a state in the type data and then act differently depending on the value stored in the state.
    • Data Files: With more complex solutions, behaviours can be constructed from data files. This way, the behaviour is completely removed from the code base.
    • Type: The breed object molds or defines a monster's type, hence the name of the pattern i.e. type.
    • Instances: Instances of the monsters which use the same breed object are conceptually identical and will act in the same way.
    • Data: The instances store the data required per breed; this is what get's altered when the monster takes damage.
    • Usages:
    1. You don't know what types you will need up front, just that you require multiple types.
    2. You want to be able to modify and add new types without having to change code.
    After the end of the rather short lectural side of the lesson, we were shown some questions that other people on the course asked about the assignment. Two of the three questions were about some of the rules in the BlackJack game, in which the tutor said we didn't NEED to implement it, but implementing it would get us higher marks. The other question was about the documentation needed for the assignment. It says that it should cover our design decisions and utilise UML, Pseudocode and diagrams where necessary, basically saying why we design the game(s) like we did and how to implement it.

    After that, we then moved onto the second practical of the lesson. Carrying on from the first practical earlier on, we had to implement the Pseudocode from earlier, as in, creating the classes for the enemies. Sadly, we only managed to create the classes and ran out of time to do any more work on it.

    Friday, 20 November 2015

    Low-Level Programming_Post9

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

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

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

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

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

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