enemy.c 97.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
/* 
 *   Copyright (c) 1994, 2002, 2003 Johannes Prix
 *   Copyright (c) 1994, 2002 Reinhard Prix
 *   Copyright (c) 2004-2010 Arthur Huillet 
 *
 *  
 *  This file is part of Freedroid
 *
 *  Freedroid is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  Freedroid is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Freedroid; see the file COPYING. If not, write to the 
 *  Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, 
 *  MA  02111-1307  USA
 *
 */

/**
 * This file contains all enemy related functions.  This includes their 
 * whole behavior, healing, initialization, shuffling them around after 
 * elevator-transitions, deleting them, collisions of enemies among 
 * themselves, their fireing, animation and such.
 */

#define _enemy_c

#include "system.h"

#include "defs.h"
#include "struct.h"
#include "global.h"
#include "proto.h"

#define COL_SPEED		3
#define IS_FRIENDLY_EYE_DISTANCE (2.0)

static int next_bot_id = 1; // defines the id of the next created enemy.

static int TurnABitTowardsPosition(Enemy, float, float, float);
static void MoveToMeleeCombat(Enemy, gps *, moderately_finepoint *);
static void MoveAwayFromMeleeCombat(Enemy, moderately_finepoint *);
static void ReachMeleeCombat(Enemy, gps *, moderately_finepoint *, pathfinder_context *);
static void RawStartEnemysShot(enemy *, float, float);
static int is_potential_target(enemy * this_robot, gps * target_pos, float *squared_best_dist);
53
static int can_see_tux(enemy *);
54 55 56 57 58

LIST_HEAD(alive_bots_head);
LIST_HEAD(dead_bots_head);
list_head_t level_bots_head[MAX_LEVELS];	//THIS IS NOT STATICALLY PROPERLY INITIALIZED, done in init functions

59 60 61 62 63 64 65 66 67 68 69 70 71 72
/* Definition of the sensors. The flag_set values must be exclusive,
 * so that given a flag_set we can get a unique associated name. */

struct {
	char *name;
	int flag_set;
} enemy_sensors[] = {
		{ "infrared", SENSOR_DETECT_INVISIBLE                        },
		{ "xray",     SENSOR_THROUGH_WALLS                           },
		{ "radar",    SENSOR_DETECT_INVISIBLE | SENSOR_THROUGH_WALLS },
		{ "spectral", SENSOR_FEATURELESS                             }
};


73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
static void teleport_to_waypoint(enemy *robot, level *lvl, int wp_idx)
{
	waypoint *wpts = lvl->waypoints.arr;

	// Teleport the robot to the waypoint
	robot->pos.x = wpts[wp_idx].x + 0.5;
	robot->pos.y = wpts[wp_idx].y + 0.5;
	robot->pos.z = lvl->levelnum;
	robot->nextwaypoint = wp_idx;
	robot->lastwaypoint = wp_idx;
}

/**
 * Find the closest waypoint to a bot.
 */
static int enemy_find_closest_waypoint(struct enemy *this_bot)
{
	struct level *lvl = curShip.AllLevels[this_bot->pos.z];
	struct waypoint *wpts = lvl->waypoints.arr;

	int i;
	float distance = 0.0;
	float best_distance = 10000.0;
	int best_waypoint = -1;

	for (i = 0; i < lvl->waypoints.size; i++) {
		// A standard bot cannot use a special waypoint
		if (!this_bot->SpecialForce && wpts[i].suppress_random_spawn)
			continue;

		// If no best_waypoint is already registered, use the current one as
		// a fallback result.
		if (best_waypoint == -1)
			best_waypoint = i;

		// Check if current waypoint is closer than the stored one.
		distance = (this_bot->pos.x - wpts[i].x + 0.5) * (this_bot->pos.x - wpts[i].x + 0.5) +
		           (this_bot->pos.y - wpts[i].y + 0.5) * (this_bot->pos.y - wpts[i].y + 0.5);
		if (distance <= best_distance) {
			best_distance = distance;
			best_waypoint = i;
		}
	}

	if (best_waypoint == -1)
118
		error_message(__FUNCTION__, "Found no closest waypoint on level %d.", PLEASE_INFORM, lvl->levelnum);
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181

	return best_waypoint;
}

/**
 * In the very beginning of each game, it is not enough to just place the
 * bots onto the right locations.  They must also be integrated into the
 * waypoint system, i.e. current waypoint and next waypoint initialized.
 */
int teleport_to_closest_waypoint(struct enemy *ThisRobot)
{
	struct level *lvl = curShip.AllLevels[ThisRobot->pos.z];

	// Find the closest waypoint
	int best_waypoint = enemy_find_closest_waypoint(ThisRobot);

	if (best_waypoint >= 0) {
		// Teleport the robot to the best waypoint
		teleport_to_waypoint(ThisRobot, lvl, best_waypoint);
	} else {
		// No waypoint found, make this bot wander
		ThisRobot->combat_state = WAYPOINTLESS_WANDERING;
	}

	return best_waypoint;
}

/**
 * Randomly teleports a standard bot to a free (not already occupied) waypoint.
 *
 * A random waypoint is chosen. All waypoints are examined in turn, starting
 * from the random one, until a free one is found.
 * If no free waypoint is found, the bot is teleported to the last checked
 * waypoint.
 *
 * Note: only the waypoints not forbidden for randomly placed bots are scanned.
 */
int teleport_to_random_waypoint(enemy *erot, level *this_level, char *wp_used)
{
	int start_wp = MyRandom(this_level->waypoints.size - 1);
	waypoint *wpts = this_level->waypoints.arr;
	int current_wp = start_wp;
	int last_checked_wp = -1;
	int found_wp = -1;

	// Find a random waypoint
	do {
		if (!wpts[current_wp].suppress_random_spawn) {
			last_checked_wp = current_wp;
			if (!wp_used[current_wp]) {
				found_wp = current_wp;
				break;
			}
		}
		// next waypoint, going to 0 if at end of list
		current_wp++;
		if (current_wp == this_level->waypoints.size)
			current_wp = 0;
	} while (found_wp == -1 && current_wp != start_wp); // stop when found, or when all waypoints have been scanned

	// Use a fallback waypoint if no free waypoint is found
	if (found_wp == -1) {
		if (last_checked_wp == -1) {
182 183 184
			error_message(__FUNCTION__, "All waypoints on level %d are forbidden for random bots. Something is wrong."
			                           " Forcing the bot to teleport to a forbidden waypoint.",
			                           PLEASE_INFORM, this_level->levelnum);
185 186
			found_wp = start_wp;
		} else {
187 188
			error_message(__FUNCTION__, "There was no free waypoint found on level %d to place another random bot.",
			                            NO_REPORT, this_level->levelnum);
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
			found_wp = last_checked_wp;
		}
	}

	wp_used[found_wp] = 1;

	// Teleport the robot to the found waypoint
	teleport_to_waypoint(erot, this_level, found_wp);

	return found_wp;
}

/**
 * This function teleports an enemy to a new position on the
 * map. 
 */
void teleport_enemy(enemy *robot, int z, float x, float y)
{
	// Check the validity of the teleport destination
	if (!level_exists(z) || !pos_inside_level(x, y, curShip.AllLevels[z])) {
209
		error_message(__FUNCTION__, "\
210 211
				Trying to teleport NPC (dialog name %s) from x=%f y=%f level=%d to x=%f y=%f level=%d\n\
				is not possible because the target location is not valid.", 
212
				PLEASE_INFORM, robot->dialog_section_name, robot->pos.x, robot->pos.y, robot->pos.z, x, y, z);
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
		return;
	}

	// Does the robot change level?
	if (z != robot->pos.z) {
		robot->pos.z = z;

		// Add the bot on the new level
		list_move(&robot->level_list, &(level_bots_head[robot->pos.z]));
	}

	// Prevent the bot from moving this frame
	clear_out_intermediate_points(&robot->pos, &robot->PrivatePathway[0], 5);

	// Move the bot
	robot->pos.x = x;
	robot->pos.y = y;

	// Reset the bot's waypoints
	int best_waypoint = enemy_find_closest_waypoint(robot);

	if (best_waypoint >= 0) {
		robot->homewaypoint = best_waypoint;
		robot->lastwaypoint = best_waypoint;
		robot->nextwaypoint = best_waypoint;
	} else {
		// No waypoint found, make this bot wander
		robot->combat_state = WAYPOINTLESS_WANDERING;
	}
}

/**
 * Enemies recover with time, independently of the current frame rate.
 */
static void heal_robots_over_time(void)
{
	static float time_since_last_heal = 0;
#define HEAL_INTERVAL (3.0)

	// Heal the bots every HEAL_INTERVAL seconds
	time_since_last_heal += Frame_Time();
	if (time_since_last_heal < HEAL_INTERVAL)
		return;
	time_since_last_heal = 0;

	enemy *erot;
	BROWSE_ALIVE_BOTS(erot) {
		float heal_factor;
		if (is_friendly(erot->faction, FACTION_SELF))
262
			heal_factor = Droidmap[erot->type].healing_friendly;
263
		else
264 265
			heal_factor = Droidmap[erot->type].healing_hostile;
		if (erot->energy < Droidmap[erot->type].maxenergy)
266
			erot->energy += heal_factor * HEAL_INTERVAL;
267 268
		if (erot->energy > Droidmap[erot->type].maxenergy)
			erot->energy = Droidmap[erot->type].maxenergy;
269 270 271 272 273 274 275 276 277 278 279 280
	}
}

/**
 * This function resets the 'transient state' of a bot.
 * (see the 'struct enemy' comments)
 */
void enemy_reset(enemy *this_enemy)
{
	int j;

	this_enemy->speed.x = this_enemy->speed.y = 0.0;
281
	this_enemy->energy = Droidmap[this_enemy->type].maxenergy;
282 283 284 285 286 287 288 289
	this_enemy->animation_phase = 0;
	this_enemy->animation_type = WALK_ANIMATION;
	this_enemy->frozen = 0.0;
	this_enemy->poison_duration_left = 0.0;
	this_enemy->poison_damage_per_sec = 0.0;
	this_enemy->paralysation_duration_left = 0.0;
	this_enemy->pure_wait = 0.0;
	this_enemy->firewait = 0.0;
290
	this_enemy->ammo_left = ItemMap[Droidmap[this_enemy->type].weapon_item.type].weapon_ammo_clip_size;
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
	this_enemy->attack_target_type = ATTACK_TARGET_IS_NOTHING;
	enemy_set_reference(&this_enemy->bot_target_n, &this_enemy->bot_target_addr, NULL);
	this_enemy->previous_angle = 0.0;
	this_enemy->current_angle = 0.0;
	this_enemy->previous_phase = 0.0;
	this_enemy->last_phase_change = WAIT_BEFORE_ROTATE + 1.0;
	this_enemy->last_combat_step = ATTACK_MOVE_RATE + 1.0;
	this_enemy->TextVisibleTime = 0.0;
	this_enemy->TextToBeDisplayed = NULL;
	for (j = 0; j < 5; j++) {
		this_enemy->PrivatePathway[j].x = -1;
		this_enemy->PrivatePathway[j].y = -1;
	}
	this_enemy->bot_stuck_in_wall_at_previous_check = FALSE;
	this_enemy->time_since_previous_stuck_in_wall_check = ((float)MyRandom(1000)) / 1000.1;
}

/**
 * This function prepares the droid's fabric to create a whole new
 * set of droids.
 */
void enemy_reset_fabric()
{
	next_bot_id = 1;
}

/**
 * This function creates a new enemy, and initializes its 'identity' and
 * 'global state'.
 * (see the 'struct enemy' comments)
 */
