• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
zalzane

A* speed issues (C++)

8 posts in this topic

I've been working on this code for quite awhile now trying to get it to run in a reasonable amount of time. It's supposed to be an A* algo that pathfinds between two points while taking into considering a cost grid that represents how hard it is to cross each tile. A typical grid that would be fed to the algo would be 256x256 tiles in size. During profiling I would test between one end of the grid (0,0) to the other end (255,255) and would get atrocious speeds of up to 60 seconds. There isn't much in the algo that strikes me as any kind of heavy lifting, so I'm virtually clueless as to why it's running so slow.

Here's the code, I put all the structure definitions involved and did some hardcore commenting. The indenting may be weird because of how the forum interprets whatever the hell my text editor is using for spaces.

[code] struct pair_s{
int x;
int y;
pair_s(int x_, int y_){
x = x_;
y = y_;
}
};
struct node_s{
vector<pair_s> pathToNode;
int x,y;
float distToDest;
float costTravelled;
float cumulativeCost;
bool hasNodeBeenParsed;
node_s(int x_, int y_, float distToDest_, float costTravelled_, vector<pair_s>* prevPath){
x = x_;
y = y_;
distToDest = distToDest_;
costTravelled = costTravelled_;
hasNodeBeenParsed = false;
cumulativeCost = costTravelled + distToDest;
if(prevPath != NULL){
pathToNode = (*prevPath);
pathToNode.push_back(pair_s(x,y));//add the current node to path history
}
}
};

void worldgen_c::getPathBetweenPointsAstr(int initial_x, int initial_y, int dest_x, int dest_y, vector<vector<float> >* costMap, vector<pair_s>* retPath, float costMultiplier){
vector<node_s> closedNodes;
vector<node_s> openNodes;
int gridWidth = costMap->size();
bool** nodesAcctFor = new bool*[gridWidth];//when it comes to checking if a tile has already been added to the node vectors,
for(int i=0; i<gridWidth; i++){//it's more efficent to use a 2d array of booleans rather than iterating through a list of coordinates
nodesAcctFor[i] = new bool[gridWidth];
}
for(int x=0; x<gridWidth; x++){
for(int y=0; y<gridWidth; y++){
nodesAcctFor[x][y]=false;
}
}
//initial node
closedNodes.push_back( node_s(initial_x, initial_y, getDist(initial_x, initial_y, dest_x, dest_y), (*costMap)[initial_x][initial_y]*costMultiplier, NULL) );
while(1){
//first we add spots adjacent to closed nodes to the open nodes
for(int node=0; node<closedNodes.size(); node++){
if( !closedNodes[node].hasNodeBeenParsed ){ //check to see if closed node in question has already had its adjacent friends added to open nodes
for(int x_off=-1; x_off<=1; x_off++){ //checking cardinals and diagonals
for(int y_off=-1; y_off<=1; y_off++){
if(x_off==0 && y_off==0)//we dont care about the node we're sitting on
continue;
if(closedNodes[node].x+x_off>=gridWidth || closedNodes[node].x+x_off<0 || closedNodes[node].y+y_off<0 || closedNodes[node].y+y_off>=gridWidth)//make sure node within b ounds
continue;
if(nodesAcctFor[closedNodes[node].x+x_off][closedNodes[node].y+y_off])//making sure node isnt already added to one of the tree things
continue;
//now add the node to the openNodes vector
float pathcost=1;
if(x_off != 0 && y_off != 0) //if going diagonally, higher pathcost
pathcost=1.4;
openNodes.push_back(node_s(
closedNodes[node].x+x_off, //x val
closedNodes[node].y+y_off, //y val
getDist(closedNodes[node].x+x_off, closedNodes[node].y+y_off, dest_x, dest_y),//distance to destination
closedNodes[node].costTravelled + (*costMap)[closedNodes[node].x+x_off][closedNodes[node].y+y_off]*costMultiplier + pathcost, //heuristic cost
&closedNodes[node].pathToNode//path to old node
) );
nodesAcctFor[closedNodes[node].x+x_off][closedNodes[node].y+y_off] = true;
}
}
closedNodes[node].hasNodeBeenParsed = true;
}
}


//now we check each open node and see which one has the lowest cumulative cost
int lowestCostIndex=-1;
float lowestCostValue = 4294967296;
for(int i=0; i<openNodes.size(); i++){
if( openNodes[i].cumulativeCost < lowestCostValue ){
lowestCostValue = openNodes[i].cumulativeCost;
lowestCostIndex = i;
}
}
//now convert the open node to a closed node
closedNodes.push_back( openNodes[lowestCostIndex] );
openNodes.erase(lowestCostIndex + openNodes.begin() );

if(closedNodes[closedNodes.size()-1].x == dest_x && closedNodes[closedNodes.size()-1].y == dest_y){ //see if we're finally done
(*retPath) = closedNodes[closedNodes.size()-1].pathToNode;
break;
}
}
for(int i=0; i<gridWidth; i++){//cleanup
delete[] nodesAcctFor[i];
}
delete[] nodesAcctFor;
return;
}[/code]
0

