Thursday, 12 November 2015

Low-Level Programming_Post8

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


November 12th 2015 is the date of the eighth lesson on Low-Level Programming.

Before the lesson officially began, we were informed of a new approach to have we would have our break (time off). Instead of having a full 15 minutes break after the lectural side of the lesson like we would normally do, instead, we had two 5 minute breaks and one 10 minute break. This was perhaps due to having nearly two hours of consistent teaching to take in, whereas in the new method, we had to take in around half an hour each, which I felt was better, as we could also look back at potential notes taken and take it in generally.

After becoming aware of the new break system, the lesson officially began. As per usual, we began with being shown the points that we were going to learn today and the components/features that come with them. The main points are as follows...
  • Big 'O' Notation: How we define and describe complexity of algorithms.
  • Design Patterns: What are they & Examples.
  • Auto: The Auto keyword and how it works and when to use it.
  • Windows.h: Do not use (in assignments) and how we can sleep a thread instead, poll for input and clear the screen.
Big 'O' Notation ('O' stands for Order)
  • Complexity: Refers to how the number of inputs impact the processing time.
  • Algorithms: Focuses on Algorithms.
  • Models: There are mathematical models and computing science, plus various others.
  • Symbolism: Big O Notation is used to describe the asymptotic behaviour of functions i.e. how fast a function grows or shrinks.
  • Letter O: The letter O is used because the rate of growth of a function is called it's order.
  • Orders: When we examine our algorithms we can describe the growth rate of our function in "order of".
  • T(n) = 0(n^2): In this instance our function T grows at the order of n^2 i.e. the growth rate for each input for this function is exponential.
  • Computing Science: When we talk about Big O in computing science, we're referring to how complexity scales depending on the number of inputs.
  • Arrays: For example searching through an array has a complexity that's linear, as we need to potentially check all items stored in it; O(n).
Orders of Magnitude
  • Magnitude: In asymptotic analysis, we focus on the order of magnitude of a algorithm rather than the actual values themselves.
  • Abstract: Conceptually the amount of time of processing an algorithm takes is unknown, but orders allow us to show how it scales.
  • Big O: Big O notation is the way we express orders of magnitude when discussing the complexity of an algorithms for n items.
  • Traditional Usage: When two values are within an order of  magnitude of 1, they're within a factor of 10 i.e. 10 and 20 but not 10 and 200.
  • Notation: In Big O, the n defines the order, the higher the order of n, the more aggressively the complexity of the algorithm scales.
  • Algorithms: Often, you'll see references to algorithms when discussing a function's complexity.
Algorithms
  • Meaning: It's a set of rules that govern a series of calculation of problem-solving solutions. Sometimes it's abstractly considered a recipe.
  • Computing: Simply, we can think of each line, operation or function in our program as an algorithm. Rules to tell a computer what to do.
  • Unambiguous: Algorithms are unambiguous, each step does not lend itself to interpretation i.e. Add X to Y and return the result.
Constant Expression
  • Constant Expression: How do we represent a function or algorithm that regardless of the number of inputs provides us with a constant level of complexity?
  • Element Access: Accessing an element directly in a vector has constant complexity; it's irrespective of the number of elements contained in it.
  • Time Taken: The time taken to retrieve the element has no relationship with the number of items in the array, hence, it's constant Big O notation.
Linear
  • Linear Expression: How do we represent a function or algorithm that's complexity increases in line with the number of items being processed.
  • Linear Searching: Searching through a vector is an example of linear complexity. For every item added, we need to then potentially loop through it.
  • Time Taken: The time taken to retrieve the element has no relationship with the number of items in the array, hence, it's constant Big O notation.
Polynomial
  • Polynomial: How do we represent a function or algorithm that's complexity is directly proportional to the square of the size of the input set.
  • Selection Sort: A very simple and easy way to implement algorithms that sort numbers by their lowest value has an exponential complexity.
  • Complexity Growth: The deeper nested the algorithm, the higher the polynomial degree i.e. n^2, n^3, n^4 etc.
Exponential Big O
  • Exponential: An algorithm whose growth doubles with each addition to the input set. The growth curve is shallow and then rises rapidly.
  • Recursion: Recursive functions that need to traverse through a series of data inputs, cause a doubling of processing for each additional input.
Logarithmic
  • Logarithmic: The opposite of exponents. This time, the larger the input set, the smaller increase in the algorithms processing time.
  • Associative Containers: Last week, we spoke about how sets and maps use forms of binary searches to locate the item in the container.
  • Complexity Growth: Looking at the graph we can clearly see that working with a bigger data set has significantly less impact than other algorithms.
STL Search Algorithms
  • Linear: Standard search used when traversing containers using find.
  • Binary Tree: How does Binary Tree searching differ?
  • Red Black Tree: Associative Containers.
Linear Search
  • Find: One of the most used algorithms in the STL is std::find or std::find_if, both of which are linear in complexity.
  • Distance: It is can be thought of as up to linear complexity for the distance of the container being searched (first to last).
  • Best Case: In the best case scenario, the first element we check is the one we want, which would imply a constant complexity, but we Big O deals with the largest case.
Binary Tree Search
  • Associative Containers: The containers such as set and map provide an alternative search algorithm based on binary tree searches. The key in the container is stored.
  • Logarithmic: When we look at the complexity, we find it's logarithmic in nature.
  • Linked Lists: They work similar to linked lists but provide the efficiency of search in an ordered array. Each node points to the nodes left and right.
Verb Tree
  • Finding a Verb: To find the verb 'up', we traverse the tree, simplifying the search domain until we converge on our solution.
Red Black Tree Search
  • Balanced Binary Tree: Red Black Trees are a form of self balancing binary search trees designed to help the tree maintain it's logarithmic nature.
  • Node Colours: Each node in the tree is coloured, either red or black, whilst preserving the mantra, that the deepest node is not longer than twice the shortest.
  • Leaf Nodes: All nil nodes at the end of the tree will be coloured black and both children of a red should always be black.
  • Height: Every path from a node n to a descendent leaf has the same number of black nodes. The black height is denoted as bh(n).
  • T(n) = 0(log(n)): These properties or rules guarantee that the tree has a height of O(log(n)), since the order is a function of the tree's height.
  • Root Node: The root of the tree is always black, with no adjacent red nodes in the tree allowed.
  • Black Heights: With these rules in place, the root is at least h/2(each red node requires two black nodes). A subtree node has at least 2^bh(v) - 1 nodes.
