#include "proc_explosio.h"
#include <stdlib.h>
#include "jgame.h"

namespace explosio
{
    struct tipo_pix // Cada pixel de la explosió
    {
        float x, y;
        float xa, ya;
        float g;
        uint8_t c;
    };

    struct tipo_exp // Tipo per a les explosions
    {
        int numpix;
        tipo_pix pix[50];
        int count;
    };

    static tipo_exp exp[10];
    static int numexp {0};

    void crear(const int x, const int y, const int num, const int c1, const int c2, const int c3)
    {
        if ( numexp >= 9 || numexp < 0 ) return;

        exp[numexp].count = 0;
        exp[numexp].numpix = num*2;
        const int expansio = c2*100;
        for (int i=0; i<=exp[numexp].numpix; ++i)
        {
            exp[numexp].pix[i].x  = x;
            exp[numexp].pix[i].y  = y;
            exp[numexp].pix[i].xa = float((rand()%expansio) - (expansio >> 1))/1000.0f;
            exp[numexp].pix[i].ya = float((rand()%expansio) - (expansio >> 1))/1000.0f;
            exp[numexp].pix[i].g  = 0.05;
            exp[numexp].pix[i].c  = rand()%60;
        }
        numexp++;
    }

    void pintar()
    {
        int c1 = 0;

        while (c1 != numexp)
        {
            for (int c2=0; c2<=exp[c1].numpix; ++c2)
            {
                exp[c1].pix[c2].x  = exp[c1].pix[c2].x  + exp[c1].pix[c2].xa;
                exp[c1].pix[c2].ya = exp[c1].pix[c2].ya + exp[c1].pix[c2].g;
                exp[c1].pix[c2].y  = exp[c1].pix[c2].y  + exp[c1].pix[c2].ya;
                //if ((exp[c1].pix[c2].x > 0) && (exp[c1].pix[c2].x < 319) && (exp[c1].pix[c2].y > 0) && (exp[c1].pix[c2].y < 199))
                    draw::putPixel(exp[c1].pix[c2].x, exp[c1].pix[c2].y, exp[c1].pix[c2].c);
            }
            exp[c1].count++;

            c1++;

            if (exp[c1-1].count == 80)
            {
                numexp--;
                c1--;
                if (c1 != numexp)
                {
                    exp[c1] = exp[numexp];
                }
            }
        }
    }

}