enemy *enemy_new(int type)
{
	enemy *this_enemy = (enemy*)MyMalloc(sizeof(enemy));
	memset(this_enemy, 0, sizeof(enemy));

	this_enemy->id = next_bot_id++;
	this_enemy->type = type;

	// Init 'identity' attributes.
	this_enemy->SpecialForce = FALSE;
	this_enemy->marker = 0;
	this_enemy->max_distance_to_home = 0;
	this_enemy->dialog_section_name = NULL;
335
	this_enemy->short_description_text = strdup(Droidmap[this_enemy->type].default_short_description);
336
	this_enemy->on_death_drop_item_code = -1;
337 338
	this_enemy->sensor_id = Droidmap[this_enemy->type].sensor_id;
	
339 340
	// Set the default value of the 'global state' attributes
	this_enemy->faction = FACTION_BOTS;
341
	this_enemy->will_respawn = TRUE;
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
	this_enemy->will_rush_tux = FALSE;
	this_enemy->combat_state = WAYPOINTLESS_WANDERING;
	this_enemy->state_timeout = 0.0;
	this_enemy->CompletelyFixed = 0;
	this_enemy->has_been_taken_over = FALSE;
	this_enemy->follow_tux = FALSE;
	this_enemy->has_greeted_influencer = FALSE;
	this_enemy->homewaypoint = this_enemy->lastwaypoint = this_enemy->nextwaypoint = -1;

	return this_enemy;
}

/**
 * Insert an enemy into the global lists and the level lists, depending on its
 * state (living or dead)
 */
void enemy_insert_into_lists(enemy *this_enemy, int is_living)
{
	list_add(&(this_enemy->global_list), is_living ? &alive_bots_head : &dead_bots_head);
	if (is_living) {
		list_add(&this_enemy->level_list, &level_bots_head[this_enemy->pos.z]);
	}
}

/*
 * Free an enemy data structure
 */
369
void enemy_free(enemy *e)
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
{
	if (e->dialog_section_name) {
		free(e->dialog_section_name);
		e->dialog_section_name = NULL;
	}
	if (e->short_description_text) {
		free(e->short_description_text);
		e->short_description_text = NULL;
	}

	free(e);
}

/**
 * This function removes all enemy entries from the list of the
 * enemies.
 */
void clear_enemies(void)
{
	enemy *erot, *nerot;

	int i;
	for (i = 0; i < MAX_LEVELS; i++) {
		INIT_LIST_HEAD(&level_bots_head[i]);
	}

	BROWSE_ALIVE_BOTS_SAFE(erot, nerot) {
		list_del(&erot->global_list);
		enemy_free(erot);
	}

	BROWSE_DEAD_BOTS_SAFE(erot, nerot) {
		list_del(&erot->global_list);
		enemy_free(erot);
	}

	INIT_LIST_HEAD(&alive_bots_head);
	INIT_LIST_HEAD(&dead_bots_head);

	enemy_reset_fabric();
}

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
/** Helper to modify the enemy state
 * with a constant set of names.
 */
void enemy_set_state(enemy *en, const char *cmd)
{
	if (!strcmp(cmd, "follow_tux")) {
		en->follow_tux = TRUE;
		en->CompletelyFixed = FALSE;
	} else if (!strcmp(cmd, "fixed")) {
		en->follow_tux = FALSE;
		en->CompletelyFixed = TRUE;
	} else if (!strcmp(cmd, "free")) {
		en->follow_tux = FALSE;
		en->CompletelyFixed = FALSE;
	} else if (!strcmp(cmd, "home")) {
		en->follow_tux = FALSE;
		en->CompletelyFixed = FALSE;
		en->combat_state = RETURNING_HOME;
	} else if (!strcmp(cmd, "patrol")) {
		en->follow_tux = FALSE;
		en->CompletelyFixed = FALSE;
		en->combat_state = SELECT_NEW_WAYPOINT;
	} else {
		error_message(__FUNCTION__,
		     "I was called with an invalid state named %s. Accepted values are \"follow_tux\", \"fixed\", \"free\", \"home\", and \"patrol\".",
		     PLEASE_INFORM, cmd);
	}
}

int enemy_set_destination(enemy *en, const char *label)
{
	gps dest_pos = get_map_label_center(label);
	struct level *lvl = curShip.AllLevels[dest_pos.z];
	int destinationwaypoint = get_waypoint(lvl, dest_pos.x, dest_pos.y);

	if (dest_pos.z !=  en->pos.z) {
		error_message(__FUNCTION__, "\
				Sending bot %s to map label %s (found on level %d) cannot be done because the bot\n\
				is not on the same level (z = %d). Doing nothing.",
				PLEASE_INFORM, en->dialog_section_name, label, dest_pos.z, en->pos.z);
		return 0;
	}

	if (destinationwaypoint == -1) {
		error_message(__FUNCTION__, "\
				Map label %s (found on level %d) does not have a waypoint. Cannot send bot %s\n\
				to this location. Doing nothing.\n\
				GPS center coordinates x=%f, y=%f.",
				PLEASE_INFORM, label, dest_pos.z, en->dialog_section_name, dest_pos.x, dest_pos.y);
		return 0;
	}

	clear_out_intermediate_points(&en->pos, &en->PrivatePathway[0], 5);
	en->lastwaypoint = destinationwaypoint;
	en->nextwaypoint = destinationwaypoint;
	en->combat_state = TURN_TOWARDS_NEXT_WAYPOINT;
	return 0;
}

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
static void enemy_get_current_walk_target(enemy *ThisRobot, moderately_finepoint *a)
{
	int count;

	// Get the number of path nodes.
	for (count = 0; count < 5; count++) {
		if (ThisRobot->PrivatePathway[count].x == -1) 
			break;
	}

	// If the path isn't empty, return the coordinates of the last
	// path node. Otherwise, return the current position of the bot.
	if (count) {
		a->x = ThisRobot->PrivatePathway[count - 1].x;
		a->y = ThisRobot->PrivatePathway[count - 1].y;
	} else {
		a->x = ThisRobot->pos.x;
		a->y = ThisRobot->pos.y;
	}
}

/**
 * This function moves one robot in an advanced way, that hasn't been
 * present within the classical paradroid game.
 */
static float remaining_distance_to_current_walk_target(Enemy ThisRobot)
{
	moderately_finepoint remaining_way;

	enemy_get_current_walk_target(ThisRobot, &remaining_way);

	remaining_way.x -= ThisRobot->pos.x;
	remaining_way.y -= ThisRobot->pos.y;

	return (sqrt(remaining_way.x * remaining_way.x + remaining_way.y * remaining_way.y));

};				// float remaining_distance_to_current_walk_target ( Enemy ThisRobot )

/**
 *
 *
 */
static void DetermineAngleOfFacing(enemy * e)
{
	// The phase now depends upon the direction this robot
	// is heading.
	//
	// We calculate the angle of the vector, but only if the robot has at least
	// some minimal speed.  If not, simply the previous angle will be used again.
	//
521
	if ((fabs(e->speed.y) > 0.03) || (fabs(e->speed.x) > 0.03)) {
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
		e->current_angle = 180 - (atan2(e->speed.y, e->speed.x) * 180 / M_PI + 90);
		e->previous_angle = e->current_angle;
	} else {
		e->current_angle = e->previous_angle;
	}
};				// void DetermineAngleOfFacing ( int EnemyNum )

/**
 * Once the next waypoint or the next private pathway point has been 
 * selected, this generic low_level movement function can be called to
 * actually move the robot towards this spot.
 */
static void move_enemy_to_spot(Enemy ThisRobot, moderately_finepoint next_target_spot)
{
	moderately_finepoint remaining_way;
	float maxspeed;
	int old_map_level;

	// According to properties of the robot like being frozen or not,
	// we define the maximum speed of this machine for later use...
	// A frozen robot is slow while a paralyzed robot can do absolutely nothing.
	//
	// if ( ThisRobot -> paralysation_duration_left != 0 ) return;

	if (ThisRobot->frozen == 0)
547
		maxspeed = Droidmap[ThisRobot->type].maxspeed;
548
	else
549
		maxspeed = 0.2 * Droidmap[ThisRobot->type].maxspeed;
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577

	// While getting hit, the bot or person shouldn't be running, but
	// when standing, it should move over to the 'walk' animation type...
	//
	if (ThisRobot->animation_type == GETHIT_ANIMATION)
		return;
	if (ThisRobot->animation_type == STAND_ANIMATION) {
		ThisRobot->animation_type = WALK_ANIMATION;
		ThisRobot->animation_phase = 0.0;
	}

	remaining_way.x = next_target_spot.x - ThisRobot->pos.x;
	remaining_way.y = next_target_spot.y - ThisRobot->pos.y;

	float squared_length = remaining_way.x * remaining_way.x + remaining_way.y * remaining_way.y;
	gps newpos = ThisRobot->pos;

	if (squared_length < DIST_TO_INTERM_POINT * DIST_TO_INTERM_POINT) {
		ThisRobot->speed.x = 0;
		ThisRobot->speed.y = 0;
		newpos.x = next_target_spot.x;
		newpos.y = next_target_spot.y;
	} else {
		if ((Frame_Time() > 0.001)) {
			float length = sqrt(squared_length);

			ThisRobot->speed.x = maxspeed * remaining_way.x / length;
			ThisRobot->speed.y = maxspeed * remaining_way.y / length;
578
			if (fabs(ThisRobot->speed.x * Frame_Time()) >= fabsf(remaining_way.x))
579
				ThisRobot->speed.x = remaining_way.x / Frame_Time();
580
			if (fabs(ThisRobot->speed.y * Frame_Time()) >= fabsf(remaining_way.y))
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
				ThisRobot->speed.y = remaining_way.y / Frame_Time();
			newpos.x = ThisRobot->pos.x + ThisRobot->speed.x * Frame_Time();
			newpos.y = ThisRobot->pos.y + ThisRobot->speed.y * Frame_Time();
		}
	}

	// Now the bot is moving, so maybe it's crossing a level's border ?
	// In this case, we have to reset the waypoints stored in the bot struct,
	// because those waypoints have no more sense in the new bot's level.

	if (!resolve_virtual_position(&newpos, &newpos))
		return;

	old_map_level = ThisRobot->pos.z;
	ThisRobot->pos.x = newpos.x;
	ThisRobot->pos.y = newpos.y;
	ThisRobot->pos.z = newpos.z;

	if (ThisRobot->pos.z != old_map_level) {	/* if the bot has changed level */
		// Prevent the bot from moving this frame
		clear_out_intermediate_points(&ThisRobot->pos, &ThisRobot->PrivatePathway[0], 5);

		// The waypoints used by the bot have no sense on this new level. They have
		// to be re-initialized. The closest available waypoint is chosen.
		int best_waypoint = enemy_find_closest_waypoint(ThisRobot);

		if (best_waypoint >= 0) {
			ThisRobot->homewaypoint = best_waypoint;
			ThisRobot->lastwaypoint = best_waypoint;
			ThisRobot->nextwaypoint = best_waypoint;
		} else {
			// No waypoint found, make this bot wander
			ThisRobot->combat_state = WAYPOINTLESS_WANDERING;
		}
		// Move the bot to the appropriate level list
		list_move(&ThisRobot->level_list, &(level_bots_head[ThisRobot->pos.z]));
	}

	DetermineAngleOfFacing(ThisRobot);
}

/**
 * This function moves one robot towards his next waypoint.  If already
 * there, the function does nothing more.
 */
