public
Last active

A 2D/3D collision grid

  • Download Gist
grid.hpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
// A 2D/3D collision grid. MIT licensed
// - rlyeh, 2012
 
#pragma once
 
#include <map>
#include <set>
#include <cassert>
#include <tuple>
 
template< typename T >
class grid3
{
const int cell_size;
 
typedef std::tuple<int,int,int> key;
 
std::map< key, std::set< T > > map;
typename std::map< key, std::set< T > >::iterator cursor;
 
inline key at( int x, int y, int z ) const
{
return key( x / cell_size, y / cell_size, z / cell_size );
}
 
public:
 
grid3( int _cell_size = 1 ) : cursor(map.end()), cell_size(_cell_size)
{
assert( _cell_size > 0 );
}
 
void setup( int _cell_size )
{
assert( _cell_size > 0 );
 
cell_size = _cell_size;
map = std::map< key, std::set< T > >();
cursor = map.end();
}
 
bool find( int x, int y, int z )
{
cursor = map.find( at(x,y,z) );
return( cursor != map.end() );
}
 
std::set< T > &found() const
{
return cursor->second;
}
 
size_t size() const
{
return map.size();
}
 
size_t count( const T &elem, int x, int y = 0, int z = 0 ) const
{
if( !find(x,y,z) )
return 0;
return cursor->count( elem );
}
 
void insert( const T &elem, int x, int y = 0, int z = 0 )
{
( map[ at(x,y,z) ] = map[ at(x,y,z) ] ).insert( elem );
}
 
void erase( const T &elem, int x, int y = 0, int z = 0 )
{
( map[ at(x,y,z) ] = map[ at(x,y,z) ] ).erase( elem );
}
 
void clear( int x, int y = 0, int z = 0 )
{
( map[ at(x,y,z) ] = map[ at(x,y,z) ] ) = std::set< T >();
}
};
( map[ at(x,y,z) ] = map[ at(x,y,z) ] ).insert( elem );

wat.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.