• 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
Juliean

Sorted particles and SIMD

3 posts in this topic

Hello,

 

mainly as a learning experience, but also to aid my further developement, I want to enchance my particle system using SIMD, as featured in this article: http://software.intel.com/en-us/articles/creating-a-particle-system-with-streaming-simd-extensions.

 

Now my main problem is that, unlike them, I want my particles to being sorted. This is a problem, since SIMD seems to rely on the data being accessed in a linear manner (from i to i+3), which isn't working all that well with my current approach. This is how depth updating looks currently:

 

	const D3DXVECTOR3& vPos(camera.GetPosition());
	for(DepthVector::iterator ii = m_vDepth.begin(); ii != m_vDepth.end(); ++ii)
	{
		//get index of currect particle to keep temporal coherency
		const unsigned int index = ii->index;
		ii->depth = abs(m_particles.x[index] - vPos.x);
		ii->depth += abs(m_particles.y[index] - vPos.y);
		ii->depth += abs(m_particles.z[index] - vPos.z);
	}

	std::sort(m_vDepth.begin(), m_vDepth.end(), ParticleSorter());

As you can see, I perform an index sort, later on I'll use that index to identify the particle. Note that since I'm using an SoA I can't really sort that itself... can I? Anyway, now this is the code I've written so far in SIMD:

 

void ParticleEmitter::SortParticles(const D3DXVECTOR3& vCameraPos)
{
	//load camera position and create depth register
	__m128 cameraPosX = _mm_set1_ps(vCameraPos.x), cameraPosY = _mm_set1_ps(vCameraPos.y), cameraPosZ = _mm_set1_ps(vCameraPos.z), depthRegister;
	//register for abs()-ing 
	__m128 dummy = _mm_set1_ps(1.0f);

	__declspec(align(16)) float depth[4];
	
	// number of 4 elements we can process
	const unsigned int remainingParticles = m_vDepth.size() % 4;
	//get vector iterator
	DepthVector::iterator ii = m_vDepth.begin();
	//
	for(unsigned int i = 0; i < m_cParticles - remainingParticles; i+=4)
	{
		//set register to X-component of camera distance -> abs( ParticleX - CameraX )
		depthRegister = _mm_andnot_ps(dummy, _mm_sub_ps( _mm_load_ps(&m_particles.x[i]), cameraPosX) );
		//add Y-component -> abs( ParticleY - CameraY)
		_mm_add_ps(depthRegister, _mm_andnot_ps(dummy, _mm_sub_ps( _mm_load_ps(&m_particles.y[i]), cameraPosY) ) );
		//add Z-component -> abs( ParticleZ - CameraZ)
		_mm_add_ps(depthRegister, _mm_andnot_ps(dummy, _mm_sub_ps( _mm_load_ps(&m_particles.z[i]), cameraPosZ) ) );

		//load depth
		_mm_store_ps(depth, depthRegister);

		//set depth
		ii->depth = depth[0];
		ii++;
		ii->depth = depth[1];
		ii++;
		ii->depth = depth[2];
		ii++;
		ii->depth = depth[3];
		ii++;
	}

	std::sort(m_vDepth.begin(), m_vDepth.end(), ParticleSorter());
}


Now there are two problems with the code:

 

- Number one, I don't see how to keep temporal coherence, as I did before. This is very bad, as re-sorting the previous-frame sorted depth list is almost twice as fast as the unordered one. Is there any way to perform index sorting, or some other way of sorting particles that is compatible with SIMD?

 

- Number two, this code is only running half of the time. Sometimes it crashes on the first "ii->depth = depth[i]" - line, stating something about a read access violation at a non-null memory adress. It always crashes at another "i", so there really is no pattern, looking at the debugger doesn't tell me anything, since all values seem to be okay, and the adress the error message tells isn't anywhere I can look at in the MSVC debugger. Since I'm new to SIMD, maybe someone can see a mistake in the code I cannot see? Nevermind, shouldn't have done depth[i], depth[i+1] ... but depth[0], depth[1]... fixed the crash, but the first problem still resides - the SIMD code performs far worst er (0.0055 ms instead of 0.003 ms), and profiling tells me that all the performance I gain from quatering the work needed for depth calculation is more than lost lost because the depth vector needs to be sorted frame after frame again from scratch. Any ideas?

 

In case you wonder, this is how I declare the regarding structs:

 

struct Particles
{
	#define BOUNDARY_ALIGNMENT 16

