/**
 * @file explosion.c
 */
#include "lephisto.h"
#include "log.h"
#include "pilot.h"
#include "weapon.h"
#include "spfx.h"
#include "rng.h"
#include "explosion.h"

/**
 * @fn void expl_explode(double x, double y, double vx, double vy,
 * double radius, DamageType dtype, double damage,
 *  unsigned int parent, int mode)
 *
 * @brief 
 */
void expl_explode(double x, double y, double vx, double vy,
    double radius, DamageType dtype, double damage,
    unsigned int parent, int mode) { 

  int i, n;
  double a, d;
  double area;
  double ex, ey;
  double layer;
  int efx;
  int exp_s, exp_m, exp_l;

  /* Standard stuff. */
  exp_s = spfx_get("ExpS");
  exp_m = spfx_get("ExpM");
  exp_l = spfx_get("ExpL");
  layer = SPFX_LAYER_FRONT;

  /* Number of explosions. */
  area = M_PI * pow2(radius);
  n = (int)(area / 100.);

  /* Create explosions. */
  for(i = 0; i < n; i++) {
    /* Get position. */
    a = RNGF()*360.;
    d = RNGF()*(radius-5.) + 5.;
    ex = d*cos(a);
    ey = d*sin(a);

    /* Create explosion. */
    efx = (RNG(0,2)==0) ? exp_m : exp_s;
    spfx_add(efx, x+ex, y+ey, vx, vy, layer);
  }

  /* Final explosion. */
  spfx_add(exp_l, x, y, vx, vy, layer);

  /* Run the damage. */
  if(damage > 0.)
    expl_explodeDamage(x, y, radius, dtype, damage, parent, mode);
}

/**
 * @fn 
 *
 * @brief
 */
void expl_explodeDamage(double x, double y, double radius,
    DamageType dtype, double damage,
    unsigned int parent, int mode) {

  /* Explosion affects ships. */
  if(mode & EXPL_MODE_SHIP)
    pilot_explode(x, y, radius, dtype, damage, parent);

  /* Explosion affects missiles and bolts. */
  if((mode & EXPL_MODE_MISSILE) && (mode & EXPL_MODE_BOLT))
    weapon_explode(x, y, radius, dtype, damage, parent, mode);

  /* Explosion affects missiles. */
  else if(mode & EXPL_MODE_MISSILE)
    weapon_explode(x, y, radius, dtype, damage, parent, mode);

  /* Explosion affects bolts. */
  else if(mode & EXPL_MODE_BOLT)
    weapon_explode(x, y, radius, dtype, damage, parent, mode);
}