Share this post


Link to post
Share on other sites
ah, easy fix: binary heap sorting: http://www.policyalmanac.org/games/binaryHeaps.htm

you should see substancial improvment in speeds.
1

Share this post


Link to post
Share on other sites
There's a surprising amount of heavy lifting that occurs in the open and closed lists. If you profile your code you'll soon see where the real culprit is.

That said, you may not need to go to the extent of implementing a binary heap if you can reduce the number of members in the closed list. I had some speed issues in my first attempt at an A* implementation and refactored my code to make better use of the spatial partitioning my engine was already using and the performance was good enough without needing the complexity of a binary heap.

My game world is broken down into zones which are 32x32 tiles, so instead of storing tiles in the closed list, I stored Zones and a 1024bit array representing the traversal of each tile for the zone. To check the closed list I simply find the zone through a list scan then do some simple bit twiddling to find the tile itself, thus reducing the size of the closed list by a factor of between 100 to 1000.

Basically I was too lazy to learn how to implement a binary heap. :)

Another option is to do the pathfinding on a much coarser grid first, then pathfind between adjacent grids.
1

Share this post


Link to post
Share on other sites
As stated use a heap based priority queue to store the open list. Do not use a closed list at all, just store a flag on each tile representing whether it's open, closed or neither. Only clear the cost and parent pointers on the tile when you visit it for the first time in a particular A* session so that would mean encapsulating the algorithm in a class with a static variable that always increments a search id. Use hierarchical pathfinding A*. Hope that helps.
1

Share this post


Link to post
Share on other sites
thanks guys, the issue was with the comparasion/sort stuff and binary heap thing pretty much fixed it
0

Share this post


Link to post
Share on other sites
Not sure if it works in all situations or at all, but try pathfinding from both the start and the end at the same time, and when the 2 spreading areas touch each other, get the path.

In some situations it will be slower than normal in some it should be faster. Also not sure if it works on other than grid like node system.
1

Share this post