static void MoveThisRobotTowardsHisCurrentTarget(enemy *ThisRobot)
{
	if (ThisRobot->animation_type == ATTACK_ANIMATION)
		return;

	if ((ThisRobot->PrivatePathway[0].x == ThisRobot->pos.x) && (ThisRobot->PrivatePathway[0].y == ThisRobot->pos.y)) {
		if (ThisRobot->PrivatePathway[1].x != -1) {
			int i;
			for (i = 1; i < 5; i++) {
				ThisRobot->PrivatePathway[i - 1].x = ThisRobot->PrivatePathway[i].x;
				ThisRobot->PrivatePathway[i - 1].y = ThisRobot->PrivatePathway[i].y;
			}
			ThisRobot->PrivatePathway[4].x = -1;
			ThisRobot->PrivatePathway[4].y = -1;
		}
		return;
	}

	move_enemy_to_spot(ThisRobot, ThisRobot->PrivatePathway[0]);

	if ((fabsf(ThisRobot->pos.x - ThisRobot->PrivatePathway[0].x) < 0.001)
	    && fabsf(ThisRobot->pos.y - ThisRobot->PrivatePathway[0].y) < 0.001) {	/* Have we reached our target ? */
		int i;
		for (i = 1; i < 5; i++) {
			ThisRobot->PrivatePathway[i - 1].x = ThisRobot->PrivatePathway[i].x;
			ThisRobot->PrivatePathway[i - 1].y = ThisRobot->PrivatePathway[i].y;
		}
		ThisRobot->PrivatePathway[4].x = -1;
		ThisRobot->PrivatePathway[4].y = -1;
	}

	if (ThisRobot->PrivatePathway[0].x == -1) {
		ThisRobot->PrivatePathway[0].x = ThisRobot->pos.x;
		ThisRobot->PrivatePathway[0].y = ThisRobot->pos.y;
	}
}

/**
 * This function sets a new waypoint to a bot.
 *
 * Returns TRUE if everything was OK, FALSE if couldn't set a new waypoint.
 *
 * The new waypoint is randomly chosen in a list of potentially usable
 * connections. We want the previous waypoint to have a lower probability
 * in order to avoid bots going back on their steps too often.
 *
 * This should imply to generate a non-uniform random value. However this
 * is not needed here. Let's say that we have 3 potential new waypoints
 * { A, B, C }, A being the previous waypoint. If p(A) is 3 times lower
 * than the probability of the other waypoints, then we can use a uniform
 * random value, to choose a waypoint in the following set:
 * { A, B, B, B, C, C, C }
 *
 * Implementation:
 *
 * instead of replicating waypoints, we only keep a restricted { B, C } set,
 * and use the following trick:
 *
 * - rnd is a random value in the [0, 7[ range. (7 = cardinality of the
 *   whole set, with replicated waypoints).
 * - if rnd is 0, then 'A' is chosen.
 * - if 1 <= rnd <= 3, so if (rnd-1)/3 == 0, then 'B' is chosen
 * - if 4 <= rnd <= 6, so if (rnd-1)/3 == 1, then 'C' is chosen
 *
 * so, if rnd != 0, then (rnd-1)/3 is the index of the waypoint to
 * choose in the 'restricted' set.
 */
static int set_new_random_waypoint(enemy *this_robot)
{
	const int PMULT = 3; // Probability multiplier
	int i;
	int nb_free_waypoints;
	int lastwaypoint_is_free;

	level *bot_level = curShip.AllLevels[this_robot->pos.z];

	// If the bot is not tied into the waypoint system, do not select a new waypoint
	if (this_robot->nextwaypoint == -1) {
		return FALSE;
	}

	// nextwaypoint is actually the waypoint that the bot just reached.
	waypoint *current_waypoint = &((waypoint *)bot_level->waypoints.arr)[this_robot->nextwaypoint];

	// Pre-condition: there must be some connections
	//
	int num_conn = current_waypoint->connections.size;
	if (num_conn == 0)	// no connections found!
	{
715
		error_message(__FUNCTION__,
716 717
				     "Found a waypoint without connection\n"
				     "The offending waypoint nr. is: %d at %d, %d.\n"
718
				     "The map level in question got nr.: %d.",
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
				     PLEASE_INFORM,
				     this_robot->nextwaypoint, current_waypoint->x, current_waypoint->y,
				     this_robot->pos.z);
		return FALSE;
	}

	// For each connected waypoint, check if the path to this waypoint
	// is free of droids, and if so, store the waypoint.
	// Special case (see function's comment): the previous waypoint
	// (called 'lastwaypoint') is not stored, but a flag is set if its
	// path is free.
	//
	nb_free_waypoints = 0;
	lastwaypoint_is_free = FALSE;
	freeway_context frw_ctx = { .check_tux = TRUE, .except_bots = {this_robot, NULL} };

	int free_waypoints[num_conn];
	int *connections = current_waypoint->connections.arr;

	waypoint *wpts = bot_level->waypoints.arr;
	for (i = 0; i < num_conn; i++) {
		waypoint *w = &wpts[connections[i]];

		int is_free = way_free_of_droids(current_waypoint->x + 0.5, current_waypoint->y + 0.5,
				w->x + 0.5, w->y + 0.5, this_robot->pos.z, &frw_ctx);
		if (is_free) {
			if (connections[i] != this_robot->lastwaypoint) {
				free_waypoints[nb_free_waypoints++] = connections[i];
			} else {
				lastwaypoint_is_free = TRUE;
			}
		}
	}

	// If no paths are free, make the bot wait a bit (use a random waiting
	// time, to help avoid 'deadlocks' between bots).
	//
	if (nb_free_waypoints == 0 && !lastwaypoint_is_free) {
		this_robot->pure_wait = 0.5 + (float)MyRandom(4)/8.0;
		return TRUE;
	}

	// Randomly chose one of the free connected waypoints.
	// (see function's comment)
	//
	int next_waypoint_id;

	if (lastwaypoint_is_free) {
		int rnd = MyRandom(PMULT*nb_free_waypoints); // range: [0, PMULT*nb_free_waypoints + 1[
		if (rnd != 0) {
			next_waypoint_id = free_waypoints[(rnd-1)/PMULT];
		} else {
			next_waypoint_id = this_robot->lastwaypoint;
		}
	} else {
		// If the previous waypoint is not free, then there's no need for any
		// specific random law...
		int rnd = MyRandom(nb_free_waypoints - 1);
		next_waypoint_id = free_waypoints[rnd];
	}

	// Set the new path
	//
	this_robot->lastwaypoint = this_robot->nextwaypoint;
	this_robot->nextwaypoint = next_waypoint_id;

	return TRUE;
}

/**
 * If the droid in question is currently not following the waypoint system
 * but rather moving around on it's own and without any real destination,
 * this function sets up randomly chosen targets for the droid.
 */
static void set_new_waypointless_walk_target(enemy * ThisRobot, moderately_finepoint * mt)
{
	int i;
	moderately_finepoint target_candidate;
	int success = FALSE;

#define MAX_RANDOM_WALK_ATTEMPTS_BEFORE_GIVING_UP 4

	for (i = 0; i < MAX_RANDOM_WALK_ATTEMPTS_BEFORE_GIVING_UP; i++) {
		// We select a possible new walktarget for this bot, not too
		// far away from the current position...
		//
		target_candidate.x = ThisRobot->pos.x + (MyRandom(600) - 300) / 100;
		target_candidate.y = ThisRobot->pos.y + (MyRandom(600) - 300) / 100;


		if (DirectLineColldet(ThisRobot->pos.x, ThisRobot->pos.y,
					target_candidate.x, target_candidate.y, ThisRobot->pos.z, &WalkablePassFilter)) {
			mt->x = target_candidate.x;
			mt->y = target_candidate.y;
			success = TRUE;
		}
	}

	if (!success) {
		ThisRobot->pure_wait = WAIT_COLLISION;
	}
};				// void set_new_waypointless_walk_target ( enemy* ThisRobot )

/**
 * When a (hostile) robot is defeated and explodes, it will drop some 
 * treasure, i.e. stuff it had or parts that it consisted of or similar
 * things.  Maybe there will even be some extra magical treasures if the
 * robot in question was a 'boss monster'.  This function does the 
 * treasure dropping.
 */
829
static void enemy_drop_treasure(struct enemy *this_droid)
830
{
831 832 833
	int extract_skill_level = Me.skill_level[get_program_index_with_name("Extract bot parts")];
	if (extract_skill_level > 5)
		extract_skill_level = 5;
834 835 836 837

	// If the Tux has the skill to extract certain components from dead bots,
	// these components will be thrown out automatically, when the bot is killed.
	//
838
	switch (extract_skill_level) {
839
	case 5:
840 841 842 843 844
		if (Droidmap[this_droid->type].amount_of_tachyon_condensators
		    && Droidmap[this_droid->type].amount_of_tachyon_condensators > MyRandom(100))
			DropItemAt(get_item_type_by_id("Tachyon Condensator"), this_droid->pos.z, this_droid->pos.x,
			           this_droid->pos.y, 1);
		// no break
845
	case 4:
846 847 848 849 850
		if (Droidmap[this_droid->type].amount_of_antimatter_converters
		    && Droidmap[this_droid->type].amount_of_antimatter_converters > MyRandom(100))
			DropItemAt(get_item_type_by_id("Antimatter-Matter Converter"), this_droid->pos.z, this_droid->pos.x,
			           this_droid->pos.y, 1);
		// no break
851
	case 3:
852 853 854 855 856
		if (Droidmap[this_droid->type].amount_of_superconductors
		    && Droidmap[this_droid->type].amount_of_superconductors > MyRandom(100))
			DropItemAt(get_item_type_by_id("Superconducting Relay Unit"), this_droid->pos.z, this_droid->pos.x,
			           this_droid->pos.y, 1);
		// no break
857
	case 2:
858 859 860 861 862
		if (Droidmap[this_droid->type].amount_of_plasma_transistors
		    && Droidmap[this_droid->type].amount_of_plasma_transistors > MyRandom(100))
			DropItemAt(get_item_type_by_id("Plasma Transistor"), this_droid->pos.z, this_droid->pos.x,
			           this_droid->pos.y, 1);
		// no break
863
	case 1:
864 865 866 867 868
		if (Droidmap[this_droid->type].amount_of_entropy_inverters
		    && Droidmap[this_droid->type].amount_of_entropy_inverters > MyRandom(100))
			DropItemAt(get_item_type_by_id("Entropy Inverter"), this_droid->pos.z, this_droid->pos.x,
			           this_droid->pos.y, 1);
		// no break
869 870 871 872
	case 0:
		break;
	}

873
	if (this_droid->on_death_drop_item_code != (-1)) {
874 875
		// We make sure the item created is of a reasonable type
		//
876 877
		if ((this_droid->on_death_drop_item_code <= 0) || (this_droid->on_death_drop_item_code >= Number_Of_Item_Types)) {
			error_message(__FUNCTION__, "Bot at %f %f (level %d, dialog %s) is specified to drop an item that doesn't exist (item type %d).", PLEASE_INFORM, this_droid->pos.x, this_droid->pos.y, this_droid->pos.z, this_droid->dialog_section_name, this_droid->on_death_drop_item_code);
878 879 880
			return;
		}

881 882
		DropItemAt(this_droid->on_death_drop_item_code, this_droid->pos.z, this_droid->pos.x, this_droid->pos.y, 1);
		this_droid->on_death_drop_item_code = -1;
883 884 885 886 887
	}
	// Apart from the parts, that the Tux might be able to extract from the bot,
	// there is still some chance, that the enemy will have (and drop) some other
	// valuables, that the Tux can then collect afterwards.
	//
888
	DropRandomItem(this_droid->pos.z, this_droid->pos.x, this_droid->pos.y, Droidmap[this_droid->type].drop_class, FALSE);
889 890 891
}

/**
892
 * When an enemy is hit, this causes some blood to be sprayed on the floor.
893 894 895 896 897 898 899 900 901 902
 * The blood is just an obstacle (several types of blood exist) with 
 * preput flag set, so that the Tux and everyone can really step *on* the
 * blood.
 *
 * Blood will always be sprayed, but there is a toggle available for making
 * the blood visible/invisible for more a children-friendly version of the
 * game.
 *
 * This function does the blood spraying (adding of these obstacles).
 */
