Thomas Sampson


Leave a comment

Finding variable assignments

When searching through an entire codebase for a variable it is often useful to limit the search results to those instances where the variables is assigned a new value (or perhaps when the variable is used IN an assignment). This can be achieved with the following regular expressions…

Find assignments

MyVariableName[ \t\r\n\v\f]*=[^=]

Find usage in an assignment

=[^=][ \t\r\n\v\f]*MyVariableName


Leave a comment

ATI Tessellation demo

ATI tessellation demo showing how the GPU can take a relatively simple triangular mesh and use additional normal/displacement data to generate a more rich, detailed mesh on the fly. Extra tessellation detail is generated dynamically and passes straight through the GPU, requiring no extra video memory for the additional vertex data.


Leave a comment

Basic C++ Multi Threading

This is a quick post for anyone who wants to get up and running with multiple threads quickly in C++. I have been doing a fair amount of python programming recently, in particular a 2D networked game, and have realised how useful distributing independent tasks across multiple threads can be. After looking into how best and easiest to translate this experience from python and get a working example going in C++, I am posting the following code which I will attempt to explain beneath.

#include <iostream>
#include <windows.h>
#include <conio.h>
using std::cout;
using std::endl;

int thread_count(0);
int main_thread_count(0);

DWORD_PTR WINAPI threadFunction(void* p)
{
  ++thread_count;
  while(true)
  {
    cout << "Thread "<<(unsigned int)p<<" busy...."<<endl;
  }

  return 0;
}

int main(int argc, char* argv[])
{
  cout << "Starting...."<<endl;

  //Gather processor info
  SYSTEM_INFO si={0,0};
  GetSystemInfo(&si);
  const unsigned int num_cores(si.dwNumberOfProcessors);

  cout << num_cores << " Cores detected"<<endl;

  //Set up thread handles
  HANDLE* thread_handle=new HANDLE[num_cores];
  ZeroMemory(thread_handle,sizeof(HANDLE)*num_cores);

  for(unsigned int core(0);core<num_cores; ++core)
  {
    DWORD_PTR rqd;
    thread_handle[core]=CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)threadFunction, (LPVOID)core,     NULL, &rqd);
  }

  cout << "Main thread reached"<<endl;

  std::cin.get();
  std::cin.get();

  //Terminate threads
  DWORD exit_code( 0);
  for(unsigned int core(0);core<num_cores; ++core)
  {
    TerminateThread(thread_handle[core],exit_code);
  }

  delete[] thread_handle;

  return 0;
}

Quick run through!

How many threads to use? A good question! When you first come across threading you may believe it is the answer to every problem and spawn threads in abundance! In the example above I have used the GetSystemInfo() call to gather information about the available CPU’s, then use this information to spawn a thread per cpu. The threads get spawned in the same virtual address space as the parent process and are allocated a stack space of 1mb by default (although this is tweakable). For this reason you could essentially spawn as many threads as you like up to the virtual memory limit of the system, but a separate thread per cpu is usually prefered, and is the recommended approach over at msdn.

Spawning a thread essentially means running some previously declared function in parallel to main, and in this example each new thread runs threadFunction(). In real life this is seemingly useless, you would usually have a specific function and task for each thread such as rendering particles, or listening out on a socket for incoming connections.

Thread handles are used to allow you to make reference and work with your threads after you have created them, for a comprehensive list of thread operations see here. Be sure to use the thread handles to TerminateThread() on each of your threads before exiting the parent process.


Leave a comment

STL algorithm predicates

Just a quick reminder on how to set up a predicate function for an stl algorithm (accumulate shown here) using the () operator on a struct/class.

This arbitrary example accumulates all integer values in bag which are greater than 2. There third parameter to accumulate (the zero) means start accumulating from 0 rather than a given constant.

struct check
{
	int operator()(int l, int r)
	{
		return (r>2)?  (l+r): l;
	}
};

int total=std::accumulate(bag.begin(),bag.end(),0,check());


Leave a comment

Visual Studio Post Build Events

I am currently working on a Visual Studio solution that has multiple projects each building an exe or library to a different directory. My aim was to copy some of the output files all into the same folder as the main application is dependent on the other projects residing in the same directory.

Previously, if I had updated and rebuilt one of the projects in the solution I would manually locate the output file and drag it into the right place. However today I discovered the post build events area in Visual studio (right click solution > Build events). Here you can input your own DOS commands and utilise a bunch of VS environmental macros/variables to create a simple batch script which is automatically executed every time you build/rebuild your solution. Any output from your DOS commands (echo) is printed into the ouput window inline with all the other build information Visual Studio provides during the build process.