Design Patterns
  • Software Architecture: How we design our systems and engines.
  • Patterns: What are Patterns?
  • State Pattern: What's the State Pattern?
Software Architecture
  • Good Design: Good design can encompass many ideals and concepts, but normally illustrates itself when adding new functionality is seamless.
  • OOP: Fundamentally, this is why OOP design continues to be the standard when building your codebase.
  • Coupling: Remember, if you can't understand one part of a program without understanding another, you have coupling.
  • Performance: All of our design decisions to make code more manageable aren't free.
  • Balance: We want a nicely designed codebase which is easy to understand, debug and extend over it's life time, but also quick.
  • Design Patterns: Design patterns are all about helping us to provide sensible interface and solutions to meet our desirable software architecture.
State Pattern
  • State Machines: As discussed last week, objects in the game world including the game itself can be broken down to it's constituent states.
  • Usage: When managing the game state for your object is becoming convoluted, now's a good time to use the state pattern.
Multiple States
  • Concurrent States: You may find that an object in your game, has multiple states unrelated to each other, or require loose coupling.
  • Hierarchical States: It's inevitable that after implementing a number of states that there will be common behaviours between some of them.
Pushdown Automata
  • Stack: It sometimes makes sense to record a series of states that have happened in order, for this we can emulate the stack principle.
  • Convenience: When transitioning between the character's state, it makes sense that we might want to revert to the last state before the current.
  • Multiple States: Store a current and a stack of previous states.
States
  • Limited: States are considered fairly limited. For more complex AI solutions, we have behaviour trees, neural nets and pathfinding algorithms.
  • Behaviour Changes: If the object being modelled behaviour changes with respective to some internal state, then states are still valid.
  • Distinct Options: The object can be easily categorized into one of several small distinct states.
  • Input Response: The entity responds to a series of inputs and/or events over time. i.e. input handling, menu screens, pausing text etc.
Factory Patterns
  • Constructor of Objects: A factory is exactly that; it produces or in this case constructs object's of our choosing. Very common in games.
  • Workings: Very simply, you ask the factory for an object of type X and it constructs it and returns a reference of the newly constructed object.
  • Similar Classes: Often our factory will look after the construction of a multiple of classes, that share the same base class.
  • Parameters: In order to construct the objects, the factory either needs to have sane construction defaults or allow the user to specify them.
  • Storage: Whilst the factory is busy constructing objects, it can use specific pools and even allocate them to a central storage location.
  • Return Type: Depending on the type of storage used and whom owns responsibility for the destruction of the object, you may get the actual object or a reference to it instead.
In one of the main points, I mentioned that we were told NOT to use the Windows.h file in our assignments. I will now display a guidance as to why we shouldn't use it and similar methods...
  • It bloats your codebase and pollutes namespaces ,defines etc (Lean and Mean config is available).
  • Using the functionality included will tie your program into a single platform, you lose the benefit or portability.
  • Stay away from the use of system commands (system ("pause") etc).
We were, however, given other features and methods that we could use in our assignments to help us.

C++11: Sleeping a Thread!
  • Sleep Function: Instead of using the system function provided by windows to sleep, let's utilise the new standards version.
  • Thread: We in effect stall the thread for a given amount of time. Once the time has elapsed, the thread resumes.
  • Literals: C++14 even allows us to specify literals to determine the sleep unit.
Storing Inputs
  • Windows.h: Windows provides some convenient ways of polling for input, but how can we implement our own 'portable' alternatives.
  • Polling: Instead of running a function that handles the check and the actions, we could store the inputs status in an 'input' class or similar.
Cleaning the Console
  • System: We could use system commands to do this for us, but i've made a point of disallowing them (slow and non-portable).
  • Alternative: Quite simply, why not just print a series of new lines to the screen, not the most graceful solution, but effective.
  • Platform Independent Code: Or we could attempt to write two different versions of console clearing modes depending on the platform we're running on.
C++11: Auto
  • Type Inference: C++11 introduces the Auto keyword. This keyword lets the compiler auto-deduce the type.
  • Shorthand: Provides us with the ability to declare variables efficiently and more quickly. i.e. iterators are longhanded, auto resolves this.
  • Usability: Only use auto when the type inference is obvious and it doesn't obfuscate the codebase.

Friday, 6 November 2015

Low-Level Programming_Post7

Low-Level Programming: Post 7 05/11/15

November 5th 2015 is the date of the seventh lesson on Low-Level Programming.

At the beginning of the lecture, we were given/shown, as per usual, an overview on the lecture for today. The following bullet points covered what content we were going to be shown today and what we would take away from it.
  • Pointers and Containers: Raw and Smart Pointers and their usage in Containers.
  • Containers: Sets, Maps, Multi-Sets, and Multi-Maps.
  • Algorithms: Find, Find_if and Binary Predicates.
  • State Systems: Game States and how a system might compose of them.
Unlike some of the previous lessons, there wasn't anything particularly 'unique' at the beginning (such as an assignment overview, Dev blogs reviewing and how it's marked etc). Instead we went straight into the lesson for the day.

On the first bullet and it's contents, we learnt about Pointers and Containers. We have already gone into some depth on Pointers before and it's varieties (Smart_Ptrs, Unique_Ptrs, Shared_Ptrs and Weak_Ptrs). However, unlike in previous blog posts where I move onto the next point, I am going to make an exception to this one, since it also goes into containers, vectors and how they seem to link together.

Vectors and Ptrs
  • Containers: It's acceptable and common to have containers of pointers. These can be traditional raw, unique or smart.
  • Considerations: With a Vector, the pointers are stored contiguously in memory.
  • Heap: They're on the heap, but the default allocator has made the decision on their location.
  • Cleanup: The Vector will free the memory it's allocated for the array contents, but any manual heap allocations need to be freed by you.
  • Elements: When you don't want to store copies of an object's array or pointers are a good choice.
Vectors and Unique_Ptrs
  • Unique Ptrs: Storing a vector of unique ptrs allows us to resolve the deallocation issues.
  • Ownership: Remember the pointer is unique and will remove the data on the heap regardless of any other pointers or refs.
  • Memory Location: Much the same as raw pointers, we just have the wrapper that provides us with deallocation.