903
static void enemy_spray_blood(struct enemy *droid)
904
{
905 906 907 908 909 910 911 912 913
	// Fix virtual position (e.g. from a dying robot)
	struct gps droid_pos = { -1, -1, -1 };
	if (!resolve_virtual_position(&droid_pos, &droid->pos)) {
		return;
	}

	// Find a random position that is inside the droid's level
	// (that's not mandatory, but ease computation), and outside any obstacle
	struct gps blood_pos = { -1, -1, -1 };
914

915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
	struct level *rlvl = curShip.AllLevels[droid_pos.z];
	const int tries = 4;
	int i;
	for (i = 0; i < tries; i++) {
		moderately_finepoint tried_pos = { 0.5, 0 };
		RotateVectorByAngle(&tried_pos, MyRandom(360));
		tried_pos.x += droid_pos.x;
		tried_pos.y += droid_pos.y;
		if (pos_inside_level(tried_pos.x, tried_pos.y, rlvl)) {
			if (!SinglePointColldet(tried_pos.x, tried_pos.y, droid_pos.z, NULL))
				continue;
			blood_pos.x = tried_pos.x;
			blood_pos.y = tried_pos.y;
			blood_pos.z = droid_pos.z;
			break;
		}
	}
	if (i == tries) {
		// Was not able to find a random position inside the level, use bot's position
		blood_pos.x = droid_pos.x;
		blood_pos.y = droid_pos.y;
		blood_pos.z = droid_pos.z;
	}
938

939
	// Get a random blood print
940 941 942

	struct obstacle_group *blood_group = NULL;

943
	if (Droidmap[droid->type].is_human)
944 945 946 947 948
		blood_group = get_obstacle_group_by_name("blood");
	else
		blood_group = get_obstacle_group_by_name("oil stains");

	if (!blood_group) {
949
		error_message(__FUNCTION__, "Could not find obstacle group for blood.", PLEASE_INFORM);
950 951 952 953
		return;
	}

	int *random_blood_type = dynarray_member(&blood_group->members, MyRandom(blood_group->members.size - 1), sizeof(int));
954 955
	struct obstacle_spec *obs_spec = get_obstacle_spec(*random_blood_type);
	add_volatile_obstacle(curShip.AllLevels[blood_pos.z], blood_pos.x, blood_pos.y, *random_blood_type, obs_spec->vanish_delay + obs_spec->vanish_duration);
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
}

/**
 * When a robot has reached energy <= 1, then this robot will explode and
 * die, lose some treasure and add up to the kill record of the Tux.  All
 * the things that should happen when energy is that low are handled here
 * while the check for low energy is done outside of this function namely
 * somewhere in the movement processing for this enemy.
 */
static int kill_enemy(enemy * target, char givexp, int killertype)
{
	int reward = 0;

	/* Give death message */
	if (givexp) {
971
		reward = Droidmap[target->type].experience_reward * Me.experience_factor;
972 973 974 975 976 977 978
		Me.Experience += reward;
	}

	if (is_friendly(target->faction, FACTION_SELF)) {
		if (killertype > -1) {	    //killed by someone else, and we know who it is
			enemy *killer = NULL;
			killer = enemy_resolve_address(killertype, &killer);
979 980 981
			// TRANSLATORS: Your friend <bot's short description> was killed by <bot's short description>
			append_new_game_message(_("Your friend [s]%s[v] was killed by %s."),
			                        D_(target->short_description_text), D_(killer->short_description_text));
982
		} else if ((killertype == -1) && (givexp)) {      //You killed someone
983 984
			// TRANSLATORS: You killed <bot's short description>
			append_new_game_message(_("You killed [s]%s[v]."), D_(target->short_description_text));
985 986
			Me.destroyed_bots[target->type]++;
		} else if (killertype == -2) {  //bot killed itself
987 988
			// TRANSLATORS: <bot's short description> halted and caught fire
			append_new_game_message(_("[s]%s[v] halted and caught fire."), D_(target->short_description_text));
989
		} else {
990 991
			// TRANSLATORS: <bot's short description> is dead
			append_new_game_message(_("[s]%s[v] is dead."), D_(target->short_description_text));
992 993 994
		}
	} else {
		if (givexp && (killertype == -1)) {
995 996
			// TRANSLATORS: For defeating <bot's short description>, you receive <10> experience
			append_new_game_message(_("For defeating [s]%s[v], you receive %d experience."), D_(target->short_description_text),
997 998 999 1000
						reward);
			Me.destroyed_bots[target->type]++;		
		}

1001 1002 1003 1004
		//	The below section is much more of debug info that something that actually should be "spammed" to the user by default.
		//	Possibly Tux could know about fighting going on in the immediate vicinity, but for sure not on the other side of the world map.
		//	It just confuses beginners while giving little or no valuable info to even an experienced player.
		/*
1005
 		else if (killertype && killertype != -1)
1006 1007
			append_new_game_message(_("[s]%s[v] was killed by %s."), target->short_description_text,
						Droidmap[killertype].droidname);
1008
		else
1009 1010
			append_new_game_message(_("[s]%s[v] died."), target->short_description_text);
		 */
1011 1012
	}

1013 1014 1015 1016 1017 1018 1019 1020
	// NOTE:  We reset the animation phase to the first death animation image
	//        here.  But this may be WRONG!  In the case that the enemy graphics
	//        hasn't been loaded yet, this will result in '1' for the animation
	//        phase.  That however is unlikely to happen unless the bot is killed
	//        right now and hasn't been ever visible in the game yet.  Also it
	//        will lead only to minor 'prior animation' before the real death
	//        phase is reached and so serious bugs other than that, so I think it
	//        will be tolerable this way.
1021

1022 1023 1024
	target->animation_phase = ((float)first_death_animation_image[Droidmap[target->type].individual_shape_nr]) - 1 + 0.1;
	target->animation_type = DEATH_ANIMATION;
	play_death_sound_for_bot(target);
1025

1026
	enemy_drop_treasure(target);
1027

1028 1029
	if (MyRandom(15) == 1)
		enemy_spray_blood(target);
1030

1031 1032
	list_move(&(target->global_list), &dead_bots_head); // bot is dead. move it to dead list
	list_del(&(target->level_list));                    // bot is dead. remove it from level list
1033 1034 1035 1036

	event_enemy_died(target);

	return 0;
1037
}
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047

/**
 *
 *
 */
static void start_gethit_animation(enemy * ThisRobot)
{
	// Maybe this robot is fully animated.  In this case, after getting
	// hit, the gethit animation should be displayed, which we'll initiate here.
	//
1048 1049
	if ((last_gethit_animation_image[Droidmap[ThisRobot->type].individual_shape_nr] - first_gethit_animation_image[Droidmap[ThisRobot->type].individual_shape_nr] > 0)) {
		if (ThisRobot->animation_type == DEATH_ANIMATION) {
1050 1051
			DebugPrintf(-4, "\n%s(): WARNING: animation phase reset for INFOUT bot... ", __FUNCTION__);
		}
1052
		ThisRobot->animation_phase = ((float)first_gethit_animation_image[Droidmap[ThisRobot->type].individual_shape_nr]) + 0.1;
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
		ThisRobot->animation_type = GETHIT_ANIMATION;
	}

};				// void start_gethit_animation_if_applicable ( enemy* ThisRobot ) 

/*
 *  Hit an enemy for "hit" HP. This is supposed to be the *only* means 
 *  of removing HPs to a bot.
 *
 *  target is a pointer to the bot to hit
 *  hit is the amount of HPs to remove
 *  givexp (0 or 1) indicates whether to give an XP reward to the player or not
 *  killertype is the id of the bot who is responsible of the attack, or -1 if it is unknown
 *  or if it is the player, -2 for a non-human dialog-killed droid.  
 *  mine is 0 or 1 depending on whether it's the player who is responsible for the attack
 */
void hit_enemy(enemy * target, float hit, char givexp, short int killertype, char mine)
{
	/*
	 * turn group hostile
	 * spray blood
	 * enter hitstun
	 * say a funny message
	 * remove hp
	 * check if droid is dead
	 */

1080 1081 1082 1083 1084
	if (target->energy <= 0) {
		// Do not kill already dead enemies
		return;
	}

1085 1086 1087 1088 1089 1090
	// no XP is given for killing a friendly bot
	if (is_friendly(target->faction, FACTION_SELF) && givexp)
		givexp = 0;

	// hitstun
	// a hit that does less than 5% (over max life) damage cannot stun a bot
1091
	if (hit / Droidmap[target->type].maxenergy >= 0.05) {
1092 1093 1094
		start_gethit_animation(target);

		// if the current wait time of the bot is greater than the hitstun duration, we do nothing
1095 1096
		if (target->firewait < Droidmap[target->type].recover_time_after_getting_hit) {
			target->firewait = Droidmap[target->type].recover_time_after_getting_hit;
1097 1098 1099 1100 1101 1102
		}
	}

	target->energy -= hit;
	if (target->energy <= 0) {
		kill_enemy(target, givexp, killertype);
1103 1104
	} else if (hit > 1 && MyRandom(6) == 1) {
		enemy_spray_blood(target);
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
	}
	if (mine)
		Me.damage_dealt[target->type] += hit;
}

/**
 * This function moves a single enemy.  It is used by update_enemy().
 */
static void MoveThisEnemy(enemy * ThisRobot)
{
	// robots that still have to wait also do not need to
	// be processed for movement
	//
	if (ThisRobot->pure_wait > 0)
		return;

	gps oldpos = { ThisRobot->pos.x, ThisRobot->pos.y, ThisRobot->pos.z };

	MoveThisRobotTowardsHisCurrentTarget(ThisRobot);

	if (CheckEnemyEnemyCollision(ThisRobot)) {
		ThisRobot->pos.x = oldpos.x;
		ThisRobot->pos.y = oldpos.y;
		ThisRobot->pos.z = oldpos.z;
	}
};

/**
 * This function returns a gps (position) for a robot's current target, 
 * or NULL if such target doesn't exist or is dead or is invisible (if target is Tux)
 */
static gps *enemy_get_target_position(enemy * ThisRobot)
{
1138 1139 1140 1141 1142
	if (ThisRobot->attack_target_type == ATTACK_TARGET_IS_PLAYER) {

		if (can_see_tux(ThisRobot))
			return &Me.pos;
		else
1143
			return NULL;
1144

1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
	} else if (ThisRobot->attack_target_type == ATTACK_TARGET_IS_ENEMY) {
		enemy *bot_enemy = enemy_resolve_address(ThisRobot->bot_target_n, &ThisRobot->bot_target_addr);
		if (!bot_enemy || bot_enemy->energy <= 0)
			return NULL;
		return &bot_enemy->pos;
	}

	/* No (more) target */
	return NULL;
}

/**
 * More for debugging purposes, we print out the current state of the
 * robot as his in-game text.
 */