Here is a simple example which solved my problem but there are much more advanced techniques you could use with this feature.

echo Copying pre loader application to build directory
copy "$(SolutionDir)cwpl_app\bin\Debug\CwplApp.exe" "$(OutDir)"
echo Launching pre loader tool
"$(SolutionDir)cwpl_app\bin\Debug\CwplApp.exe"


2 Comments

Extracting data from float

Earlier this week i was presented with the simple problem of checking if floating point number was a whole number. I stumbled upon the useful function modf and thought it was worth a quick post. the modf function requires <stdio.h> and <math.h>, and allows you to separate the integral and fractional part of a floating point number.

Taking the value 5.24f as an example…

  • Integral part = 5
  • Fractional part=0.24

modf is fully documented here but is rather simple. modf takes two arguments, the first is the value you wish to query (in the case above this would be 5.24). The second argument is a pointer to where the integral part should be placed. The return value of the method is the fractal part. Therefore the solution to my original problem (testing if a float is infact an integer value) is as follows…

Solution

int f;

if(modf(myValue,&f)==0)
{

//myValue is a whole number

}


Leave a comment

Advanced 2D collision detection

http://www.gamedev.net/reference/programming/features/2dRotatedRectCollision/page2.asp

This is a great article written by explaining how to achieve accurate collision detection between two dimensional objects using the “Separating Axis Theorem”.

Although this tutorial deals with the collision of rectangular objects (so would apply to bounding boxes around 2D shapes rather than pixel based collision detection), this is not limited to axis aligned rectangles. This allows the algorithm to check for collision with rotated boxes rather than the less useful axis aligned collision detection approach (hitTest() in flash anyone?).

I have finished reading the tutorial and intend to form a c++ implementation in the near future. Although some parts may need a quick re-read, this method is not as complicated as it might first appear. A word of warning, this kind of collision detection should only be triggered by a less accurate method. By this I mean that if you have a large collection of objects which require collision checking, do some simple tests firsts to check that they arent a mile apart (the radius test is suggested in the article).

Only if the result of a simpler algorithm suggest that the two shapes are in close proximity, should we go ahead and make use of the more resource expensive approach presented here. Running the algorithm suggested in this article would be wasteful if it was to be executed all the time on all objects regardless of the distance between them.


4 Comments

Shorthand IF statement in C++

The C++ conditional operator (also known as the ternary operator) provides a succinct way to select a simple operation or assignment value based on a condition, without expressing the selection with the more cumbersome if/else syntax. If the condition is true, the leftmost expression is evaluated, otherwise the rightmost. Example usage can be seen below.

int a(5), b(10);
(a > b)? std::cout << a : std::cout << b; // operation
int c = (a > b)? a : b;                   // assignment
int d = (a > b)? ((a > 10)? 10 : a) : b;  // nested


Leave a comment

C++ Inline keyword

Today I came across the inline keyword in c++. The inline keyword can be placed before a function defenition and is usually placed before functions which contain only a few lines of code.

If you have written a function which is only 3 lines of code for example, and these 3 lines of code are fairly simple and non resource-expensive, some compilers will automatically inline your function. However, the inline keyword is a way of enforcing that this happens at compile time. So what is function inlining?

Function inlining allows the compiler to substitute any calls to your function with the actual function definition it’s self. Let’s say you have a call to a function go(). Without function inlining, at runtime all sorts will go off. Register values, any paramaters and the instruction pointer will be pushed onto the stack (time consuming), the instruction pointer pointed to the location of the function, the function executes then all values are popped off of the stack!

If your function is a large complex algorithm which only gets executed a couple of times in the program, and needs keeping seperate for clarity, then this is not such a problem. However if your function is small and gets called repeatedly throughout the program, function inlining allows those few lines of code, to replace the original call to the function. For example,

Without function inlining…

void go()
{
    cout << "Hello World";
    cout << "Test function!";
}
int main()
{
    for(int i( 0);i<10;++i)
    {
        go(); // Standard call mechanism initiated
    }
}

With function inlining enforced…..

inline void go()
{
    cout << "Hello World";
    cout << "Test function!";
}
int main()
{
    for(int i( 0);i<10;++i)
    {
        cout << "Hello World"; //Gets inserted at compile time
        cout << "Test function!"; //Gets inserted at compile time
    }
}

Although many factors contribute towards the performance of a program, inlining can be used to bring about significant performance increases if used properly.