Vectors and Shared_Ptrs
  • Shared Ptrs: Sometimes we might want to store a container of reference counted ptrs.
  • Shared Ownership: Multiple reference to the same data can be controlled.
  • Central Storage: It's possible to return a shared pointer that can be used elsewhere in the game, but also stored in a central container.
Associative Containers
  • Associative: At the moment the container types we've been looking at are all unsorted with no association between the data orders.
  • Key Values: The key which stores the associated value is used to maintain the sort appropriate to the container.
  • Elements: The key values are how we can look up the elements in the container.
Set
  • Sets: Containers that store unique elements following a specific order.
  • Unique: Sets only allow one entry per unique key.
  • Key: The value of the object being inserted into the container also dictates the unique key.
  • Sorted: The items are sorted using a comparison object, by default this is the less than operation.
  • Insertions: Sets are good at insertions, regardless of the location the new object is being added, unlike vectors and deques.
  • Binary Search Tree: Underlying principles are based on binary search trees.
Set Vs Vector
  • Ordered: A set will always retain it's order, a vector will need to be sorted to guarantee it's order.
  • Vector Sort: Sorting a vector can be slow, especially if you need to repeat the process on a frequent basis.
  • Proportional: The time it takes an item to insert into a vector is proportional to the number of items in it. The set is proportional to the log.
  • Initialisation: If you add all the items upfront and then sort one, the performance is negated.
  • Iteration: Faster on a vector than on a set.
  • Set Overhead: Needs to store additional information for tree traversal. Insertions only faster if you're not inserting to the end of a vector.
Find
  • STL: There's an algorithm include that's part of the STL and allows a linear search of a container.
  • Sets: In associative container like sets, they include their own find algorithm that performs logarithmically instead.
  • Usage: You can use either the associative container version of the STL version depending on your requirements. 
  • Binary Search: If you have a sorted vector, you can perform a binary search using lower or upper bounds.
Find_If
  • STL: Much like remove_if which requires a predicate you can use a find_if which needs a unary predicate.
  • Boolean: It takes a single parameter and returns a boolean to determine whether the element should be selected/highlighted.
  • Usage: The associative container does not provide this function, it's in the algorithms section.
Map
  • Indexed Key: Our lookup key is separate from the value stored in the array.
  • Pairs: They use pairs, which has two members, first and second. The first is the key.
  • Set Overhead: Fast insertions and logarithmic lookup times and like set, unique values must be used.
Multi-Set
  • Sets: Work the same as a set. The difference is that the key does not need to be unique, we can have duplicates.
  • Vector Sort: Sorting a vector can be slow, especially if you need to repeat the process on a frequent basis.
  • Search Trees: Again, often implement as binary search trees.
  • Binary Predicate: We can provide a custom sort predicate that will take both objects and perform a comparison.
  • Function Ptr: Basically, you're passing a pointer to the specialised sort function.
  • Operator Overload: Alternatively we can provide an operator overloaded function that provides a custom sort.
  • Clarity: Using the operator overloader could be considered clearer than passing a function pointer through and is automagically called.
Multi-Map
  • Multiple Keys: The Multi-Map allows a separate lookup value to the element. With a Multi-Map duplicate, keys are now supported.
  • Usage: If you need to store multiple instances of objects but need to look them up by a key value, then this is the container. Caches which use hashes are one example.
State
  • Game: In most games, the logic being process is dependent on the current state of the game. (Running -> Jump Button -> Jumping -> Reach apex of jump -> Falling etc).
  • Game Loop: On simple games, you often find that all the logic may be in a single loop i.e. the game loop.
  • Modular: If instead we look at our games as a series of states, we can more easily control what's been updated or checked every update.
  • Specialised: Using states allows us to keep the logic required for updating our objects more succinct and specialised.
  • State Machines: Conceptually the idea of differeing states and transitioning between them is handled by our state machine.
State Behaviours
  • State-Dependent Behaviour: State machines can be used in any part of our game, where the design lends itself well to processing the logic in a series of states.
At the end of the Straight-forward lectural side of the lesson (and once the 15 min break finished), the practical side of the lesson began. The practical once again saw us try and work on the DungeonDeath game. Since I wasn't working alone on the game this week, we had an attempt to change the player to have a unique_ptr, which I think we succeeded at. We were also about to attempt to move the static array of rooms into vectors of levels, but we ran out of time.

Friday, 30 October 2015

Low-Level Programming_Post6

Low-Level Programming: Post 6 29/10/15

October 29th 2015 is the date of the sixth lesson on Low-Level Programming.

At the start of the lesson, we were given, as usual, an overview of what we were going to learn today. The following bullet points are the list of features that were taught in the lesson (including a guide as to how to make the practical from last week work and how it should have been done)...

  • Libs: Last week's practical reviewed.
  • Container: Vectors, Arrays, Linked Lists and Deques i.e. non-associative.
  • Iterators: What they are and how they work.
  • Erase-Remove Idiom: How to search and erase elements in containers provided by the STL.
Before we began working on the bullet points above, there we three 'important pieces of information' given to us.

The first 'piece of information' was on how the lessons were going to be covered from next week onwards. It said that in the three hour lesson(s), one hour will go into the concepts (lecture) and the other two will go into the practicals. We were also told/recommended to go and work/practice on any pieces of work that were provided to us over the past few weeks, since there isn't enough time to cover everything in extensive detail.

The second 'piece of information' was essentially a recap on Shared_Ptrs, Weak_Ptrs, Casting and Implicit Casting. Since we have covered the above points in the past two posts, I won't be going into extensive detail again on them.

The third, and unquestionably the most important 'piece of information' was the assignment brief given to us. It covered the marking scheme and expectations for the first part of the assignment. It goes as follows...

  • 75% Portfolio: Portfolio of Tasks, Assignments and Practical Work.
  • 40& Exercise One: 40% of the 75% for this one, with the instructions on Blackboard.
The next part covered the deliverables necessary for the assignment...
  • A Single Executable Running.
  • A Menu System.
  • And the Three Games Required.
  • The Three Games listed above are Blackjack, Hangman and Snake.