void enemy_say_current_state_on_screen(enemy * ThisRobot)
{
	if (ThisRobot->pure_wait <= 0) {
		switch (ThisRobot->combat_state) {
		case MOVE_ALONG_RANDOM_WAYPOINTS:
			ThisRobot->TextToBeDisplayed = ("state:  Wandering along waypoints.");
			break;
		case SELECT_NEW_WAYPOINT:
			ThisRobot->TextToBeDisplayed = ("state: Select next WP.");
			break;
		case TURN_TOWARDS_NEXT_WAYPOINT:
			ThisRobot->TextToBeDisplayed = ("state:  Turn towards next WP.");
			break;
		case RUSH_TUX_AND_OPEN_TALK:
			ThisRobot->TextToBeDisplayed = ("state:  Rush Tux and open talk.");
			break;
		case STOP_AND_EYE_TARGET:
			ThisRobot->TextToBeDisplayed = ("state:  Stop and eye target.");
			break;
		case ATTACK:
			ThisRobot->TextToBeDisplayed = ("state:  Attack.");
			break;
		case RETURNING_HOME:
			ThisRobot->TextToBeDisplayed = ("state:  Returning home.");
			break;
		case WAYPOINTLESS_WANDERING:
			ThisRobot->TextToBeDisplayed = ("state:  Waypointless wandering.");
			break;
		case PARALYZED:
			ThisRobot->TextToBeDisplayed = ("state:  Paralyzed.");
			break;
		case COMPLETELY_FIXED:
			ThisRobot->TextToBeDisplayed = ("state: Completely fixed.");
			break;
		case FOLLOW_TUX:
			ThisRobot->TextToBeDisplayed = ("state: Follow Tux.");
			break;
		case UNDEFINED_STATE:
			ThisRobot->TextToBeDisplayed = ("state: None.");
			break;
		default:
			ThisRobot->TextToBeDisplayed = ("state:  UNHANDLED!!");
			break;
		}
	} else {
		switch (ThisRobot->combat_state) {
			case MOVE_ALONG_RANDOM_WAYPOINTS:
				ThisRobot->TextToBeDisplayed = ("purewait (MARW)");
				break;
			case SELECT_NEW_WAYPOINT:
				ThisRobot->TextToBeDisplayed = ("purewait (SNW)");
				break;
			case TURN_TOWARDS_NEXT_WAYPOINT:
				ThisRobot->TextToBeDisplayed = ("purewait (TTNW)");
				break;
			case RUSH_TUX_AND_OPEN_TALK:
				ThisRobot->TextToBeDisplayed = ("purewait (RTAOT)");
				break;
			case STOP_AND_EYE_TARGET:
				ThisRobot->TextToBeDisplayed = ("purewait (SAET)");
				break;
			case ATTACK:
				ThisRobot->TextToBeDisplayed = ("purewait (A)");
				break;
			case RETURNING_HOME:
				ThisRobot->TextToBeDisplayed = ("purewait (RH)");
				break;
			case WAYPOINTLESS_WANDERING:
				ThisRobot->TextToBeDisplayed = ("purewait (WW)");
				break;
			case PARALYZED:
				ThisRobot->TextToBeDisplayed = ("purewait (P)");
				break;
			case COMPLETELY_FIXED:
				ThisRobot->TextToBeDisplayed = ("purewait (CF)");
				break;
			case FOLLOW_TUX:
				ThisRobot->TextToBeDisplayed = ("purewait (FT)");
				break;
			case UNDEFINED_STATE:
				ThisRobot->TextToBeDisplayed = ("purewait (US)");
				break;
			default:
				ThisRobot->TextToBeDisplayed = ("purewait (UNH)");
				break;
		}
	}

	ThisRobot->TextVisibleTime = 0;

};				// void enemy_say_current_state_on_screen ( enemy* ThisRobot )

/**
 * Some robots (currently) tend to get stuck in walls.  This is an 
 * annoying bug case we have not yet been able to eliminate completely.
 * To provide some safety against this case, some extra fallback handling
 * should be introduced, so that the bots can still recover if that 
 * unlucky case really happens, which is what we provide here.
 *
 * Since passability checks usually can become quite costly in terms of 
 * processor time and also because it makes sense to allow for some more
 * 'natural' fallbacks to work, we only check for stuck bots every second
 * or so.  In order to better distribute the checks (and not cause fps
 * glitches by doing them all at once) we use individual timers for this
 * test.
 */
void enemy_handle_stuck_in_walls(enemy * ThisRobot)
{
	waypoint *wpts = curShip.AllLevels[ThisRobot->pos.z]->waypoints.arr;

	// Maybe the time for the next check for this bot has not yet come.
	// in that case we can return right away.
	//
	ThisRobot->time_since_previous_stuck_in_wall_check += Frame_Time();
	if (ThisRobot->time_since_previous_stuck_in_wall_check < 1.0)
		return;
	ThisRobot->time_since_previous_stuck_in_wall_check = 0;

	// First we take a look if this bot is currently stuck in a
	// wall somewhere.
	//
	if (!SinglePointColldet(ThisRobot->pos.x, ThisRobot->pos.y, ThisRobot->pos.z, &WalkablePassFilter)) {
		// So at this point we know, that we have a bot that is stuck right now,
		// has been stuck one second ago and also is not moving along waypoints, which
		// would lead to the bot reaching some sensible spot sooner or later anyway.
		// In one word:  we have arrived in a situation that might make a crude correction
		// sensible.  We teleport the robot back to the nearest waypoint.  From there, it
		// might find a suitable way on it's own again.
		//      
		DebugPrintf(-2, "\n\nFound robot that seems really stuck on position: %f/%f/%d.",
			    ThisRobot->pos.x, ThisRobot->pos.y, ThisRobot->pos.z);
		DebugPrintf(-2, "\nMore details on this robot:  Type=%d.", ThisRobot->type);
		DebugPrintf(-2, "\nShort Description=%s.", ThisRobot->short_description_text);
		DebugPrintf(-2, "\nPrivate Pathway[0]: %f/%f.", ThisRobot->PrivatePathway[0].x, ThisRobot->PrivatePathway[0].y);
		DebugPrintf(-2, "\nPrivate Pathway[1]: %f/%f.", ThisRobot->PrivatePathway[1].x, ThisRobot->PrivatePathway[1].y);
		DebugPrintf(-2, "\nnextwaypoint: %d at %f/%f",
			    ThisRobot->nextwaypoint, wpts[ThisRobot->nextwaypoint].x + 0.5, wpts[ThisRobot->nextwaypoint].y + 0.5);

		enemy_say_current_state_on_screen(ThisRobot);
		DebugPrintf(-2, "\nnextwaypoint=%d. lastwaypoint=%d. combat_%s.",
			    ThisRobot->nextwaypoint, ThisRobot->lastwaypoint, (ThisRobot->TextToBeDisplayed) ? ThisRobot->TextToBeDisplayed : "NONE");

		if (!EscapeFromObstacle(&(ThisRobot->pos.x), &(ThisRobot->pos.y), ThisRobot->pos.z, &WalkablePassFilter)) {
			// No free position was found outside the obstacle ???
			// It should not happen but since we want the bot to escape in any situation, just have a last fallback
			//
			ThisRobot->pos.x = wpts[ThisRobot->nextwaypoint].x + 0.5;
			ThisRobot->pos.y = wpts[ThisRobot->nextwaypoint].y + 0.5;
		}
		ThisRobot->combat_state = SELECT_NEW_WAYPOINT;
		ThisRobot->bot_stuck_in_wall_at_previous_check = TRUE;
		return;
	} else {
		// this bot isn't currently stuck.  what more could anybody want?
		ThisRobot->bot_stuck_in_wall_at_previous_check = FALSE;
	}
};				// enemy_handle_stuck_in_walls ( enemy* ThisRobot )

/**
 * This function selects a target for a friendly bot. 
 * It takes closest reachable enemy bot in view range.
 * A new target is selected at each frame. This should prevent a friendly bot to follow
 * an enemy and thus get too far away from its "steady" position.
 *
 * Note : this function does set ThisRobbot->attack_target_type, and calls enemy_set_reference()
 *        accordingly to its finding.
 */
void update_vector_to_shot_target_for_friend(enemy * ThisRobot)
{
1329
	float aggression_distance = Droidmap[ThisRobot->type].aggression_distance;
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
	float squared_aggression_distance = aggression_distance * aggression_distance;
	float squared_best_dist;

	/*
	   if ( ThisRobot->pure_wait > 0 )
	   {    // Target was not reachable
	   // We could, for example, try to find an other target
	   // But we should not do that as soon as the bot is pure_waiting,
	   // because it could be a very temporary state.
	   // So, a "pure_waiting" counter would be needed...
	   }
	 */

	// We set some default values, in case there isn't anything attackable
	// found below...
	ThisRobot->attack_target_type = ATTACK_TARGET_IS_NOTHING;
	enemy_set_reference(&ThisRobot->bot_target_n, &ThisRobot->bot_target_addr, NULL);

	// This initialization ensures that only targets inside aggression_distance are checked.
	squared_best_dist = squared_aggression_distance;

	enemy *erot;
	BROWSE_LEVEL_BOTS(erot, ThisRobot->pos.z) {
		if (is_friendly(ThisRobot->faction, erot->faction))
			continue;

		if (is_potential_target(ThisRobot, &erot->pos, &squared_best_dist)) {
			ThisRobot->attack_target_type = ATTACK_TARGET_IS_ENEMY;
			enemy_set_reference(&ThisRobot->bot_target_n, &ThisRobot->bot_target_addr, erot);
		}
	}

}				// void update_vector_to_shot_target_for_friend ( ThisRobot )

/**
 * This function selects an attack target for an hostile bot.
 * Selected target is the previous target if it is still valid (see paragraph below),
 * or the closest potential target.
 *
 * For gameplay value purposes, it also performs a little hack : the target of 
 * the previous frame can be selected even if it is "slightly" out of view (2 times the range),
 * in order to simulate "pursuit". Sorry for the mess but there is no other proper place for that.
 *
 * Note : this function does set this_robot->attack_target_type, and calls enemy_set_reference()
 *        accordingly to its finding.
 */
void update_vector_to_shot_target_for_enemy(enemy * this_robot)
{
	int our_level = this_robot->pos.z;
	float squared_best_dist;
	float xdist, ydist;
1381
	float aggression_distance = Droidmap[this_robot->type].aggression_distance;
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
	float squared_aggression_distance = aggression_distance * aggression_distance;

	// Check validity of old target (if any)
	//
	// Logic : 
	// A target is valid if :
	// 1- always available (not dead and not invisible)
	// 2- was reachable (this_robot was not blocked along its way to the target)
	// 3- is not too far
	// 
	gps *tpos = enemy_get_target_position(this_robot);

	if (!tpos) {		// Old target is no more available
		this_robot->attack_target_type = ATTACK_TARGET_IS_NOTHING;
		enemy_set_reference(&this_robot->bot_target_n, &this_robot->bot_target_addr, NULL);
	}
	/*
	   else if ( this_robot->pure_wait > 0 )
	   {    // Target was not reachable
	   // We could, for example, try to find an other target
	   // But we should not do that as soon as the bot is pure_waiting,
	   // because it could be a very temporary state.
	   // So, a "pure_waiting" counter would be needed...
	   }
	 */
	else if (this_robot->attack_target_type != ATTACK_TARGET_IS_NOTHING) {
		// Check virtual distance
		update_virtual_position(&this_robot->virt_pos, &this_robot->pos, tpos->z);
		if (this_robot->virt_pos.z == -1) {	// Target is at more than one level away
			this_robot->attack_target_type = ATTACK_TARGET_IS_NOTHING;
			enemy_set_reference(&this_robot->bot_target_n, &this_robot->bot_target_addr, NULL);
		} else {
			xdist = tpos->x - this_robot->virt_pos.x;
			ydist = tpos->y - this_robot->virt_pos.y;

			if ((xdist * xdist + ydist * ydist) > 3.0*3.0) {	
				/// Previous target is too far away to follow without checking if
				// there are enemies located closer
				this_robot->attack_target_type = ATTACK_TARGET_IS_NOTHING;
				enemy_set_reference(&this_robot->bot_target_n, &this_robot->bot_target_addr, NULL);
			} else {
				// All tests passed : Continue with same target
				return;
			}
		}
	}
	// Search for a new target
	//

	// This initialization ensures that only targets inside aggression_distance are checked.
	squared_best_dist = squared_aggression_distance;

	// First check if Tux is a potential target
1435
	if (can_see_tux(this_robot)) {
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
		if (is_potential_target(this_robot, &Me.pos, &squared_best_dist)) {
			this_robot->attack_target_type = ATTACK_TARGET_IS_PLAYER;
		}
	}
	// But maybe there is a friend of the Tux also close.  Then maybe we
	// should attack this one instead, since it's much closer anyway.
	enemy *erot;
	BROWSE_LEVEL_BOTS(erot, our_level) {
		if (is_friendly(erot->faction, this_robot->faction))
			continue;

		if (is_potential_target(this_robot, &erot->pos, &squared_best_dist)) {
			this_robot->attack_target_type = ATTACK_TARGET_IS_ENEMY;
			enemy_set_reference(&this_robot->bot_target_n, &this_robot->bot_target_addr, erot);
		}
	}

}				// void update_vector_to_shot_target_for_enemy ( ThisRobot )