	Particles(unsigned int count)
	{
		/*x = new float[count];
		y = new float[count];
		z = new float[count];*/
		x  = (float*)_mm_malloc(count * sizeof(float), BOUNDARY_ALIGNMENT);
		y  = (float*)_mm_malloc(count * sizeof(float), BOUNDARY_ALIGNMENT);
		z  = (float*)_mm_malloc(count * sizeof(float), BOUNDARY_ALIGNMENT);
	}

	~Particles(void)
	{
		_mm_free(x);
		_mm_free(y);
		_mm_free(z);
		/*delete[] x;
		delete[] y;
		delete[] z;*/
	}

	float* x, *y, *z;
};

		struct ParticleDepth
		{
			int index;
			float depth;
		};

Thanks in advance!

Edited by Juliean
0

Share this post


Link to post
Share on other sites

You might try a radix sort instead of a std::sort.

 

In general a std::sort is O(n*log(n)) complexity and a radix sort is O(n), so it's often faster for large sets. A radix sort's speed will not be affected by the sortedness of the original array, so the fact you have to sort from scratch will not affect you.

 

Whether SIMD + Radix sort will actually end up beating your original approach which took advantage of temporal coherency to accelerate sorting is something you'd have to measure, but my gut feeling is that it's definitely worth a go.

0

Share this post


Link to post
Share on other sites

Thanks for the input,

 

but unfortunately the radix sort performs even worse (takes almost twice the time), but thats probably due to my bad implementation:

 


void acl::gfx::radixsort(ParticleEmitter::DepthVector::iterator first, ParticleEmitter::DepthVector::iterator last, int factor)
{
	// partitionieren
	std::map<int, std::vector<int> > buckets;
	for (ParticleEmitter::DepthVector::const_iterator i = first; i != last; ++i) {
		// get digit and map to bucket
		if (factor == 10) buckets[i->depth%factor].push_back(i->depth);
		else buckets[(i->depth/(factor/10)) %10].push_back(i->depth);
	}
 
	// collect
	ParticleEmitter::DepthVector::iterator copyfirst = first;
	for (int i = 0; i < 10; ++i) {
		for (std::vector<int>::const_iterator it = buckets[i].begin(); it != buckets[i].end(); )
			// collect and apply changes
				copyfirst++->depth = *it++;
	}
 
 
	if (factor > std::max_element(first, last, ParticleSorter())->depth) return;
	radixsort(first, last, factor *= 10);
}

Do you maybe have a better radix implementation so I could give it another shot? My struct now uses an int as key:

 

		struct ParticleDepth
		{
			int index;
			int depth;
		};
Edited by Juliean
0

Share this post


Link to post
Share on other sites

my code appears to be roughly twice as fast as std::sort for big n in my probably wrong tests:

 

http://ideone.com/5aBW1x

 

#include <stdlib.h>
#include <stdint.h>

#include <time.h>
#include <assert.h>

#include <algorithm>
#include <iostream>

void radix_sort(uint32_t *in, uint32_t *out, int shift, int n){
    int index[256] = {};
    for (int i=0; i<n; i++) index[(in[i]>>shift)&0xFF]++;
    for (int i=0, sum=0; i<256; i++) sum += index[i], index[i] = sum - index[i];
    for (int i=0; i<n; i++) out[index[(in[i]>>shift)&0xFF]++] = in[i];
}
void check(int n){
    uint32_t *data = new uint32_t[n];
    uint32_t *temp = new uint32_t[n];
    uint32_t *same = new uint32_t[n];
    for (int i=0; i<n; i++) same[i] = data[i] = (rand()<<16)|rand();// Note: rand() might not produce enough randomness

    clock_t t_radix = clock();

    radix_sort(data, temp,  0, n);
    radix_sort(temp, data,  8, n);
    radix_sort(data, temp, 16, n);
    radix_sort(temp, data, 24, n);

    t_radix = clock() - t_radix;

    clock_t t_sort = clock();

    std::sort(same, same+n);

    t_sort = clock() - t_sort;

    std::cout << "n: " << n << std::endl;
    std::cout << "radix_sort: " << t_radix << std::endl;
    std::cout << "  std:sort: " << t_sort  << std::endl;
    std::cout << std::endl;

    for (int i=0; i<n; i++) assert(same[i] == data[i]);

    delete[] data;
    delete[] temp;
    delete[] same;
}

int main(){
    for (int i=0; i<30; i++) check(1<<i);
    return 0;
}

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