The most crucial part of the brief was perhaps the breakdown of the assignment...
  • 10% for the Coding Style.
  • 10 % for the Menu System: Console Based, the System should be the first point of entry into your game.
  • 15% for the Object-Oriented Programming.
  • 15% for Blackjack: Implementing the game and meeting the grading criteria. This game shouldn't pose too many problems as it's rules are simple.
  • 20% for Hangman: Should be trickier than Blackjack but still achievable.
  • 30% for Snake: The trickiest game of the three, hence it carries more marks. At least attempts at marks are awarded for coding design decisions.
The last part of the brief was a general guidance on how to work on the assignment...
  • Console: Don't focus on graphics; this assignment is all about code design and OPP decision making. I.e. Correct usage of inheritance and memory.
  • Try: Do try to complete all three game. Even if the game isn't fully working, there are marks for the design of the games.
  • Easy Marks: Just following the Coding Style gets you 10%, not to mention the Menu System another 10%.
  • Tutorials: Whilst the tutorials won't tell you exactly how to resolve all the gameplay mechanics, you will get the chance to work with the elements needed to complete the task.
  • Attendance: Skipping lectures and tutorials will do you no favours in the long run. It's the opportunity to practice the concepts.
After the assignment brief, we were given a guide as to how the practical from last week's lesson should have worked. I managed to get most of the instruction guides. They are as follows...
  • Create a New Project.
  • Select Console Application.
  • Do NOT include two 'additional options'.
  • Open File in File Explorer.
  • Copy 'Libcaca' (name of project) into project.
  • #include 'caca.h' -> Error.
  • Go into Project Properties.
  • Additional, include dependencies/directions.
  • #include 'caca.h'
  • #include <iostream>
  • Go into Project->Linker->All Options.
  • Additional Library Directions.
  • X86 -> Debug.
  • Full Stop, not Comma.
  • Add Void ShowMessage(); before Main.
  • Add ShowMessage(); IN Main.
Now that the parts before on what we were going to learn finished, we started on learning on the bullet point features. As it always is, I will not be going over past features (in this case, a basic Vectors recap).
Vector: Common Operations
  • Iterators:
  • begin & cbegin - Iterator to First Element.
  • end & cend - Iterator to Last Element.
  • rbegin & crbegin - Reverse Iterator to First Element.
  • rend & crend - Reverse Iterator to Last Element.
Vector: Reverse Iterator
  • Reverse Iterator: Reverse Iterators traverse backwards through the array. And they also support const.
Vector: Capacity
  • Size: We can find out the size of the array.
  • Capacity: We can check the capacity of the array.
  • Reserve: We can reserve a block of memory for X objects.
Vector: In Summary
  • Arrays: A good alternative to traditional arrays in C and C++.
  • Performance: Shows efficient and fast performance when iterating through the array.
  • Memory: Contiguous memory usage benefits caching and prevents fragmentation.
  • Memory Allocation: Dynamic reallocation is powerful but also slow, so reserve a reasonable amount of space up front.
  • Iterators: Provides iterators and individual access using [] operator.
Iterators
  • What Are They?: An Iterator is any object that points to an element in a container and has the ability to iterate through the container's range.
  • Operation: Usage of the increment (++), decrement (--) and deference (*) operations.
  • Pointer: A raw pointer can be thought as an iterator, due to it's ability to increment and decrement i.e. pointer arithmetic.
  • Behaviour: A pointer is a type of iterator, but not all iterators work the same way as pointers.
  • Types:
  • Input.
  • Output.
  • Forward.
  • Bidirectional.
  • Random Access.
Erase-Remove Idiom
  • What is it?: A C++ technique to remove container elements that fulfill certain conditions.
  • Loops: It's possible to achieve the same behaviour by using loops to locate elements to erase. but this is considered simpler.
  • C++ Std: Provides us with two algorithms that can be used to remove elements, Remove and remove_if.
  • Iterators: They use iterators to determine the range that should be erased (2x forward iterators).
  • Restructures: In order to ascertain the begin and end iterators, the container has to be re-arranged.
  • Erase: The two remove algorithms do not erase the elements, the result is normally passed to an erase function.
Erase-Remove Idiom: Performance
  • Removal: As remove and remove_if do not actually erase the items, but does move valid data, there must be some sort of overhead.
  • Operation: In modern C++ the elements that are valid are moved to the front of the container. However, the elements to be deleted are not, this means they have an undefined but valid state.
  • Distance: Performance of the algorithm is determined by the number of elements in it, though iteration (linear) should be a constant, the moving of the data is unknown.
  • Erase: Don't forget to erase the results of remove function as the end of the array could be invalid. The erase-remove idiom comes from having to remove first before erasing.
Predicates
  • Unary Predicates: STL algorithms often use predicates to accomplish tasks; such as remove.
  • Return: Simply unary predicates are functions that take a single parameter and return a Boolean.
  • C++ Std:We've seen already that remove_if utilises predicates to determine whether the element should be moved.
  • Iterators: The predicate should take an iterator and deference it for usage within the function.
  • Constant: The dereferenced object should not have any non-constant function called and must not invalidate iterators that the algorithm uses.
  • Index Agnostic: The predicate should also not care about the order of elements tested or their position.
Std::Array
  • Fixed Size Array: STL container that encapsulates fixed size arrays.
  • Functionality: Designed to allow the simplicity and of an array but with support for the std algorithms and iterators.
  • Performance: Has the same performance as a C style array.
Linked Lists
  • Nodes: Linked Lists consist of nodes that link to each other. Forward lists utilise a next node ptr, to traverse both ways you need a prev node ptr.
  • Disparate: The memory is allocated on a node by node basis. No guarantee is made to their location, thus potentially causing cache misses.
  • Agnostic: As long as a node has a ptr to the next item in the list, the items they point to can be of any type.
  • Removal: Removal of nodes causes a deallocation and then an update of the prev node, thus preventing wasted memory space.
  • Dynamic Allocation: Prevents the overheads inherent in resizing arrays dynamically, i.e. allocation and then moves from one location to another.
  • Constraints: You don't need random access to the elements and memory allocation/deallocation is more vital than cache misses.
Linked Lists: In Operation
  • Adding/Removing: You can break the chain and add or remove new items easily.
  • Performance: No overhead other than an allocation or deallocation when working with nodes.
