/* Bob */

#include <math.h>
#include "main.h"
#include "tilemap.h"
#include "sprite.h"
#include "sprhelp.h"
#include "s_animal.h"
#include "s_anim_s.h"
#include "player.h"
#include "collide.h"
#include "options.h"
#include "log.h"



SPRITE *add_portal_sprite(TILEMAP *map, SPRITE *sprite, int x, int y) {
 SPRITE *newsprite = add_sprite(sprite);
 PORTAL *portal;

 newsprite->life = 1; /* Alive - not really, but we don't want to kill it :) */

 newsprite->type = SPRITE_TYPE_PORTAL;

 newsprite->x = x + 0.5;
 newsprite->y = y + 0.5;
 newsprite->z = map->tile[y][x].z + 0.5;

 newsprite->xv = 0;
 newsprite->yv = 0;
 newsprite->zv = 0;

 newsprite->r = 0.47;

 newsprite->anim = Portal;
 newsprite->anim_speed = 9362;
 newsprite->cur_frame = 0;
 newsprite->num_frames = 7;

 portal = newsprite->data = malloc(sizeof(PORTAL));
 if (!portal) exit(37);
 portal->tick = random() % 250;

 return newsprite;
}



void draw_portal(BITMAP *bmp, SPRITE *sprite, float cth) {

	/* PORTAL *portal = sprite->data; */

	(void)cth;

    ASSERT(sprite);

	draw_generic_sprite(bmp, sprite, sprite->anim[sprite->cur_frame >> 16], POLYTYPE_ATEX_MASK);
}




void update_portal(TILEMAP *map, SPRITE *sprite) {

	PORTAL *portal = sprite->data;

	(void)map;

	portal->tick++;
	sprite->cur_frame += sprite->anim_speed;

	if (sprite->cur_frame >= itofix(sprite->num_frames))
		sprite->cur_frame = 0;

	if (portal->tick > (1 / (((animal_rate == 3) ? 5 : animal_rate) + .001)) * 1800) {
		portal->tick = 0;

		spawn_animal(sprite);
	}
}



void si_portal(TILEMAP *map, SPRITE *spr1, SPRITE *spr2) {

 SPRITE *portal;
 SPRITE *other;

 float xd, yd, zd;
 float d, r;

 if (spr1->type == SPRITE_TYPE_PORTAL) {
  portal = spr1;
  other = spr2;
 } else {
  portal = spr2;
  other = spr1;
 }

 xd = other->x - portal->x;
 yd = other->y - portal->y;
 zd = other->z - portal->z;

 d = xd*xd + yd*yd + zd*zd;

 r = portal->r + other->r;

 if (d < r*r) {

  d = sqrt(d);

  xd /= d;
  yd /= d;
  zd /= d;

  d = r - d;

  other->x += xd*d;
  other->y += yd*d;
  other->z += zd*d;
  sprite_tilemap_collision(map, other, NULL);

/* Remnants of code from collide.c
  d = xd*sprite->xv + yd*sprite->yv + zd*sprite->zv;

  if (d < 0) {

   float e = 2*d;
   sprite->xv -= xd*e;
   sprite->yv -= yd*e;
   sprite->zv -= zd*e;

   if (callback) {
    *sx = xd*xd;
    *sy = yd*yd;
    *sz = zd*zd;

    (*callback)(sprite, xvtx, yvtx, zvtx, -d, 1, tile, hit);

    *sx = 0;
    *sy = 0;
    *sz = 0;
   }
  }
*/
 }
}