Link to post
Share on other sites
A few small notes, as with all the optimizations they might help or not (you should always profile to see), I've cut the quoted code just to the relevant parts:
- you're doing an awful lot of work in the constructors of pair_s and node_s, in particular assignments in a ctor body are a bad idea since they cause multiple (re)initializations when you instantiate objects (e.g., when constructing closedNodes here -- [code]vector<node_s> closedNodes;[/code] -- the objects contained in the container are constructed when the container itself is); use initialization lists instead: [url="http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6"]http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6[/url]
- regarding nodesAcctFor -- 1D array may be faster than 2D array for nodesAcctFor, since it gives you contiguity (your CPU's cache lines will thank you) and avoids multiple heap allocations ("new" is a significantly expensive operation, you should avoid having it in a for loop if you can), see [url="http://stackoverflow.com/questions/2151084/map-a-2d-array-onto-a-1d-array-c"]http://stackoverflow.com/questions/2151084/map-a-2d-array-onto-a-1d-array-c[/url]
- it might be a good idea to use size_t or ptrdiff_t (depends on whether you want signed or unsigned) instead of ints in your for loops when you use the iteration variable as an index to an array/container (and it expresses the intent more clearly, so a plus for readability), see: http://www.viva64.com/en/a/0050/

[quote name='zalzane' timestamp='1328507348' post='4910057']
[code] struct pair_s{
int x;
int y;
pair_s(int x_, int y_){
x = x_;
y = y_;
}
};
struct node_s{
node_s(int x_, int y_, float distToDest_, float costTravelled_, vector<pair_s>* prevPath){
x = x_;
y = y_;
distToDest = distToDest_;
costTravelled = costTravelled_;
hasNodeBeenParsed = false;
cumulativeCost = costTravelled + distToDest;
if(prevPath != NULL){
pathToNode = (*prevPath);
pathToNode.push_back(pair_s(x,y));//add the current node to path history
}
}
};

void worldgen_c::getPathBetweenPointsAstr(int initial_x, int initial_y, int dest_x, int dest_y, vector<vector<float> >* costMap, vector<pair_s>* retPath, float costMultiplier){
vector<node_s> closedNodes;
vector<node_s> openNodes;
int gridWidth = costMap->size();
bool** nodesAcctFor = new bool*[gridWidth];//when it comes to checking if a tile has already been added to the node vectors,
for(int i=0; i<gridWidth; i++){//it's more efficent to use a 2d array of booleans rather than iterating through a list of coordinates
nodesAcctFor[i] = new bool[gridWidth];
}
for(int x=0; x<gridWidth; x++){
for(int y=0; y<gridWidth; y++){
nodesAcctFor[x][y]=false;
}
}
// ... cut ...
}[/code]
[/quote]
1

Share this post


Link to post
Share on other sites
[quote name='Matt-D' timestamp='1328813653' post='4911395']
A few small notes, as with all the optimizations they might help or not (you should always profile to see), I've cut the quoted code just to the relevant parts:
- you're doing an awful lot of work in the constructors of pair_s and node_s, in particular assignments in a ctor body are a bad idea since they cause multiple (re)initializations when you instantiate objects (e.g., when constructing closedNodes here -- [code]vector<node_s> closedNodes;[/code] -- the objects contained in the container are constructed when the container itself is); use initialization lists instead: [url="http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.6"]http://www.parashift...s.html#faq-10.6[/url]
- regarding nodesAcctFor -- 1D array may be faster than 2D array for nodesAcctFor, since it gives you contiguity (your CPU's cache lines will thank you) and avoids multiple heap allocations ("new" is a significantly expensive operation, you should avoid having it in a for loop if you can), see [url="http://stackoverflow.com/questions/2151084/map-a-2d-array-onto-a-1d-array-c"]http://stackoverflow...to-a-1d-array-c[/url]
- it might be a good idea to use size_t or ptrdiff_t (depends on whether you want signed or unsigned) instead of ints in your for loops when you use the iteration variable as an index to an array/container (and it expresses the intent more clearly, so a plus for readability), see: [url="http://www.viva64.com/en/a/0050/"]http://www.viva64.com/en/a/0050/[/url]

[quote name='zalzane' timestamp='1328507348' post='4910057']
[code] struct pair_s{
int x;
int y;
pair_s(int x_, int y_){
x = x_;
y = y_;
}
};
struct node_s{
node_s(int x_, int y_, float distToDest_, float costTravelled_, vector<pair_s>* prevPath){
x = x_;
y = y_;
distToDest = distToDest_;
costTravelled = costTravelled_;
hasNodeBeenParsed = false;
cumulativeCost = costTravelled + distToDest;
if(prevPath != NULL){
pathToNode = (*prevPath);
pathToNode.push_back(pair_s(x,y));//add the current node to path history
}
}
};

void worldgen_c::getPathBetweenPointsAstr(int initial_x, int initial_y, int dest_x, int dest_y, vector<vector<float> >* costMap, vector<pair_s>* retPath, float costMultiplier){
vector<node_s> closedNodes;
vector<node_s> openNodes;
int gridWidth = costMap->size();
bool** nodesAcctFor = new bool*[gridWidth];//when it comes to checking if a tile has already been added to the node vectors,
for(int i=0; i<gridWidth; i++){//it's more efficent to use a 2d array of booleans rather than iterating through a list of coordinates
nodesAcctFor[i] = new bool[gridWidth];
}
for(int x=0; x<gridWidth; x++){
for(int y=0; y<gridWidth; y++){
nodesAcctFor[x][y]=false;
}
}
// ... cut ...
}[/code]
[/quote]
[/quote]

oh wow, thanks for the incredible feedback.

It's not often that I can get feedback at that level of detail/insight, thank you.
0

Share this post


Link to post
Share on other sites
I did a collaboration with another programmer many years ago (via Usenet, heh) helping to optimize his A* solution (2D grid based map) he actually did a real good visual interface that showed the algorithm executing and had many precanned testcases of 'problematic' terrain patterns, lots of variants (manhattan vs 8 adjacents), etc...

eventually used HeapQ
Minimizing the A* map data to fit in cache much better (packing/bitflags??/ints as small as possible)

another speedup (there were many small incrementals) was doing pointer math with map row spans when checking 8 adjacents (and for HeapQ as well)

another was if possible putting a edge of impassibles all around the map so that the x<0 X>mapsize y<0 y>mapsize tests for candidates didnt have to be done

with power of 2 mapsizes then shifts used instead of divides (actually did speed it up some small significant amount)

oh and proper inlining and other compiler optimizations made a huge difference in speed (I forget if we unwrapped the 8 adjacent loop)


even on my old 800mhz single core P4 laptop, a 512x512 greyscale picture maps solutions ran virtually instantaneously (he actually had performance tools built into the visual interface to do sets of 500-1000 random paths on a map....)
That even with more than a few 'modular' options with extra sub calls that once standardized could be eliminated (inlined)
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0