#ifndef BODYSPLASHSYSTEM
#define BODYSPLASHSYSTEM
#include "particlesystem.h"
#include "util_vector.h"
#include "acceleratedparticle.h"
#include "cl_util.h"
#include "r_efx.h"
#include "../common/com_model.h"
#include "const.h"
#include "pm_shared.h"
#include "pmtrace.h"
#include "pm_defs.h"
#include "event_api.h"
#include "r_studioint.h"
#include "studio_util.h"
#include <math.h>
#include "triangleapi.h"
#include "StudioModelRenderer.h"
#include "GameStudioModelRenderer.h"

#define NUMBER_OF_SPLASH_SPRITES 200
extern engine_studio_api_t IEngineStudio;

template <class TParticle> class TBodySplashSystem:public TParticleSystem<TParticle>
{
public:	
	TBodySplashSystem(int ent, int type, HSPRITE sprite):TParticleSystem<TParticle>(ent,type)
	{	m_fRemove = false;		
		m_hsprSprite = sprite;
		cl_entity_t *pClient = gEngfuncs.GetEntityByIndex(ent);
		m_vecStart = pClient->origin;

		for (int i=0;i<NUMBER_OF_SPLASH_SPRITES;i++)
		{	TParticle p(m_hsprSprite);
			SetupParticle(p);
			particles.push_back(p);
		}
	}

	/**
	 * Updates the physics for all particles in the system
	 * @param timeDiff time difference since last draw
	 */
	virtual void think(float time)
	{
		vector<TParticle>::iterator b = particles.begin();
		int iCollisions=0;
 		while (b != particles.end())
 		{
  			if( b->m_fCollision)
			{	
				iCollisions++;				
			}
			else
			{
				b->doThink(time);
				if(b->m_fCollision)
				{
					iCollisions++;				
					if(iCollisions%6)
					{
						//splash!
						pmtrace_t tr;
						gEngfuncs.pEventAPI->EV_SetTraceHull( 2 );
						gEngfuncs.pEventAPI->EV_PlayerTrace( m_vecStart, b->position, PM_STUDIO_BOX, -1, &tr );
						gEngfuncs.pEfxAPI->R_DecalShoot( 
							gEngfuncs.pEfxAPI->Draw_DecalIndex( gEngfuncs.pEfxAPI->Draw_DecalIndexFromName( "{bodypartblob" ) ), 
							gEngfuncs.pEventAPI->EV_IndexFromTrace( &tr ), 0, tr.endpos, 0 );
					}
				}
			}
   			b++;
   		}
		if(particles.size()==iCollisions)
		{
			m_fRemove = true;
		}
 	}

private:
	void SetupParticle(TParticle &p)
	{	vec3_t vecDir;
		vecDir.x = gEngfuncs.pfnRandomFloat( -1, 1 );
		vecDir.y = gEngfuncs.pfnRandomFloat( -1, 1 );
		vecDir.z = gEngfuncs.pfnRandomFloat( -1, 1 );
		VectorNormalize(vecDir);
		p.position = m_vecStart;
		p.startPosition = m_vecStart;
		p.velocity = vecDir*155;
		p.acceleration.z = -150;
		p.m_flSize = gEngfuncs.pfnRandomFloat( 2, 7 );
		p.m_flRotationSpeed = gEngfuncs.pfnRandomFloat( 7, 14 );
		p.m_flStartTime = gEngfuncs.GetClientTime();
		//model_s *pModel = IEngineStudio.GetModelByIndex(m_hsprSprite);
		p.m_iFrame = gEngfuncs.pfnRandomLong(0,SPR_Frames(m_hsprSprite)-1);
		p.m_iRenderMode = kRenderTransAlpha;
		//p.m_iFrame = gEngfuncs.pfnRandomLong(0,2);
	}
	vec3_t m_vecStart;
	HSPRITE m_hsprSprite;
};
#endif