#include "Lightning.h"

Lightning::Lightning(void)
{
}

bool Lightning::init()
{
	 if(!lightning_tex.LoadTGA("pics/lightning2.tga")) return false;
   glGenTextures(1, &lightning_tex.ID);
   
   glBindTexture(GL_TEXTURE_2D, lightning_tex.ID);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

   int type = lightning_tex.type == 3 ? GL_RGB : GL_RGBA;
   glTexImage2D(GL_TEXTURE_2D,0, lightning_tex.type, lightning_tex.imageWidth, lightning_tex.imageHeight, 0,
                     type, GL_UNSIGNED_BYTE, lightning_tex.image);


    m_p_emitter = new Cpart_emitter(30);

	//Vector3 pos = Vector3(2*((rand() % 400)-200),	50,		-550 -(2*(rand() % 500)));
	Vector3 pos = Vector3(0.0,40,0.0);
	Vector3 vel = Vector3(0.0,0.0,0.0);
	float color[4] = { 1,1,1,1};
	float size = 60.0f + ( (rand() % 10)  -5)*0.1;
	int ttl = 15;
	float fade_vel = 0.2;
	Cparticle* part = new Cparticle(m_p_emitter);
	part->set_particle(pos, vel, color, size,ttl,fade_vel);

	m_p_emitter->add_particle(part);

	old_pos = Vector3(0.0,80.0,0.0);

	light_count = 0;

   return true;
}

void Lightning::add()
{
	
	//Vector3 pos = Vector3(2*((rand() % 400)-200),	50,		-550 -(2*(rand() % 500)));
	//Vector3 pos = Vector3(0.0,15.0,0.0);
	Vector3 vel = Vector3(0.0,0.0,0.0);
	float color[4] = { 1,1,1,.1};
	float size = 60.0f + ( (rand() % 10)  -5)*0.1;
	int ttl = 200 + (rand() % 10);
	float fade_vel = 0.01;
	Cparticle* part = new Cparticle(m_p_emitter);
	part->set_particle(old_pos, vel, color, size,ttl,fade_vel);

	if (!m_p_emitter->add_particle(part)) m_p_emitter->clear_vec();


}

void Lightning::rnd_add ()
{
	
	Vector3 pos = old_pos;
	int my_rand = rand() % 10;
	if (my_rand >=4) {
		double x = (double) (rand() % 30 - 15);
		double z = (double) (rand() % 30 - 15);
		old_pos= Vector3 (x,40.0,z);
	}
	if (my_rand <=3) //create multiple at the same position
	{
		
		Vector3 vel = Vector3(0.0,0.0,0.0);
		float color[4] = { 1,1,1,.1};
		float size = 60.0f + ( (rand() % 10)  -5)*0.1;
		int ttl = 200 + (rand() % 10);
		float fade_vel = 0.01;
		Cparticle* part = new Cparticle(m_p_emitter);
		part->set_particle(pos, vel, color, size,ttl,fade_vel);

		if (!m_p_emitter->add_particle(part)) m_p_emitter->clear_vec();
	}


}

void Lightning::update()
{
	//call rnd_add() again to add some overlaying lightnings
	int my_rand = rand() % 1000;
	if (my_rand >=998) rnd_add();


	

	glEnable(GL_TEXTURE_2D);
	

	//glRotated(180,1,0,0);
	//glTranslated(0,-30,0);
	float mat_color[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
	glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, mat_color);

	glBindTexture(GL_TEXTURE_2D, lightning_tex.ID);

     m_p_emitter->update();
	 if (m_p_emitter->light) light_count++;

    glDisable(GL_TEXTURE_2D);
	
}
Lightning::~Lightning(void)
{
}