Deque
  • Double Ended: Sequence containers that can be expanded or contracted on both ends (front or back).
  • Functionality: In terms of functionality, they work in a similar fashion to vectors, but they allow manipulation of items at both ends.
  • Adding/Removing: They are efficient when removing or adding elements to either end of the array.
  • Expansion: Like vectors, they can expand or contract and this is performed dynamically.
  • Memory: Vectors guarantee contiguous blocks of memory but deques do not.
  • Performance: They can grow more efficiently than vectors and are suited to tasks with lots of insertions or removals.
Deque: Workings
  • Vector vs Deque: Vectors are contiguously allocated in memory, deques do not operate in the same manner.
When the lectural side of the lesson, along with the break finished, we had to work on the DungeonDeath game once again. Since I was working alone this weak, I was not making a lot of progress. I did manage to, however, add some more rooms to the level and fix the exit game option, since it left a 'This room is blocked' comment when closing the program down.

Thursday, 22 October 2015

Low-Level Programming_Post5

Low-Level Programming: Post 5 22/10/2015

October 22nd 2015 is the date of the fifth lesson on Low-Level Programming.

In today's lesson, we began with the traditional overview of what we were going to learn today, with the first point a review of what we learnt last week (Static and Dynamic Casting). However, before we began the slides, we were tasked to 'peer review' other people's blogs. However, my table only viewed one out of the four dev blogs, as we started discussing about 'Cache Coherency'.

After reviewing the blog, we were given the official marking and expectations for the module. 75% of the marks go towards the portfolio (Portfolio of tasks and Assignments/Practical Work) and 25% of the marks go towards the dev blogs (Tracking of Learning and that the dev blogs are completed on a daily basis).

The following points are what we learnt in the lesson...

  • Memory: Automagic Pointers, Deep Copies, Virtual Destructors.
  • Containers: Structs and Vector.
  • Libraries: Practical Work involving the use of a third-party library.