/**
 * This function handles the inconditional updates done to the bots by
 * the automaton powering them. See update_enemy().
 */
static void state_machine_inconditional_updates(enemy * ThisRobot)
{
	// Robots that are paralyzed are completely stuck and do not 
	// see their state machine running

	// For debugging purposes we display the current state of the robot
	// in game
	enemy_say_current_state_on_screen(ThisRobot);

	// we check whether the current robot is 
	// stuck inside a wall or something...
	//
	enemy_handle_stuck_in_walls(ThisRobot);

	// determine the distance vector to the target of this shot.  The target
	// depends of course on whether it's a friendly device or a hostile device.
	//
	if (is_friendly(ThisRobot->faction, FACTION_SELF)) {
		update_vector_to_shot_target_for_friend(ThisRobot);
	} else {
		update_vector_to_shot_target_for_enemy(ThisRobot);
	}

	ThisRobot->speed.x = 0;
	ThisRobot->speed.y = 0;

}

/**
 * This function handles state transitions based solely (or almost) on 
 * the external situation and not on the current state of the bot. 
 * The purpose is to reduce code duplication in the "big switch" that follows.
 */
static void state_machine_situational_transitions(enemy * ThisRobot)
{
	waypoint *wpts = curShip.AllLevels[ThisRobot->pos.z]->waypoints.arr;

	/* The various situations are listed in increasing priority order (ie. they may override each other, so the least priority comes first. */
	/* In an ideal world, this would not exist and be done for each state. But we're in reality and have to limit code duplication. */

	// Rush Tux when he's close & visible
	update_virtual_position(&ThisRobot->virt_pos, &ThisRobot->pos, Me.pos.z);
1501
	if (ThisRobot->will_rush_tux && ThisRobot->virt_pos.z != -1 && can_see_tux(ThisRobot)
1502 1503 1504 1505
	    && (powf(Me.pos.x - ThisRobot->virt_pos.x, 2) + powf(Me.pos.y - ThisRobot->virt_pos.y, 2)) < 16) {
		ThisRobot->combat_state = RUSH_TUX_AND_OPEN_TALK;
	}

1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
	// Transition away from Rush Tux gracefully if it is unset or if the bot became aggressive
	if (ThisRobot->combat_state == RUSH_TUX_AND_OPEN_TALK) {
		if (!ThisRobot->will_rush_tux)
			ThisRobot->combat_state = UNDEFINED_STATE;
			
		if (!is_friendly(ThisRobot->faction, FACTION_SELF)) {
			ThisRobot->combat_state = UNDEFINED_STATE;
			ThisRobot->will_rush_tux = 0;
		}
	}
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591

	/* Return home if we're too far away */
	if (ThisRobot->max_distance_to_home != 0 &&
	    sqrt(powf((wpts[ThisRobot->homewaypoint].x + 0.5) - ThisRobot->pos.x, 2) +
		 powf((wpts[ThisRobot->homewaypoint].y + 0.5) - ThisRobot->pos.y, 2))
	    > ThisRobot->max_distance_to_home) {
		ThisRobot->combat_state = RETURNING_HOME;
		ThisRobot->attack_target_type = ATTACK_TARGET_IS_NOTHING;
		enemy_set_reference(&ThisRobot->bot_target_n, &ThisRobot->bot_target_addr, NULL);
	}

	/* Paralyze if appropriate */
	if (ThisRobot->paralysation_duration_left > 0) {
		ThisRobot->combat_state = PARALYZED;
	}

	/* Now we will handle changes, which take place for many - but not exactly all - states */
	/* Those are all related to attack behavior */

	switch (ThisRobot->combat_state) {	/* Get out for all states we don't want to handle attack for */
	case STOP_AND_EYE_TARGET:
	case ATTACK:
	case PARALYZED:
	case RETURNING_HOME:
	case SELECT_NEW_WAYPOINT:
	case RUSH_TUX_AND_OPEN_TALK:
		return;
	}

	/* Fix completely if appropriate */
	if (ThisRobot->CompletelyFixed) {
		ThisRobot->combat_state = COMPLETELY_FIXED;
	}

	/* Follow Tux if appropriate */
	if (ThisRobot->follow_tux) {
		ThisRobot->combat_state = FOLLOW_TUX;
	}

	/* Switch to stop_and_eye_target if appropriate - it's the prelude to any-on-any attacks */
	if (ThisRobot->attack_target_type != ATTACK_TARGET_IS_NOTHING) {
		ThisRobot->combat_state = STOP_AND_EYE_TARGET;
	}

	/* If combat_state is UNDEFINED_STATE, go to SELECT_NEW_WAYPOINT state */
	if (ThisRobot->combat_state == UNDEFINED_STATE) {
		ThisRobot->combat_state = SELECT_NEW_WAYPOINT;
	}
}

/* ----------------------------------------------------------
 * "stop and eye tux" state handling 
 * ---------------------------------------------------------- */
static void state_machine_stop_and_eye_target(enemy * ThisRobot, moderately_finepoint * new_move_target)
{
	gps *tpos = enemy_get_target_position(ThisRobot);

	// Target no more available -> going to default state
	if (!tpos) {
		ThisRobot->state_timeout = 0;
		ThisRobot->combat_state = UNDEFINED_STATE;
		ThisRobot->attack_target_type = ATTACK_TARGET_IS_NOTHING;
		enemy_set_reference(&ThisRobot->bot_target_n, &ThisRobot->bot_target_addr, NULL);
		return;
	}

	update_virtual_position(&ThisRobot->virt_pos, &ThisRobot->pos, tpos->z);

	/* Make sure we're looking at the target */
	gps target_vpos;
	update_virtual_position(&target_vpos, tpos, ThisRobot->pos.z);
	TurnABitTowardsPosition(ThisRobot, target_vpos.x, target_vpos.y, 120);

	/* Do greet sound if not already done */
	if (!ThisRobot->has_greeted_influencer) {
		ThisRobot->has_greeted_influencer = TRUE;
1592
		if (Droidmap[ThisRobot->type].greeting_sound_type != (-1)) {
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
			play_greeting_sound(ThisRobot);
		}
	}

	/* Check state timeout */

	//XXX if the target is out of sight, we should resume normal operation. not the case currently

	// After some time, we'll no longer eye the Tux but rather do something,
	// like attack the Tux or maybe also return to 'normal' operation and do
	// nothing.  When Tux is still visible at timeout, then it will be attacked... otherwise
	// the robot resumes normal operation...
	//
	ThisRobot->state_timeout += Frame_Time();
1607
	if (ThisRobot->state_timeout > Droidmap[ThisRobot->type].time_spent_eyeing_tux) {
1608 1609 1610 1611
		ThisRobot->state_timeout = 0;
		SetRestOfGroupToState(ThisRobot, ATTACK);
		ThisRobot->combat_state = ATTACK;
		ThisRobot->last_combat_step = ATTACK_MOVE_RATE + 1.0;	// So that attack will start immediately
1612
		if (Droidmap[ThisRobot->type].greeting_sound_type != (-1)) {
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
			play_enter_attack_run_state_sound(ThisRobot);
		}
	}
}

/* ---------------------------------
 * "attack tux" state
 * 
 * This function will compute the destination position of a bot in order
 * to reach its target. In the caller (update_enemy), the pathfinder is 
 * called, to define the path of the bot up to its target.
 * 
 * This function will also eventually start a shoot.
 * 
 * --------------------------------- */

/*
 * Note concerning the modification of pathfinder_context :
 * 
 * When we ask the pathfinder to find a path between two points, the pathfinder 
 * will, by default, check if no bots are blocking the path.
 * Let consider the following case : an attacking bot (B1) with a melee weapon 
 * is at the entrance of a corridor. Its target (T) is inside the corridor, and an 
 * other bot (B2) is also inside the corridor :
 *       ---------------------
 *   B1                 B2 T
 *       ---------------------
 * In this case, the pathfinder will not be able to find a way between B1 and T.
 * B1 will thus not move.
 * 
 * However, if B1 were able to go just behind B2, it could be near enough to its
 * target to shoot it :
 *       ---------------------
 *                   B1 B2 T
 *       ---------------------
 * Such behavior will make B1 be as aggressive as possible.
 * We will only use it with friendly bots, so that the game is not too hard.
 * 
 * To implement this behavior, we have to tell the pathfinder not to check
 * collisions with bots. This is implemented in ReachMeleeCombat(). 
 */
