/* Bullet stuff for gradient wars

   By James Stanley

   No license - Use as you wish */

#include "bullet.h"

bullet_t *bullet_list;
bullet_t *last_bullet;

void new_bullet(fixed x, fixed y, fixed xs, fixed ys, fixed angle) {
  bullet_t *bullet;
  
  bullet = malloc(sizeof(bullet_t));
  bullet->x = x;
  bullet->y = y;
  bullet->xs = xs;
  bullet->ys = ys;
  bullet->angle = angle;
  bullet->image = bullet1;
  bullet->next = NULL;
  
  if(bullet_list) {
    bullet->prev = last_bullet;
    last_bullet->next = bullet;
  } else {
    bullet->prev = NULL;
    bullet_list = bullet;
  }
  
  last_bullet = bullet;
}

void del_bullet(bullet_t *bullet) {
  if(bullet->next) {//If there's a next bullet, update it's prev pointer
    bullet->next->prev = bullet->prev;
  } else {//bullet == last_bullet
    last_bullet = bullet->prev;
    if(last_bullet) last_bullet->next = NULL;
  }
  
  if(bullet->prev) {
    bullet->prev->next = bullet->next;
  } else {//bullet == bullet_list
    bullet_list = bullet->next;
    if(bullet_list) bullet_list->prev = NULL;
  }
  
  free(bullet);
}

void draw_bullets(BITMAP *canvas) {
  bullet_t *bullet;
  int bx, by;
  
  for(bullet = bullet_list; bullet; bullet = bullet->next) {
    bx = fixtoi(bullet->x);
    by = fixtoi(bullet->y);
    if((bx > (-offsetx)) && (bx < ((-offsetx)+SCR_WIDTH))) {
      if((by > (-offsety)) && (by < ((-offsety)+SCR_HEIGHT))) {
        rotate_sprite(canvas, bullet->image, offsetx+(bx-6), offsety+(by-6), bullet->angle);
      }
    }
  }
}

void update_bullets(void) {
  bullet_t *bullet = bullet_list;
  bullet_t *bullet_next;
  
  while(bullet) {
    bullet->x += bullet->xs;
    bullet->y += bullet->ys;
    
    bullet_next = bullet->next;
    
    if(bullet->x < 0) del_bullet(bullet);
    else if(bullet->x > itofix(WIDTH)) del_bullet(bullet);
    else if(bullet->y < 0) del_bullet(bullet);
    else if(bullet->y > itofix(HEIGHT)) del_bullet(bullet);
    
    bullet = bullet_next;
  }
}

void del_all_bullets(void) {
  bullet_t *bullet;
  
  while(bullet_list) {
    bullet = bullet_list->next;
    free(bullet_list);
    bullet_list = bullet;
  }
  
  last_bullet = NULL;
}