Similar to last week, I will not be going over what we reviewed (as that is on last week's post). Therefore, I will be starting with Memory.

Memory Management/Class Cleanup
  • Class Memory: When we create classes, there's a good chance it's going to store some sort of data regarding it's state.
  • Inheritance: When we use inheritance, we should ensure our destructor is virtual to make sure all the respective destructors in the hierarchy are called.
  • Dynamic Memory: If we've used the new keyword to store data, we've got chunks of memory on the heap that need cleaning. Don't forget to release it when the class is destroyed.
Shallow vs Deep Copies
  • Object Copying: An object is automatically copied when passed by value, returned from a function, used as an initialiser or provided to the object's constructor.
  • Copy Constructor: Copies the object using the constructor nomenclature.
  • Assignment Operator: Copies the object when the = (assignment) operator is used.
  • Default: The compiler handily generates these default versions for us and they tend to do a pretty good job of copying objects.
Default Copies
  • Value: The default copy operations simply copies the value of each data member to the new object's data member, known as a 'member-wise copy'.
Heap and Copies
  • Shallow Copy: All the shallow copy does is that it creates another pointer that pointed to the same block of memory on the heap.
  • Deallocation: When one of the objects is destroyed, the block of memory being shared is freed on the heap, leaving the copy with a dangling pointer.
Smart Pointers
  • Smart Pointers: There's a lot of responsibility on the programmer to make sure that memory is released correctly; but to make life easier, smart pointers were invented.
  • C++11: With the recent standard, three new pointer types were added to make working with pointers easier. Auto_ptr is now deprecated as a result.
Unique_Ptr
  • Common Usage: A unique pointer is probably the go-to pointer when using smart pointers.
  • Performance: They are the same size as raw pointers and for most operations they execute the exact same instruction set.
  • Guidance: If a raw pointer is suitable for your program, then it's a reasonable assumption that a unique_ptr also is.
  • Exclusivity: A unique_ptr is exclusive in it's ownership. It always has ownership of the data it points to. Moving from one unique_ptr to another transfers the ownership.
  • Copying: A unique_ptr is exactly that. You don't want two unique_ptr's pointing to the same resource. Hence copying of them is disabled.
  • Why?: When a unique_ptr is destroyed it automatically deletes the memory it points to i.e. dangling pointers.
  • Implicit Conversion: You can't implicitly convert pointers to smart pointers. You need to construct the auto_ptr explicitly.
  • Changing Ownership: We can do this using the reset function on the auto_ptr. Whenever you want to change the smart pointer is managing, use reset.
  • Moving Ownership: We can also change ownership between two unique_ptrs.
Shared_Ptr
  • Dynamic Memory: The lack of garbage collection in C++ is one of the hardest hurdles for new programmers, but shared_ptr allows us the same behaviour.
  • Lifetime: Using shared_ptrs an object's lifetime is managed through shared ownership. No one shared_ptr owns the object.
  • Reference Counted: Instead the shared_ptr tracks all instances that are being managed and only frees the memory when the count is 0.
  • Garbage Collection: Programmers need not worry when the last reference to the memory is destroyed as the object's destruction is now deterministic.
  • Constructors: They simply increase the count and destructors reduce the count.
  • Size: They are twice the size, on pointer for the data and one to keep track of the reference count.
  • Reference Count(1): It's located on the heap, so it comes with all the overheads that allocating on the heap entails.
  • Atomic Reads/Writes: The reference count has to be thread safe. Atomic operations are necessary to keep the threads in sync and are typically slower.
  • Move: When constructing a shared_ptr from another and no longer requiring the original, we should attempt to move rather than copy.
  • Inheritance: Shared pointers also utilise inheritance and have a virtual function (destruction). So there's overhead for memory and cycles here.
  • Reference Count(2): The Reference Count is part of a larger block of memory known as the control block.
  • One Per Shared: For every object that is shared, there is one control block. If an object is shared by five pointers, there's still only one.
  • Contents: 1. The reference count. 2. Custom allocator. 3. Custom deallocator. 4. Other data such as a weak count.
  • Control Blocks: A control block is created when the shared_ptr is created. However, it can't know if one already exists.
  • Make Shared: Std::make_shared will create a new object to point to, so we know it doesn't have a control block.
  • Unique_ptr: When constructing a shared_ptr from a unique one, a control block is always allocated.
  • Raw Pointer: Only use a raw pointer to construct the shared_ptr if you know that it doesn't have a control block i.e. stored as a shared_ptr elsewhere.
Weak_Ptr
  • Weak Pointers: They are pointers that act like shared_ptr's but they do not count towards the ownership of the object.
  • Dereferencing: They can't be dereferenced. Instead you convert them to a shared_ptr before access.
  • Dangling Pointer: It's strength is the ability to check if the object still exists in memory before you can obtain access to it.
  • Atomic Operation: In order for the check to complete and the conversion to a shared_ptr atomic operations are used.
  • Performance: It has the same overheads as the shared_ptr.
  • A Cache: Where we only want read-access but need to guarantee the object still lives.
  • Observer's List: A design pattern that involves other elements (observers) of your software observing the state of specific elements in your game (subjects).
  • Circular Shared_ptrs: When two shared_ptrs point to each other. This forms a deadlock.
After the 'Memory Management' part finished and after the 15 minute break, the next part of the lesson began, which was about Data Structures.

Structs
  • Structure: An array allows you to keep a collection of the same type, where as a struct allows you to combine multiple types in one structure.
  • Grouping: This is useful when we want to group data of different types together, where as an array would not work.
  • Conceptually: The data often stored in a struct is conceptually linked, although not closely enough to be a class.
  • Parameters: Functions with large parameter lists can be altered to use structs which can continue to grow easily.
  • Class-Like: Structs in C++ are actually the equivalent of public classes. Classes are private by default but structs are public.
  • Preference: Prefer classes where it's more than just data that you want to collate i.e. if you want to create member functions etc.
  • Array Support: Because structs have types, they are supported in arrays or container types just like any other.
  • Pointer to Structs: It's legitimate to access the data in a structure using pointers. It follows the same guidance of normal ones.
  • Nested: You can use nest structs within structs if you so choose to do so.
Containers
  • Types: Containers allow us to store objects collectively.
  • Examples: Arrays, Linked Lists, Associative i.e. maps, Unordered, Stacks.
  • Stack: We already know how a stack works, we discussed it when we spoke about memory allocation and the call stack frames.
  • Container Library: C++ provides a container library for these type of implementation, saving you the time and effort.
Vector
  • Arrays(1): Up until now, we've been focusing on C style arrays. Let's look at the container version most used instead.
  • Vectors(1): They are containers that store elements in a contiguous block and can also be dynamically resized during runtime.
  • Internally: They are dynamically allocated arrays under the hood. Their power comes from runtime ability to change size.
  • Reallocation: Once the capacity of the vector is reached, the array will be resized.
  • Why?: Containers offer us more flexibility including iteration.
  • Capacity: The array stored in the vector has a limited capacity. When reached, it's extended.
  • Vectors(2): They are containers that store elements in a contiguous block and can also be dynamically resized during runtime.
  • Allocated Memory: To prevent excessive memory allocations and the cost of moving objects on the heap, the array normally has a reserve capacity.
  • Memory Usage: Memory Usage is higher than necessary because of this. Often the programmer sets a reasonable capacity to begin with.
  • Efficiency: Vectors are fantastic at iterating through objects and at adding new objects to the beginning and the end of the container.
  • Arrays(2): When you need an array, especially one on the heap, then the vector should be your choice.
  • Iterators: Containers use iterators for deciding on how to navigate the array. You can use iterators instead of range based loops; if you want.
With the lectural side of the lesson over, we moved onto the practical side of the lesson. In this practical session, we were given a new project to work on. I didn't managed to get a lot done, ending with copying/moving the lib file from one project's file to another, due to the confusion of where the project needed to be extracted.

Thursday, 15 October 2015

Low-Level Programming_Post4

Low-Level Programming: Post 4 15/10/2015

October 15th 2015 is the date of the fourth lesson on Low-Level Programming.

The lesson that happened on the date above started in a very similar way to last week's lesson, in that, we were given an overview of what we were going to be taught that day. Unlike last week's lesson, however, we went straight into learning the features (last week, we were shown some examples of good/bad Dev Blogs and given an approach on how to work on the DungeonDeath game provided last week).

The following list shows what we were going to be taught today...

  • Memory: Pointers, References, Stacks, Caches, Recursion.
  • Arrays: Multi-Dimensional, Dynamic, Range-Based Loops.
  • Casting: Static, Dynamic and Const (Casting).
Only the Stacks listed above was the only feature taught last week, so I'm going straight into Recursion.
Recursion
  • Recursion: When a function calls itself.
  • Base Case: The first thing a recursive function should do is handled the ending case or cases that terminate the function call.
  • Simplifies: The idea is that for each call to the function we make the problem domain smaller and smaller until it converges on our base case.
  • Invalid Base Case: Make sure your base case will always be reached at some point.
  • Stack Overflow: Every time we call the function a new stack frame is created and items pushed onto the stack.
  • Performance: Can provide succinct solutions to problems but beware of the performance overhead of placing so much strain on the stack.
Cache Coherency
  • Main Memory: Caches are CPU specific areas of memory that are faster to access and write to.
  • Cache Sizes: The CPU often has multiple caches that are slower the larger they get i.e. registers, L1, L2 and L3.
  • Cache Contents: When memory is first read, it's loaded into the cache, these small chunks are known as cache lines.
  • Memory Request: If the memory requested is already in the cache it can be returned, otherwise we have a cache-miss.
  • Multi-Core: Many of today's CPU's have multiple cores, however, we now have the possibility of contention within the CPU cache.
  • Performance: Whilst the on-die caches are still fast, CPUs often share some aspects of their L cache across the cores. This can cause slow-downs.
  • Threads: If multiple threads are pulling in data from different places, but are attempting to use the same cache, we have contention and the other thread has to wait.
Static Arrays
  • Arrays: A collection of items in memory that are of the same type.
  • Management: It's easier to manage a 1000 game objects when they're all stored in a collective.
  • Fixed Size: Static arrays are given a fixed size, denoted by the [] characters and stored on the stack.
Dynamic Arrays
  • Dynamic Arrays: A collection of items in memory that are of the same type and allocated on the heap.
  • Management: We don't have to worry about worst-case scenarios at runtime, we can allocate what we need.
  • No Fixed Size: Dynamic memory allocation for arrays requires a chunk of the heap large enough to store X number of objects.
  • Deallocation: Make sure to deallocate all the memory after we're finished with it.
  • Heap: It's possible to use the Multi-Dimensional nomenclature for arrays allocated in the heap.
  • Access: We now have to do a lot more housekeeping and it takes more effort to pull the data out of the array.
Multi-Dimensional Arrays
  • Collections: Arrays are collections of the same type. The arrays we've been looking at have all been single in their dimensions.
  • Arrays of Arrays: Sometimes we might want to represent a collection as having both rows and columns i.e. a tile map.
  • Conceptual: Multi-Dimensional arrays are purely for the programmer's ease. The compiler remembers the imaginary depth.
Range-Based Loops
  • Concept: You provide a container that C++ can iterate over for you. Leads to cleaner and simpler code.
  • Unsupported: The container has to provide a suitable begin and end function for C++ to utilise range based loops.
  • Const: Where possible we should use a const reference to access the objects (assuming they're bigger than basic types).
Pointers
  • Pointers: Every variable or object we create has a location in our system memory. Pointers hold the addresses of memory locations.
  • Dereferencing(1): If we assign the pointer a type and point it to a valid block of memory where that type is stored, we can dereference it.
  • Invalid Pointers: We know that if we attempt to access an invalid pointer, we get a crash, hence the need for nullptr.
  • Size: A pointer's size is exe and platform independent. The two most common are 32 bit and 64 bit.
  • Type Safe: We can give a pointer a type which enforces type safety, as long as we don't define a void pointer.
  • Dynamic Memory: In order to use dynamic memory we need to use pointers, so we know where to find things on the heap.
  • Dereferencing(2): Defining a pointer to the variable value stores the memory address to the value, causing a level of indirection.
  • Pointer Types: We can store a pointer of any defined type and even no type (void). The various pointer types are 'int *ip', 'double *dp', 'float *fp' and 'char *ch'.
References
  • What Are They?: An alias for an existing variable or object. They allow you to interact and access memory like a pointer.
  • Why?: It's argued that programs are easier to maintain and read through the usage of references.
  • Versus Pointers: You cannot have null references and it must be initialised when it's created. You can't later change what it points to.
  • References Usage: Often used as parameters to a function or as a return value.
  • Pass as Const Reference: Where possible prefer to pass objects by const reference instead of value.
Static_cast
  • Type Safety: C++ is a type safety language, if the compiler completes, it means your programming isn't performing unsafe operations on objects.
  • Casting: Well casting allows us to subvert the type safety net. We can freely use it to force implicit conversions (int to double).
  • C Style Syntax: (T) Expression or T (Expression).
  • Static_cast: Like C cast's this is used to force implicit conversions. It can not cast from const to non-const objects.
  • Usages: Implicit conversion; Upcast and Downcasts of class inheritance; Ptrs to void and void to ptrs; Amongst esoteric others.
  • Code: It's clear than traditional casting, we can just search for static_cast and we know that a cast is being performed.
Dynamic_cast
  • Safe Polymorphic Casting: You can cast a pointer or reference to any polymorphic type supported class. That can be up or down or even sideways through the inheritance chain.
  • Result: The resultant object will guarantee successful casting. If it has failed the pointer, it returns will be null or std::bad_cast if a reference.
  • Limitations: Diamond inheritance must utilize virtual. Protected/Private inheritance will fail.
  • Performance (RTTI): Depending on the compiler's implementation of the dynamic_cast, there can be considerable slowdown.
Const_cast
  • Constness: It's possible to remove an object's constness. This can be achieved through the usage of const_cast.
  • Responsibility: You're telling the compiler that this variable or object should be mutable, that you know best.
  • Guidance: Don't do it unless absolutely necessary. If you can't code the correct const solution or make changes to the code base.
  • Ramifications:  By breaking the constness of the object, users of the code calling what they believe to be const functions could end up with changed data.
After the lectural side of the lesson, we continued to work on the DungeonDeath game that was provided to us last week. In the lesson, I attempted to add a exit game option and to add more levels to the game. I managed to add the exit game option to the game, but when the program breaks, it still leaves the default comment when we don't decide to go north or south. Near the end of the lesson, we started on making the extra levels/rooms, since there were only north and south rooms programed into the game. I managed to create a startup room for the east side, but I then ran out of time to continue.

Thursday, 8 October 2015

Low-Level Programming_Post3

Low-Level Programming: Post 3 08/10/2015


8th October 2015 is the date of the third lesson on Low-Level Programming.

Unlike the previous lesson that I had, in which the beginning was a recap of what we were taught in the first lesson, the lesson today was a cover of what we were going to be taught today, before the practical side of the lesson, which is in the last hour of the lesson. But before I get to what we were taught today, there were two different features that were shown to us. Both of these were to help us to develop the 'Dev Blogs' and a way to approach the Dungeon Game code provided to us last week.

The first of the two features that was mentioned in the above paragraph was that we were provided with some examples on how to develop the Dev blogs. Some of the examples were good, others were bad.

Despite there being only 1 image on the good side of how to develop the Dev blog, it is/was helpful nevertheless. The image provided what was taught in the lesson, the key points/concepts from the lesson and a personal point of view on how the person who wrote the post felt about what was taught in the lesson. The last point about the person saying their view about the lesson surprised me a little, but I completely understand why he/she provided their personal opinion on the lesson.

There were, however, 3 images that showed how the Dev blogs shouldn't be done. The three examples ranged from saying the computers were 'crap' and not understanding as to why we had to fix some compiler errors, only mentioning some of the main points taught in the lesson and, my personal 'favourite', a post that only had the words "Write blog entry here". These posts also helped me despite being completely rubbish, as it gave us examples on how NOT to do Dev blog posts.

The second of the two features that was mentioned in the paragraph was that we were given a method on how to approach the coding task from last week, in that, some images were provided on listing the various variables, states and so on that are listed on each different object. For example, the first image showed that the 'bat' object contains the following: Attacks, Defends, Is It Alive?, Renders, States and two mini variables connected to the States, which are Has Health and Has Damage Modifier. The player, though sharing some of the characteristics of the bat (enemy), it also has some differences. The 'player' object contains the following: Defends, Attacks, Has Score, Has Health, States and three mini variables connected to the States, which are Has Score, Has Health and Has Damage Modifier. It also showed some OOP graphs on the different variables mentioned in the bat and player object(s).

For example, the bat's graph is as follows...


The player's graph is as follows...

The GameObject's graph is as follows...

After the two parts of the lesson (Dev blogs and 'How to approach the code from last week') and after the break, we were taught some new features and a small recap, since I knew some of the features from last year. Some of them include Memory Allocation, both static and dynamic, stacks, scopes and nullPtr.

Static Memory Allocation
  • Default Behaviour: When we create instances of object memory is automatically allocated on the stack.
  • Lifetime(1): The memory remains allocated until the object or variable falls out of scope.
  • Cleanup: The memory cleanup process is automatic.
  • Lifetime(2): All objects, variables and arrays have a known size throughout the programs run.
  • Management: Removed from the programmer's concern.
Scopes
  • Scopes: Areas in our code where we combine functionality.
  • Organisation: Everything in our program can be seen as organized into these scopes i.e. functions, classes etc.
  • Memory Allocation: When the scope terminates, all the memory that's been statically allocated get's released.
  • Variables: Anything destroyed in this scope won't be accessible. This is why we shouldn't return references or pointers to objects whose lifespan ends when the function does.
Stack
  • Stack: A fast and organized dedicated area in memory. where we store instances of variables and objects at runtime.
  • FILO: First in, last out principal. We push and pop items off the stack.
  • Memory: Memory is managed for you.
  • Static: Everything needs to be a known quantity at program run.
  • Size Limits: It's a limited amount of memory and it's possible to utilise it all. Stack Overflow is 'Game Over'.
  • Local Storage: When the function call ends, all data is popped off of the stack.
Dynamic Memory Allocation
  • Dynamic Memory: The opposite if Static memory. The complier is unable to determine the amount of memory it needs to allocate.
  • Lifespan: Dynamically allocated memory lives independently of the function it's allocated in.
  • Allocation: The programmer is in charge of both allocation and deallocation.
  • Heap: Instead of the stack, dynamic allocation occurs on the heap.
Heap
  • Heap: A region of memory that's not automagically handled for you.
  • Organisation: Unlike the stack, it has no defined structure, you can add and delete memory as you see fit.
  • Allocation: In order to allocate memory dynamically, we use the new keyword.
  • Access: In order to access the memory, we now need to deference a pointer,
Automatic/Dynamic
  • Memory Usage: Dynamic allocation allows us to reserve only the amount of memory we require i.e. less wasted unused portions.
  • Speed: The stack is faster to access than the heap due to the level of indirection a pointer deference incurs.
  • Memory Management: Stack usage means the memory is freed when it's not needed, unlike dynamic. You can't 'leak' the stack.
  • Memory Organisation: The stack is organised in such as way that memory fragmentation will not occur. The heap offers no such assurances.
  • Memory Limits: The stack has a memory limit, the heap does not. However, the hardware has a finite amount of memory before swapping happens.
  • Resizing of Memory: It's actually possible to take an item in the heap and dynamically resize it.
NullPtr
  • Null Pointer: The null pointer is a non-valid pointer i.e. it doesn't point to any memory location.
  • Usage: Using the null pointer we can run checks before we try and deference it. This will save us crashing if it doesn't point anywhere.
  • Deletion: When we free some memory from the heap, we should always make the pointer null.

Saturday, 3 October 2015

Low-Level Programming_Post2

Low-Level Programming: Post 2 01/10/2015

1st October 2015 is the date of the second lesson on Low-Level Programming.

The start of the lesson was essentially a recap of some of the features learnt from the first lesson. I have already gone into some detail about some of the features learnt from the first lesson on my first post. The next paragraph will show what else was taught in the lesson, from Static Member Variables, Public/Private Inheritance, going into detail on Constructors and so on. The first part explains about Static Member Variables, with some of the following notes used from the lessons mixed together.
  • Static Member Variables force a single shared instance amongst all objects instantiated of that class.
  • They belong to the class itself and are shared amongst instances.
  • As they are treated independently of class instancing they must be explicitly defined to a non-zero value (where a non-zero value is desirable) outside of the class definition.
  • To access them we use the scope operator '::'.
  • The static variable resides in the class scope but does not belong to objects of that class. It belongs to the class.
  • Class definitions are often included in multiple translation units i.e. CPP. The static variable should be shared amongst all and not stored as copies.
  • As it resides within the class scope (similar to namespace) we access it using the :: operator. We can access it through instances of that class, but it then becomes unclear that it's static access.
  • Static values are stored in the data segment which is a portion of the object file or the virtual address space of a program that contains variables. Const statics are stored in the rodata segment.
The next paragraph is about Public/Private Inheritance. The following info was found on a website about Inheritance.

One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the baseclass, and the new class is referred to as the derived class.
The idea of inheritance implements the is a relationship. For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well and so on.

Public Inheritance: When deriving a base class from a public base class, public members of that base class become public members of the derived class and protected members of that base class become protected members of the derived class. A base class's private members are never accessible through calls to the public and protected members of the base class.

Private Inheritance: When deriving from a private base class, public and protected members of the base class become private members of the derived class.

The following line(s) is some more information based on Constructors.


Initialisation

  • Member Variables need some 'Sane' values. (int maxBoost = 50).
  • Use Initialiser lists and not the body of the constructor.
Viral Functions
  • Don't call virtual functions from constructors or destructors. They don't exist.
  • The most derived function will never get called, as that part of the class doesn't exist yet.
  • As construction happens at the lowest level first, the derived member variables won't have been initialised.
  • Compliers may warn.
  • The program may compile but not link.
  • If it makes it to runtime, it'll either crash or perform unintended behaviour.
The next part of this page are some of the new features that we learnt from the lesson.

Default and Delete
  • If we don't define default constructors and assignment operators the complier will do this for us.
  • We can use the default keyword to acknowledge we intend for the compliers default version to be used.
  • Use 'Delete' when we don't want to allow usage of functions.
Delete
  • Traditionally we use private non-defined functions.
  • We can use delete to invalidate the function call both to automatically constructed functions and ones of our choosing.
  • Will also use template instantiations.
After the lectural side of the lesson, we moved onto the practical side of it. The exercise given to use was to work on the DungeonGame from the last lesson and refactor the code using OOP and how we would handle the animations per object. We quickly split the various components into categories, such as the bat having a render, the 'Newton's Cradle' having an animation (as if the game was loading) and the player itself. The Newton's Cradle and the Bat were put into the Redner category as they both get displayed after some time when the program runs, but an Animation feature was added into the Newton's Cradle object as it was the only object in the game to have an animation. The player and the bat shared the health and attack functions, however, and so were linked together as a result. Sadly, we ran out of time to finish the task(s) and couldn't continue further.