static void state_machine_attack(enemy * ThisRobot, moderately_finepoint * new_move_target, pathfinder_context * pf_ctx)
{
	// Not yet time to computer a new bot's move, or to start a new shoot
1657
	if (ThisRobot->firewait > 0.0 && ThisRobot->last_combat_step < ATTACK_MOVE_RATE)
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
		return;

	// Get old target's position
	gps *tpos = enemy_get_target_position(ThisRobot);

	// Target no more available -> going to default state
	if (!tpos) {
		ThisRobot->combat_state = UNDEFINED_STATE;
		ThisRobot->attack_target_type = ATTACK_TARGET_IS_NOTHING;
		enemy_set_reference(&ThisRobot->bot_target_n, &ThisRobot->bot_target_addr, NULL);
		return;
	}
	// In case the target is on another level, evaluate the virtual position of the bot
	// in the target's level
	update_virtual_position(&ThisRobot->virt_pos, &ThisRobot->pos, tpos->z);

	// First compute the type of the bot's move, and if the target can be shot,
	// depending on the weapon's type and the distance to the target
	//
	gps move_pos = { tpos->x, tpos->y, tpos->z };

	enum {
		NO_MOVE,
		REACH_MELEE,
		MOVE_MELEE,
		MOVE_AWAY
	} move_type = NO_MOVE;

	int shoot_target = FALSE;
1687
	int melee_weapon = ItemMap[Droidmap[ThisRobot->type].weapon_item.type].weapon_is_melee;
1688 1689

	if (melee_weapon) {
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
		// The bot and its target are on different levels.
		if (ThisRobot->pos.z != move_pos.z) {
			// Before to start the attack, the bot has to reach its target's level.
			// Hence, compute virtual position to reach, and wait until the bot is at
			// the right level.
			update_virtual_position(&move_pos, tpos, ThisRobot->pos.z);
			move_type = REACH_MELEE;
			shoot_target = FALSE;
			goto EXECUTE_ATTACK;
		}

1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
		// Check visibility
		int target_visible =
		    DirectLineColldet(ThisRobot->virt_pos.x, ThisRobot->virt_pos.y, move_pos.x, move_pos.y, move_pos.z,
				      &WalkablePassFilter);

		if (!target_visible) {
			move_type = REACH_MELEE;
			shoot_target = FALSE;
			goto EXECUTE_ATTACK;
		}
		// Check distance               
		float dist2 =
		    (ThisRobot->virt_pos.x - move_pos.x) * (ThisRobot->virt_pos.x - move_pos.x) + (ThisRobot->virt_pos.y -
												   move_pos.y) * (ThisRobot->virt_pos.y -
														  move_pos.y);

		if (dist2 > SQUARED_MELEE_APPROACH_DIST) {
			move_type = REACH_MELEE;
			shoot_target = FALSE;
			goto EXECUTE_ATTACK;
		}

		if (dist2 > SQUARED_MELEE_MAX_DIST) {	// Approaching the target -> find a place near the bot
			move_type = MOVE_MELEE;
			shoot_target = FALSE;
			goto EXECUTE_ATTACK;
		}
		// All tests passed, the bot can shot.
		shoot_target = TRUE;
		goto EXECUTE_ATTACK;
	}

	else			// Range weapon

	{
		// Check visibility                     
		int target_visible =
		    DirectLineColldet(ThisRobot->virt_pos.x, ThisRobot->virt_pos.y, move_pos.x, move_pos.y, move_pos.z, &FlyablePassFilter);

		if (!target_visible) {
			move_type = REACH_MELEE;
			shoot_target = FALSE;
			goto EXECUTE_ATTACK;
		}
		// Check distance
		float dist2 =
		    (ThisRobot->virt_pos.x - move_pos.x) * (ThisRobot->virt_pos.x - move_pos.x) + (ThisRobot->virt_pos.y -
												   move_pos.y) * (ThisRobot->virt_pos.y -
														  move_pos.y);

		if (dist2 < SQUARED_RANGE_SHOOT_MIN_DIST) {	// Too close -> move away, and start shooting
			move_type = MOVE_AWAY;
			shoot_target = TRUE;
			goto EXECUTE_ATTACK;
		}
		// Check if outside of bullet range
1757 1758
		itemspec *bot_weapon = &ItemMap[Droidmap[ThisRobot->type].weapon_item.type];
		float shot_range = bot_weapon->weapon_bullet_lifetime * bot_weapon->weapon_bullet_speed;
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804
		float squared_shot_range = shot_range * shot_range;

		if (dist2 >= squared_shot_range) {
			move_type = REACH_MELEE;
			shoot_target = FALSE;
			goto EXECUTE_ATTACK;
		}
		// All tests passed, the bot can shoot.
		shoot_target = TRUE;
		goto EXECUTE_ATTACK;

	}

 EXECUTE_ATTACK:

	// Execute the bot's move
	//
	// We will often have to move towards our target.
	// But this moving around can lead to jittering of droids moving back and 
	// forth between two positions very rapidly.  Therefore we will not do this
	// movement thing every frame, but rather only sometimes
	//

	if (ThisRobot->last_combat_step >= ATTACK_MOVE_RATE) {
		ThisRobot->last_combat_step = 0;

		switch (move_type) {
		case REACH_MELEE:
			ReachMeleeCombat(ThisRobot, &move_pos, new_move_target, pf_ctx);
			break;
		case MOVE_MELEE:
			MoveToMeleeCombat(ThisRobot, &move_pos, new_move_target);
			break;
		case MOVE_AWAY:
			MoveAwayFromMeleeCombat(ThisRobot, new_move_target);
			break;
		default:
			break;
		}
	} else {
		ThisRobot->last_combat_step += Frame_Time();
	}

	// Execute the bot's shoot

	/* Great suggestion of Sarayan : we do not care about friendly fire, and make bullets go through people of the same side. */
1805
	if (shoot_target && ThisRobot->firewait <= 0)
1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
		RawStartEnemysShot(ThisRobot, move_pos.x - ThisRobot->virt_pos.x, move_pos.y - ThisRobot->virt_pos.y);

}

static void state_machine_paralyzed(enemy * ThisRobot, moderately_finepoint * new_move_target)
{
	/* Move target - none */
	new_move_target->x = ThisRobot->pos.x;
	new_move_target->y = ThisRobot->pos.y;

	if (ThisRobot->paralysation_duration_left <= 0)
		ThisRobot->combat_state = SELECT_NEW_WAYPOINT;
}

static void state_machine_returning_home(enemy * ThisRobot, moderately_finepoint * new_move_target)
{
	/* Bot too far away from home must go back to home waypoint */

	waypoint *wpts = curShip.AllLevels[ThisRobot->pos.z]->waypoints.arr;

	/* Move target */
	new_move_target->x = wpts[ThisRobot->homewaypoint].x + 0.5;
	new_move_target->y = wpts[ThisRobot->homewaypoint].y + 0.5;

	/* Action */
	if (remaining_distance_to_current_walk_target(ThisRobot) < ThisRobot->max_distance_to_home / 2.0) {
		ThisRobot->combat_state = SELECT_NEW_WAYPOINT;
		return;
	}

	ThisRobot->combat_state = RETURNING_HOME;
}

static void state_machine_select_new_waypoint(enemy * ThisRobot, moderately_finepoint * new_move_target)
{
	/* Move target - none */
	new_move_target->x = ThisRobot->pos.x;
	new_move_target->y = ThisRobot->pos.y;

	/* Bot must select a new waypoint randomly, and turn towards it. No move this step. */
	if (!set_new_random_waypoint(ThisRobot)) {	/* couldn't find a waypoint ? go waypointless  */
		ThisRobot->combat_state = WAYPOINTLESS_WANDERING;
	} else {
		ThisRobot->combat_state = TURN_TOWARDS_NEXT_WAYPOINT;
	}
}

static void state_machine_turn_towards_next_waypoint(enemy * ThisRobot, moderately_finepoint * new_move_target)
{
	waypoint *wpts = curShip.AllLevels[ThisRobot->pos.z]->waypoints.arr;

	/* Action */
	/* XXX */
	new_move_target->x = ThisRobot->pos.x;
	new_move_target->y = ThisRobot->pos.y;
	ThisRobot->last_phase_change = WAIT_BEFORE_ROTATE + 1.0;

	if (TurnABitTowardsPosition(ThisRobot, wpts[ThisRobot->nextwaypoint].x + 0.5, wpts[ThisRobot->nextwaypoint].y + 0.5, 90)) {
		new_move_target->x = wpts[ThisRobot->nextwaypoint].x + 0.5;
		new_move_target->y = wpts[ThisRobot->nextwaypoint].y + 0.5;
		ThisRobot->combat_state = MOVE_ALONG_RANDOM_WAYPOINTS;
	}
}

static void state_machine_move_along_random_waypoints(enemy * ThisRobot, moderately_finepoint * new_move_target)
{
	/* The bot moves towards its next waypoint */

	waypoint *wpts = curShip.AllLevels[ThisRobot->pos.z]->waypoints.arr;

	/* Move target */
	new_move_target->x = wpts[ThisRobot->nextwaypoint].x + 0.5;
	new_move_target->y = wpts[ThisRobot->nextwaypoint].y + 0.5;

	/* Action */
	if ((new_move_target->x - ThisRobot->pos.x) * (new_move_target->x - ThisRobot->pos.x) +
	    (new_move_target->y - ThisRobot->pos.y) * (new_move_target->y - ThisRobot->pos.y) < DIST_TO_INTERM_POINT*DIST_TO_INTERM_POINT) {
		ThisRobot->combat_state = SELECT_NEW_WAYPOINT;
		return;
	}

	ThisRobot->combat_state = MOVE_ALONG_RANDOM_WAYPOINTS;
}

static void state_machine_rush_tux_and_open_talk(enemy * ThisRobot, moderately_finepoint * new_move_target)
{
	/* Move target */
	if (ThisRobot->pos.z == Me.pos.z) {
		new_move_target->x = Me.pos.x;
		new_move_target->y = Me.pos.y;
	} else {
		new_move_target->x = ThisRobot->pos.x;
		new_move_target->y = ThisRobot->pos.y;
	}

	/* Action */
	if (sqrt((ThisRobot->virt_pos.x - Me.pos.x) * (ThisRobot->virt_pos.x - Me.pos.x) + (ThisRobot->virt_pos.y - Me.pos.y) * (ThisRobot->virt_pos.y - Me.pos.y)) < 1) {	//if we are close enough to tux, we talk
1903
		chat_with_droid(ThisRobot);
1904 1905 1906 1907 1908 1909 1910 1911
		ThisRobot->will_rush_tux = FALSE;
		ThisRobot->combat_state = SELECT_NEW_WAYPOINT;
		return;
	}
}

static void state_machine_follow_tux(enemy * ThisRobot, moderately_finepoint * new_move_target)
{
1912
	if (!ThisRobot->follow_tux || (!can_see_tux(ThisRobot)) ) {
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
		ThisRobot->combat_state = WAYPOINTLESS_WANDERING;
		new_move_target->x = ThisRobot->pos.x;
		new_move_target->y = ThisRobot->pos.y;
		return;
	}

	/* Move target - The friendly bot will follow Tux, but with a small delay */

	// Compute a FrameRate independent delay
	int delay = 0.5 * 1.0 / Frame_Time();	// Number of frame for a 0.5 seconds
	delay <<= 1;		// InfluPosition is only stored every two frames

	if (GetInfluPositionHistoryZ(delay) == ThisRobot->pos.z) {
		new_move_target->x = GetInfluPositionHistoryX(delay);
		new_move_target->y = GetInfluPositionHistoryY(delay);

		moderately_finepoint ab = { ThisRobot->pos.x - new_move_target->x, ThisRobot->pos.y - new_move_target->y };
		if (fabsf(ab.x) < 1 && fabsf(ab.y) < 1) {
			new_move_target->x = ThisRobot->pos.x;
			new_move_target->y = ThisRobot->pos.y;
		}
	} else {
		update_virtual_position(&ThisRobot->virt_pos, &ThisRobot->pos, Me.pos.z);
		if (ThisRobot->virt_pos.z != -1) {
			new_move_target->x = ThisRobot->pos.x + Me.pos.x - ThisRobot->virt_pos.x;
			new_move_target->y = ThisRobot->pos.y + Me.pos.y - ThisRobot->virt_pos.y;
		} else {
			ThisRobot->combat_state = WAYPOINTLESS_WANDERING;
			new_move_target->x = ThisRobot->pos.x;
			new_move_target->y = ThisRobot->pos.y;
		}
	}
}

static void state_machine_completely_fixed(enemy * ThisRobot, moderately_finepoint * new_move_target)
{
	/* Move target */
	new_move_target->x = ThisRobot->pos.x;
	new_move_target->y = ThisRobot->pos.y;

	if (!ThisRobot->CompletelyFixed)
		ThisRobot->combat_state = WAYPOINTLESS_WANDERING;
}

static void state_machine_waypointless_wandering(enemy * ThisRobot, moderately_finepoint * new_move_target)
{
	if (remaining_distance_to_current_walk_target(ThisRobot) < 0.1) {
		set_new_waypointless_walk_target(ThisRobot, new_move_target);
		TurnABitTowardsPosition(ThisRobot, new_move_target->x, new_move_target->y, 90);
		ThisRobot->combat_state = WAYPOINTLESS_WANDERING;
	}
}

/**
 * 
 * This function runs the finite state automaton that powers the bots.
 * It handles attack and movement behaviors.
 *
 */
void update_enemy(enemy * ThisRobot)
{
	/* New structure :
	 *
	 * Inconditional updates:
	 *    debug stuff (say state on screen)
	 *    unstick from walls if relevant
	 *    certain switches (cleanup to be made here)
	 *    find an attack target (we consider it state independent)
	 *    reset speed to 0 (for now)
	 *
	 * Situational state changes (transitions from any state to a given one in certain input conditions)
	 *    switch to RUSH TUX
	 *    switch to RETURN HOME
	 *
	 * Per-state actions
	 *    for each state:
	 *       compute a new moving target (no path finding there, just tell where to go)
	 *       do actions if appropriate (attack, talk, whatever)
	 *       transition to a state
	 *
	 * Universal actions ("could" be merged with inconditional updates)
	 *    pathfind the new moving target if applicable (it differs from the current moving target)
	 *    move (special case target = cur. position)
	 *
	 */

	/* Inconditional updates */
	state_machine_inconditional_updates(ThisRobot);

	/* Situational state changes */
	state_machine_situational_transitions(ThisRobot);

	moderately_finepoint new_move_target;
	enemy_get_current_walk_target(ThisRobot, &new_move_target);

	/* Handle per-state switches and actions.
	 * Each state much set move_target and combat_state.
	 */

	// Default pathfinder execution context
	// Can eventually be changed by a state_machine_xxxx function
	freeway_context frw_ctx = { FALSE, {ThisRobot, NULL} };
	pathfinder_context pf_ctx = { &WalkableWithMarginPassFilter, &frw_ctx };

	switch (ThisRobot->combat_state) {
	case STOP_AND_EYE_TARGET:
		state_machine_stop_and_eye_target(ThisRobot, &new_move_target);
		break;

	case ATTACK:
		state_machine_attack(ThisRobot, &new_move_target, &pf_ctx);
		break;

	case PARALYZED:
		state_machine_paralyzed(ThisRobot, &new_move_target);
		break;

	case COMPLETELY_FIXED:
		state_machine_completely_fixed(ThisRobot, &new_move_target);
		break;

	case FOLLOW_TUX:
		state_machine_follow_tux(ThisRobot, &new_move_target);
		break;

	case RETURNING_HOME:
		state_machine_returning_home(ThisRobot, &new_move_target);
		break;

	case SELECT_NEW_WAYPOINT:
		state_machine_select_new_waypoint(ThisRobot, &new_move_target);
		break;

	case TURN_TOWARDS_NEXT_WAYPOINT:
		state_machine_turn_towards_next_waypoint(ThisRobot, &new_move_target);
		break;

	case MOVE_ALONG_RANDOM_WAYPOINTS:
		state_machine_move_along_random_waypoints(ThisRobot, &new_move_target);
		break;

	case RUSH_TUX_AND_OPEN_TALK:
		state_machine_rush_tux_and_open_talk(ThisRobot, &new_move_target);
		break;

	case WAYPOINTLESS_WANDERING:
		state_machine_waypointless_wandering(ThisRobot, &new_move_target);
		break;

	}

	/* Pathfind current target */
	/* I am sorry this is a bit dirty, but I've got time and efficiency constraints. If you're not happy please send a patch. No complaints will 
	 * be accepted.*/

	/* The basic design is the following :
	 * we get the current moving target of the bot (ie. old)
	 * we compare the new and current moving target
	 *    if they differ : we have to set up a new route (pathfind the route)
	 *    if they do not : we move towards our first waypoint
	 *
	 * special case: 
	 *                if first waypoint is -1 -1 we have a bug and do nothing (hack around)
	 */
	moderately_finepoint wps[40];
	moderately_finepoint old_move_target;
	enemy_get_current_walk_target(ThisRobot, &old_move_target);

	if ((new_move_target.x == ThisRobot->pos.x) && (new_move_target.y == ThisRobot->pos.y)) {	// If the bot stopped moving, create a void path
		ThisRobot->PrivatePathway[0].x = ThisRobot->pos.x;
		ThisRobot->PrivatePathway[0].y = ThisRobot->pos.y;
		ThisRobot->PrivatePathway[1].x = -1;
		ThisRobot->PrivatePathway[1].y = -1;
	} else if (((new_move_target.x != old_move_target.x) || (new_move_target.y != old_move_target.y))) {	// If the current move target differs from the old one
		// This implies we do not re-pathfind every frame, which means we may bump into colleagues. 
		// This is handled in MoveThisEnemy()
		if (set_up_intermediate_course_between_positions(&ThisRobot->pos, &new_move_target, &wps[0], 40, &pf_ctx) && wps[5].x == -1) {	/* If position was passable *and* streamline course uses max 4 waypoints */
			memcpy(&ThisRobot->PrivatePathway[0], &wps[0], 5 * sizeof(moderately_finepoint));
		} else {
			ThisRobot->PrivatePathway[0].x = ThisRobot->pos.x;
			ThisRobot->PrivatePathway[0].y = ThisRobot->pos.y;
			ThisRobot->PrivatePathway[1].x = -1;
			ThisRobot->PrivatePathway[1].y = -1;
			if (ThisRobot->pure_wait < WAIT_COLLISION)
				ThisRobot->pure_wait = WAIT_COLLISION;
		}
	}

	if (ThisRobot->PrivatePathway[0].x == -1) {
		/* This happens at the very beginning of the game. If it happens afterwards this is a ugly bug. */
		ThisRobot->PrivatePathway[0].x = ThisRobot->pos.x;
		ThisRobot->PrivatePathway[0].y = ThisRobot->pos.y;
	}

	MoveThisEnemy(ThisRobot);
};				// void update_enemy()

/**
 * This function handles all the logic tied to enemies : animation, movement
 * and attack behavior.
 *
 * Note that no enemy must be killed by the logic function. It's a technical limitation
 * and a requirement in FreedroidRPG.
 */
void move_enemies(void)
{
	heal_robots_over_time();

	enemy *erot, *nerot;
	BROWSE_ALIVE_BOTS_SAFE(erot, nerot) {
		// Ignore robots on levels that can't be seen
		if (!level_is_visible(erot->pos.z))
			continue;

		animate_enemy(erot);

		// Run a new cycle of the bot's state machine
		update_enemy(erot);
	}

	BROWSE_DEAD_BOTS_SAFE(erot, nerot) {
		// Ignore robots on levels that can't be seen
		if (!level_is_visible(erot->pos.z))
			continue;

		animate_enemy(erot);
	}
}

/**
 * When an enemy is firing a shot, the newly created bullet must be 
 * assigned a speed, that would lead the bullet towards the intended
 * target, which is done here.
 */
void set_bullet_speed_to_target_direction(bullet * NewBullet, float bullet_speed, float xdist, float ydist)
{
	// determine the direction of the shot, so that it will go into the direction of
	// the target
	//
	if (fabsf(xdist) > fabsf(ydist)) {
		NewBullet->speed.x = bullet_speed;
		NewBullet->speed.y = ydist * NewBullet->speed.x / xdist;
		if (xdist < 0) {
			NewBullet->speed.x = -NewBullet->speed.x;
			NewBullet->speed.y = -NewBullet->speed.y;
		}
	}

	if (fabsf(xdist) < fabsf(ydist)) {
		NewBullet->speed.y = bullet_speed;
		NewBullet->speed.x = xdist * NewBullet->speed.y / ydist;
		if (ydist < 0) {
			NewBullet->speed.x = -NewBullet->speed.x;
			NewBullet->speed.y = -NewBullet->speed.y;
		}
	}
};				// void set_bullet_speed_to_target_direction ( bullet* NewBullet , float bullet_speed , float xdist , float ydist )

/**
 * This function is low-level:  It simply sets off a shot from enemy
 * through the pointer ThisRobot at the target VECTOR xdist ydist, which
 * is a DISTANCE VECTOR, NOT ABSOLUTE COORDINATES OF THE TARGET!!!
 */
static void RawStartEnemysShot(enemy * ThisRobot, float xdist, float ydist)
{
	// If the robot is not in walk or stand animation, i.e. if it's in
	// gethit, death or attack animation, then we can't start another
	// shot/attack right now...
	//
	if ((ThisRobot->animation_type != WALK_ANIMATION) && (ThisRobot->animation_type != STAND_ANIMATION))
		return;

	/* First of all, check what kind of weapon the bot has : ranged or melee */
2186
	struct itemspec weapon_spec = ItemMap[Droidmap[ThisRobot->type].weapon_item.type];
2187

2188
	if (!weapon_spec.weapon_is_melee) {	/* ranged */
2189

2190
		// find a bullet entry, that isn't currently used...
2191
		//
2192 2193 2194 2195 2196 2197
		int bullet_index = find_free_bullet_index();
		if (bullet_index == -1) {
			// We are out of free bullet slots.
			// This should not happen, an error message was displayed,
			return;
		}
2198

2199
		bullet *new_bullet = &(AllBullets[bullet_index]);
2200

2201 2202
		bullet_init_for_enemy(new_bullet, weapon_spec.weapon_bullet_type,
		                      Droidmap[ThisRobot->type].weapon_item.type, ThisRobot);
2203

2204 2205 2206
		// We send the bullet onto it's way towards the given target
		float bullet_speed = (float)weapon_spec.weapon_bullet_speed;
		set_bullet_speed_to_target_direction(new_bullet, bullet_speed, xdist, ydist);
2207

2208 2209
		// Enemies also have to respect the angle modifier in their weapons...
		new_bullet->angle = -(90 + 45 + 180 * atan2(new_bullet->speed.y, new_bullet->speed.x) / M_PI);
2210

2211 2212 2213
		// At this point we mention, that when not moving anywhere, the robot should also
		// face into the direction of the shot
		ThisRobot->previous_angle = new_bullet->angle + 180;
2214

2215 2216 2217
		// Change bullet starting position so that they don't hit the shooter...
		new_bullet->pos.x += (new_bullet->speed.x) / (bullet_speed) * 0.5;
		new_bullet->pos.y += (new_bullet->speed.y) / (bullet_speed) * 0.5;
2218 2219 2220 2221

	} else {		/* melee weapon */

		int shot_index = find_free_melee_shot_index();
2222 2223 2224 2225 2226 2227
		if (shot_index == -1) {
			// We are out of free melee shot slots.
			// This should not happen, an error message was displayed,
			return;
		}

2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
		melee_shot *NewShot = &(AllMeleeShots[shot_index]);

		NewShot->attack_target_type = ThisRobot->attack_target_type;
		NewShot->mine = FALSE;	/* shot comes from a bot not tux */

		if (ThisRobot->attack_target_type == ATTACK_TARGET_IS_ENEMY) {
			NewShot->bot_target_n = ThisRobot->bot_target_n;
			NewShot->bot_target_addr = ThisRobot->bot_target_addr;
		} else {	/* enemy bot attacking tux */
			enemy_set_reference(&NewShot->bot_target_n, &NewShot->bot_target_addr, NULL);
		}

2240 2241
		NewShot->to_hit = Droidmap[ThisRobot->type].to_hit;
		NewShot->damage = weapon_spec.weapon_base_damage + MyRandom(weapon_spec.weapon_damage_modifier);
2242 2243 2244 2245 2246
		NewShot->owner = ThisRobot->id;
	}

	ThisRobot->ammo_left--;
	if (ThisRobot->ammo_left > 0) {
2247
		ThisRobot->firewait += weapon_spec.weapon_attack_time;
2248
	} else {
2249 2250 2251
		ThisRobot->ammo_left = weapon_spec.weapon_ammo_clip_size;
		if (ThisRobot->firewait < weapon_spec.weapon_reloading_time)
			ThisRobot->firewait = weapon_spec.weapon_reloading_time;
2252 2253
	}

2254 2255
	if (ThisRobot->firewait < weapon_spec.weapon_attack_time)
		ThisRobot->firewait = weapon_spec.weapon_attack_time;
2256

2257 2258
	if (last_attack_animation_image[Droidmap[ThisRobot->type].individual_shape_nr] - first_attack_animation_image[Droidmap[ThisRobot->type].individual_shape_nr] > 1) {
		ThisRobot->animation_phase = ((float)first_attack_animation_image[Droidmap[ThisRobot->type].individual_shape_nr]) + 0.1;
2259 2260 2261 2262
		ThisRobot->animation_type = ATTACK_ANIMATION;
		ThisRobot->current_angle = -(-90 + 180 * atan2(ydist, xdist) / M_PI);
	}

2263 2264 2265 2266
	if (!weapon_spec.weapon_is_melee)
		fire_bullet_sound(weapon_spec.weapon_bullet_type, &ThisRobot->pos);
	else
		play_melee_weapon_missed_sound(&ThisRobot->pos);
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477