]> icculus.org git repositories - taylor/freespace2.git/blob - src/ship/aicode.cpp
try to prevent random crashing from wing ai
[taylor/freespace2.git] / src / ship / aicode.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
4  * All source code herein is the property of Volition, Inc. You may not sell 
5  * or otherwise commercially exploit the source or things you created based on
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/Ship/AiCode.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  * 
15  * AI code that does interesting stuff
16  *
17  * $Log$
18  * Revision 1.11  2006/04/26 19:45:22  taylor
19  * fix a FS1 docked speed issue, should keep it in line with the original now
20  *
21  * Revision 1.10  2005/03/29 02:18:47  taylor
22  * Various 64-bit platform fixes
23  * Fix compiler errors with MAKE_FS1 and fix gr_set_bitmap() too
24  * Make sure that turrets can fire at asteroids for FS1 (needed for a couple missions)
25  * Streaming audio support (big thanks to Pierre Willenbrock!!)
26  * Removed dependance on strings.tbl for FS1 since we don't actually need it now
27  *
28  * Revision 1.9  2004/09/20 01:31:44  theoddone33
29  * GCC 3.4 fixes.
30  *
31  * Revision 1.8  2003/08/03 16:10:30  taylor
32  * cleanup; compile warning fixes
33  *
34  * Revision 1.7  2003/05/25 02:30:43  taylor
35  * Freespace 1 support
36  *
37  * Revision 1.6  2002/07/13 19:47:02  theoddone33
38  * Fix some more warnings
39  *
40  * Change demo building, edit Makefile if you want the demo.
41  *
42  * Revision 1.5  2002/06/17 06:33:10  relnev
43  * ryan's struct patch for gcc 2.95
44  *
45  * Revision 1.4  2002/06/09 04:41:26  relnev
46  * added copyright header
47  *
48  * Revision 1.3  2002/06/01 07:12:34  relnev
49  * a few NDEBUG updates.
50  *
51  * removed a few warnings.
52  *
53  * Revision 1.2  2002/05/03 13:34:33  theoddone33
54  * More stuff compiles
55  *
56  * Revision 1.1.1.1  2002/05/03 03:28:10  root
57  * Initial import.
58  *
59  * 
60  * 107   9/15/99 4:42a Mikek
61  * Make any big ship attacking Colossus, or Colossus attacking any large
62  * ship not use big cruiser movement code.
63  * 
64  * 106   9/15/99 3:28a Jimb
65  * Make all big ships in sm3-08 not do cruiser chase code when attacking
66  * Colossus.  Added so Beast doesn't swerve away from Colossus.
67  * 
68  * 105   9/14/99 4:18p Andsager
69  * hack for mission sm3-08 to abort cruiser_chase as sathanas is about to
70  * begin circling colossus.
71  * 
72  * 104   9/08/99 10:44p Andsager
73  * Make HUGE ships not die when warping out, after warp effect started.
74  * 
75  * 103   9/03/99 11:40p Mikek
76  * Comment out an annoying nprintf().
77  * 
78  * 102   9/01/99 11:26p Dave
79  * Fixed release build warnings.
80  * 
81  * 101   9/01/99 9:12p Mikek
82  * Make it a boatload harder to become a traitor from hitting a large
83  * ship.
84  * 
85  * 100   9/01/99 4:01p Andsager
86  * Make sure BIG|HUGE ships do not respond to shockwaves
87  * 
88  * 99    9/01/99 10:09a Dave
89  * Pirate bob.
90  * 
91  * 98    8/31/99 4:24p Andsager
92  * Reduce collisions when attacking big ships.
93  * 
94  * 97    8/31/99 7:33a Mikek
95  * Improvements in formation flying, less silly behavior, especially when
96  * leader is moving very slowly.
97  * 
98  * 96    8/31/99 5:48a Mikek
99  * Making ships not overshoot so much in formation flying.  Intermediate
100  * checkin.
101  * 
102  * 95    8/30/99 12:03a Mikek
103  * Make guard behavior much less annoying.  Guarders don't get quite so
104  * close and they try to avoid striking the target they are guarding.
105  * 
106  * 94    8/29/99 4:18p Andsager
107  * New "burst" limit for friendly damage.  Also credit more damage done
108  * against large friendly ships.
109  * 
110  * 93    8/28/99 7:29p Dave
111  * Fixed wingmen persona messaging. Make sure locked turrets don't count
112  * towards the # attacking a player.
113  * 
114  * 92    8/26/99 10:46p Andsager
115  * Apply shockwave damage to lethality.
116  * 
117  * 91    8/26/99 8:52p Dave
118  * Gave multiplayer TvT messaging a heavy dose of sanity. Cheat codes.
119  * 
120  * 90    8/26/99 5:14p Andsager
121  * 
122  * 89    8/24/99 8:55p Dave
123  * Make sure nondimming pixels work properly in tech menu.
124  * 
125  * 88    8/23/99 6:21p Jefff
126  * added "no traitor" option to missions (and fred)
127  * 
128  * 87    8/20/99 3:36p Andsager
129  * Make sure we don;t miss stealth sweep points.
130  * 
131  * 86    8/16/99 8:21a Andsager
132  * fix link error
133  * 
134  * 85    8/16/99 8:19a Andsager
135  * Add project_point_onto_bbox() to fvi and include in aicode
136  * 
137  * 84    8/15/99 1:30p Dave
138  * Removed some bounding box code because of link errors. Assuming needed
139  * function just needs to get checked in by DaveA.
140  * 
141  * 83    8/15/99 11:59a Andsager
142  * For targing big/huge ships, find nearest distance to bbox, not center.
143  * 
144  * 82    8/13/99 2:20p Andsager
145  * Add speed modification to chances turret will find stealth ship
146  * 
147  * 81    8/13/99 10:49a Andsager
148  * Knossos and HUGE ship warp out.  HUGE ship warp in.  Stealth search
149  * modes dont collide big ships.
150  * 
151  * 80    8/10/99 5:02p Andsager
152  * Fix bug where AI gets stuck in SM_EVADE_WEAPON with no target.
153  * 
154  * 79    8/10/99 11:58a Andsager
155  * Allow turrets to sometimes see stealth.
156  * 
157  * 78    7/31/99 2:57p Dave
158  * Scaled flak aim and jitter by weapon subsystem strength.
159  * 
160  * 77    7/27/99 10:33p Andsager
161  * improve ai for attacking stealth.  reduced jitter in aim.  reduced
162  * error in position when avoiding.  skill level support for attacking
163  * stealth.  Made target error same for team vs. team.
164  * 
165  * 76    7/27/99 10:49a Andsager
166  * Make turret fire rate independent of team for HUGE turrets, and also
167  * for mult team vs. team.
168  * 
169  * 75    7/26/99 12:14p Andsager
170  * Apply cap to how much slower a transport flies with cargo.  Remove
171  * limit on waypoint speed for training.  Enemy ai get stealth exact pos
172  * when stealth fires
173  * 
174  * 74    7/20/99 1:49p Dave
175  * Peter Drake build. Fixed some release build warnings.
176  * 
177  * 73    7/19/99 2:13p Dave
178  * Added some new strings for Heiko.
179  * 
180  * 72    7/19/99 12:02p Andsager
181  * Allow AWACS on any ship subsystem. Fix sexp_set_subsystem_strength to
182  * only blow up subsystem if its strength is > 0
183  * 
184  * 71    7/15/99 9:20a Andsager
185  * FS2_DEMO initial checkin
186  * 
187  * 70    7/14/99 1:44p Andsager
188  * modify ai_guard for BIG ships to circle around the long axis
189  * 
190  * 69    7/09/99 5:54p Dave
191  * Seperated cruiser types into individual types. Added tons of new
192  * briefing icons. Campaign screen.
193  * 
194  * 68    7/08/99 4:32p Andsager
195  * fix bug with turret-tagged-only
196  * 
197  * 67    7/08/99 12:06p Andsager
198  * Add turret-tagged-only and turret-tagged-clear sexp.
199  * 
200  * 66    7/02/99 3:49p Andsager
201  * Remove debug code.  Allow targeting of stealth from any weapon it
202  * fires.
203  * 
204  * 65    7/02/99 2:01p Andsager
205  * Fix bug where big ship tries to evade dumpfire weapon.
206  * 
207  * 64    7/02/99 10:58a Andsager
208  * Put in big ship - big ship attack mode.  Modify stealth sweep ai.
209  * 
210  * 63    6/30/99 5:53p Dave
211  * Put in new anti-camper code.
212  * 
213  * 62    6/28/99 3:22p Anoop
214  * Fix turret optimization, where ship may not have any valid subsystems
215  * (all blown off).
216  * 
217  * 61    6/25/99 5:56p Andsager
218  * First real pass on stealth ai.
219  * 
220  * 60    6/25/99 3:08p Dave
221  * Multiple flyby sounds.
222  * 
223  * 59    6/25/99 1:12p Danw
224  * DKA:  Make sure big ship has subsystems before trying to target them.
225  * 
226  * 58    6/25/99 10:56a Johnson
227  * Fixed dumb ai code.
228  * 
229  * 57    6/24/99 5:15p Dave
230  * Make sure stride is always at least one for checking turret subsystem
231  * targets.
232  * 
233  * 56    6/24/99 4:59p Dave
234  * Significant speedups to turret firing.
235  * 
236  * 55    6/23/99 5:51p Andsager
237  * Add waypoint-cap-speed.  Checkin stealth ai - inactive.
238  * 
239  * 54    6/16/99 10:21a Dave
240  * Added send-message-list sexpression.
241  * 
242  * 53    6/15/99 9:25a Andsager
243  * Make guard and dynamic chase (who hit you) work with stealth
244  * 
245  * 52    6/14/99 3:21p Andsager
246  * Allow collisions between ship and its debris.  Fix up collision pairs
247  * when large ship is warping out.
248  * 
249  * 51    6/14/99 10:45a Dave
250  * Made beam weapons specify accuracy by skill level in the weapons.tbl
251  * 
252  * 50    6/03/99 8:11a Andsager
253  * 
254  * 49    6/02/99 5:41p Andsager
255  * Reduce range of secondary weapons not fired from turrets in nebula.
256  * Reduce range of beams fired from turrrets in nebula
257  * 
258  * 48    6/02/99 3:23p Andsager
259  * Make AI aware of team visibility.  Allow player targeting with team
260  * visibility info.  Make stealth ships not targetable by AI in nebula
261  * unless tagged.
262  * 
263  * 47    6/02/99 12:52p Andsager
264  * Added team-wide ship visibility.  Implemented for player.
265  * 
266  * 46    6/01/99 8:35p Dave
267  * Finished lockarm weapons. Added proper supercap weapons/damage. Added
268  * awacs-set-radius sexpression.
269  * 
270  * 45    5/28/99 5:35p Andsager
271  * Make ai nebula aware
272  * 
273  * 44    5/24/99 9:55a Dave
274  * Fixed stream weapon ai firing problem. ick.
275  * 
276  * 43    5/20/99 7:00p Dave
277  * Added alternate type names for ships. Changed swarm missile table
278  * entries.
279  * 
280  * 42    5/18/99 1:30p Dave
281  * Added muzzle flash table stuff.
282  * 
283  * 41    5/12/99 2:55p Andsager
284  * Implemented level 2 tag as priority in turret object selection
285  * 
286  * 40    5/12/99 10:42a Andsager
287  * Fix turret bug allowing HUGE turrets to fire at fighters
288  * 
289  * 39    5/06/99 11:46a Andsager
290  * Bug fixes.  Don't get into illegal strafe submode.  Don't choose turret
291  * enemy objnum for beam protected.
292  * 
293  * 38    5/03/99 10:50p Andsager
294  * Make Asteroid_obj_list.  Change get_nearest_turret_objnum() to use
295  * Asteroid_obj_list, Ship_obj_list and Missile_obj_list vs.
296  * obj_used_list.
297  * 
298  * 37    4/29/99 2:29p Dave
299  * Made flak work much better in multiplayer.
300  * 
301  * 36    4/28/99 11:36p Dave
302  * Tweaked up subspace missile strike a bit,
303  * 
304  * 35    4/28/99 3:11p Andsager
305  * Stagger turret weapon fire times.  Make turrets smarter when target is
306  * protected or beam protected.  Add weaopn range to weapon info struct.
307  * 
308  * 34    4/26/99 10:58a Andsager
309  * Add OF_BEAM_PROTECTED flag to keep object from being targeted for zing.
310  * 
311  * 33    4/23/99 12:12p Andsager
312  * Modify wing positions when player is wing leader to prevent some
313  * collisions.
314  * 
315  * 32    4/23/99 12:01p Johnson
316  * Added SIF_HUGE_SHIP
317  * 
318  * 31    4/22/99 11:06p Dave
319  * Final pass at beam weapons. Solidified a lot of stuff. All that remains
320  * now is to tweak and fix bugs as they come up. No new beam weapon
321  * features.
322  * 
323  * 30    4/20/99 6:39p Dave
324  * Almost done with artillery targeting. Added support for downloading
325  * images on the PXO screen.
326  * 
327  * 29    4/20/99 3:40p Andsager
328  * Changes to big ship ai.  Uses bounding box as limit where to fly to
329  * when flying away.
330  * 
331  * 28    4/16/99 5:54p Dave
332  * Support for on/off style "stream" weapons. Real early support for
333  * target-painting lasers.
334  * 
335  * 27    4/02/99 9:55a Dave
336  * Added a few more options in the weapons.tbl for beam weapons. Attempt
337  * at putting "pain" packets into multiplayer.
338  * 
339  * 26    3/28/99 5:58p Dave
340  * Added early demo code. Make objects move. Nice and framerate
341  * independant, but not much else. Don't use yet unless you're me :)
342  * 
343  * 25    3/19/99 9:51a Dave
344  * Checkin to repair massive source safe crash. Also added support for
345  * pof-style nebulae, and some new weapons code.
346  * 
347  * 24    3/08/99 7:03p Dave
348  * First run of new object update system. Looks very promising.
349  * 
350  * 23    3/05/99 3:55p Anoop
351  * Handle some asserts properly.
352  * 
353  * 22    3/04/99 6:09p Dave
354  * Added in sexpressions for firing beams and checking for if a ship is
355  * tagged.
356  * 
357  * 21    3/02/99 9:25p Dave
358  * Added a bunch of model rendering debug code. Started work on fixing
359  * beam weapon wacky firing.
360  * 
361  * 20    2/25/99 2:32p Anoop
362  * (Alan). Fixed ai path following code for AI_BAY_EMERGE. Put in sanity
363  * check so that when the last point on the path is reached, it finishes.
364  * 
365  * 19    2/19/99 2:11p Anoop
366  * Put in some nice handling code for wacky support ship problems (like no
367  * docking paths)
368  * 
369  * 18    2/17/99 2:11p Dave
370  * First full run of squad war. All freespace and tracker side stuff
371  * works.
372  * 
373  * 17    2/11/99 5:22p Andsager
374  * Fixed bugs, generalized block Sexp_variables
375  * 
376  * 16    1/29/99 5:07p Dave
377  * Fixed multiplayer stuff. Put in multiplayer support for rapid fire
378  * missiles.
379  * 
380  * 15    1/29/99 2:25p Andsager
381  * Added turret_swarm_missiles
382  * 
383  * 14    1/27/99 9:56a Dave
384  * Temporary checkin of beam weapons for Dan to make cool sounds.
385  * 
386  * 13    1/24/99 11:37p Dave
387  * First full rev of beam weapons. Very customizable. Removed some bogus
388  * Int3()'s in low level net code.
389  * 
390  * 12    1/21/99 10:44a Dave
391  * More beam weapon stuff. Put in warmdown time.
392  * 
393  * 11    1/12/99 5:45p Dave
394  * Moved weapon pipeline in multiplayer to almost exclusively client side.
395  * Very good results. Bandwidth goes down, playability goes up for crappy
396  * connections. Fixed object update problem for ship subsystems.
397  * 
398  * 10    1/08/99 2:08p Dave
399  * Fixed software rendering for pofview. Super early support for AWACS and
400  * beam weapons.
401  * 
402  * 9     12/23/98 2:53p Andsager
403  * Added ship activation and gas collection subsystems, removed bridge
404  * 
405  * 8     11/12/98 12:13a Dave
406  * Tidied code up for multiplayer test. Put in network support for flak
407  * guns.
408  * 
409  * 7     11/05/98 5:55p Dave
410  * Big pass at reducing #includes
411  * 
412  * 6     10/26/98 9:42a Dave
413  * Early flak gun support.
414  * 
415  * 5     10/23/98 3:51p Dave
416  * Full support for tstrings.tbl and foreign languages. All that remains
417  * is to make it active in Fred.
418  * 
419  * 4     10/20/98 1:39p Andsager
420  * Make so sparks follow animated ship submodels.  Modify
421  * ship_weapon_do_hit_stuff() and ship_apply_local_damage() to add
422  * submodel_num.  Add submodel_num to multiplayer hit packet.
423  * 
424  * 3     10/13/98 9:29a Dave
425  * Started neatening up freespace.h. Many variables renamed and
426  * reorganized. Added AlphaColors.[h,cpp]
427  * 
428  * 2     10/07/98 10:53a Dave
429  * Initial checkin.
430  * 
431  * 1     10/07/98 10:51a Dave
432  * 
433  * 
434  * $NoKeywords: $
435  */
436
437 // This module contains the actual AI code that does interesting stuff
438 // to objects.   The code in Ai.cpp is just for bookeeping, allocating
439 // ai slots and linking them to ships.
440
441 #include "pstypes.h"
442 #include "fix.h"
443 #include "linklist.h"
444 #include "object.h"
445 #include "physics.h"
446 #include "vecmat.h"
447 #include "ship.h"
448 #include "model.h"
449 #include "2d.h"
450 #include "3d.h"
451 #include "ai.h"
452 #include "floating.h"
453 #include "player.h"
454 #include "freespace.h"
455 #include "weapon.h"
456 #include "missiongoals.h"
457 #include "missionlog.h"
458 #include "timer.h"
459 #include "sound.h"
460 #include "aigoals.h"
461 #include "gamesnd.h"
462 #include "hudmessage.h"
463 #include "missionmessage.h"
464 #include "cmeasure.h"
465 #include "staticrand.h"
466 #include "multimsgs.h"
467 #include "afterburner.h"
468 #include "hudets.h"
469 #include "shipfx.h"
470 #include "shiphit.h"
471 #include "aibig.h"
472 #include "multiutil.h"
473 #include "hud.h"
474 #include "objcollide.h"
475 #include "asteroid.h"
476 #include "hudlock.h"
477 #include "missiontraining.h"
478 #include "gamesequence.h"
479 #include "joy_ff.h"
480 #include "localize.h"
481 #include "flak.h"
482 #include "beam.h"
483 #include "multi.h"
484 #include "swarm.h"
485 #include "multi_team.h"
486 #include "awacs.h"
487 #include "fvi.h"
488
489 #ifndef PLAT_UNIX
490 #pragma optimize("", off)
491 #pragma auto_inline(off)
492 #endif
493
494 #define UNINITIALIZED_VALUE     -99999.9f
495
496 #define INSTRUCTOR_SHIP_NAME NOX("instructor")
497
498 #define AICODE_SMALL_MAGNITUDE  0.001f          // cosider a vector NULL if mag is less than this
499
500 #define NEXT_REARM_TIMESTAMP (60*1000)                  //      Ships will re-request rearm, typically, after this long.
501
502 #define BEAM_NEBULA_RANGE_REDUCE_FACTOR         0.8
503
504 // AIM_CHASE submode defines
505 // SM_STEALTH_FIND
506 #define SM_SF_AHEAD             0
507 #define SM_SF_BEHIND    1
508 #define SM_SF_BAIL              2
509
510 // SM_STEALTH_SWEEP
511 #define SM_SS_SET_GOAL  -1
512 #define SM_SS_BOX0              0
513 #define SM_SS_LR                        1
514 #define SM_SS_UL                        2
515 #define SM_SS_BOX1              3
516 #define SM_SS_UR                        4
517 #define SM_SS_LL                        5
518 #define SM_SS_BOX2              6
519 #define SM_SS_DONE              7
520
521 //XSTR:OFF
522
523 const char *Mode_text[MAX_AI_BEHAVIORS] = {
524         "CHASE",
525         "EVADE",
526         "GET_BEHIND",
527         "CHASE_LONG",
528         "SQUIGGLE",
529         "GUARD",
530         "AVOID",
531         "WAYPOINTS",
532         "DOCK",
533         "NONE",
534         "BIGSHIP",
535         "PATH",
536         "BE_REARMED",
537         "SAFETY",
538         "EV_WEAPON",
539         "STRAFE",
540         "PLAY_DEAD",
541         "BAY_EMERGE",
542         "BAY_DEPART",
543         "SENTRYGUN",
544         "WARP_OUT",
545 };
546
547 //      Submode text is only valid for CHASE mode.
548 const char *Submode_text[] = {
549 "undefined",
550 "CONT_TURN",
551 "ATTACK   ",
552 "E_SQUIG  ",
553 "E_BRAKE  ",
554 "EVADE    ",
555 "SUP_ATTAK",
556 "AVOID    ",
557 "BEHIND   ",
558 "GET_AWAY ",
559 "E_WEAPON ",
560 "FLY_AWAY ",
561 "ATK_4EVER",
562 "STLTH_FND",
563 "STLTH_SWP",
564 "BIG_APPR",
565 "BIG_CIRC",
566 "BIG_PARL"
567 };
568
569 const char *Strafe_submode_text[5] = {
570 "ATTACK",
571 "AVOID",
572 "RETREAT1",
573 "RETREAT2",
574 "POSITION"
575 };
576 //XSTR:ON
577
578 /*
579 //      Used for global ignore of objects.  If an object appears in the Ignore_objects array,
580 //      no one will attack it.
581 #define MAX_IGNORE_OBJECTS      16
582 typedef struct {
583         int     objnum;
584         int     signature;
585 } ignore_object;
586
587 ignore_object   Ignore_objects[MAX_IGNORE_OBJECTS];
588 */
589
590 typedef struct eval_enemy_obj_struct {
591         int                     turret_parent_objnum;                   // parent of turret
592         float                   weapon_travel_dist;                             // max targeting range of turret weapon
593         int                     enemy_team_mask;
594         int                     weapon_system_ok;                                       // is the weapon subsystem of turret ship ok
595         int                     big_only_flag;                                          // turret fires only at big and huge ships
596         vector          *tpos;
597         vector          *tvec;
598         ship_subsys *turret_subsys;
599         int                     current_enemy;
600
601
602         float                   nearest_attacker_dist;                  // nearest ship 
603         int                     nearest_attacker_objnum;
604
605         float                   nearest_homing_bomb_dist;               // nearest homing bomb
606         int                     nearest_homing_bomb_objnum;
607
608         float                   nearest_bomb_dist;                              // nearest non-homing bomb
609         int                     nearest_bomb_objnum;
610
611         float                   nearest_dist;                                           // nearest ship attacking this turret
612         int                     nearest_objnum;
613 }       eval_enemy_obj_struct;
614
615
616 control_info    AI_ci;
617
618 object *Pl_objp;
619 object *En_objp;
620
621 waypoint_list Waypoint_lists[MAX_WAYPOINT_LISTS];
622
623 // How close a turret has to be point at its target before it
624 // can fire.  If the dot of the gun normal and the vector from gun
625 // to target is greater than this, the turret fires.  The smaller
626 // the sloppier the shooting.
627 #define AICODE_TURRET_DUMBFIRE_ANGLE            (0.8f)  
628 #define AICODE_TURRET_HEATSEEK_ANGLE            (0.7f)  
629 #define AICODE_TURRET_MAX_TIME_IN_RANGE (5.0f)
630
631 #define REARM_SOUND_DELAY               (3*F1_0)                //      Amount of time to delay rearm/repair after mode start
632 #define REARM_BREAKOFF_DELAY    (3*F1_0)                //      Amount of time to wait after fully rearmed to breakoff.
633
634 #define MIN_DIST_TO_WAYPOINT_GOAL       5.0f
635 #define MAX_GUARD_DIST                                  250.0f
636 #define BIG_GUARD_RADIUS                                500.0f
637
638 #define MAX_EVADE_TIME                  (15 * 1000)     //      Max time to evade a weapon.
639
640 // defines for repair ship stuff.
641 #define MAX_REPAIR_SPEED                        25.0f
642 #define MAX_UNDOCK_ABORT_SPEED  2.0f
643
644 // defines for EMP effect stuff
645 #define MAX_EMP_INACCURACY              50.0f
646
647 // defines for stealth
648 #define MAX_STEALTH_INACCURACY  50.0f           // at max view dist
649 #define STEALTH_MAX_VIEW_DIST   400             // dist at which 1) stealth no longer visible 2) firing inaccuracy is greatest
650 #define STEALTH_VIEW_CONE_DOT   0.707           // (half angle of 45 degrees)
651
652
653 ai_class        Ai_classes[MAX_AI_CLASSES];
654 int     Ai_firing_enabled = 1;
655 int     Num_ai_classes;
656
657 int     AI_FrameCount = 0;
658 int     Ship_info_inited = 0;
659 int     AI_watch_object = 0; // Debugging, object to spew debug info for.
660 int     Num_waypoint_lists = 0;
661 int     Mission_all_attack = 0;                                 //      !0 means all teams attack all teams.
662
663 const char *Skill_level_names(int level, int translate)
664 {
665         const char *str = NULL;
666
667         #if NUM_SKILL_LEVELS != 5
668         #error Number of skill levels is wrong!
669         #endif
670
671         if(translate){
672                 switch( level ) {
673                 case 0:
674                         str = XSTR("Very Easy", 469);
675                         break;
676                 case 1:
677                         str = XSTR("Easy", 470);
678                         break;
679                 case 2:
680                         str = XSTR("Medium", 471);
681                         break;
682                 case 3:
683                         str = XSTR("Hard", 472);
684                         break;
685                 case 4:
686                         str = XSTR("Insane", 473);
687                         break;
688                 default:        
689                         Int3();
690                 }
691         } else {
692                 switch( level ) {
693                 case 0:
694                         str = NOX("Very Easy");
695                         break;
696                 case 1:
697                         str = NOX("Easy");
698                         break;
699                 case 2:
700                         str = NOX("Medium");
701                         break;
702                 case 3:
703                         str = NOX("Hard");
704                         break;
705                 case 4:
706                         str = NOX("Insane");
707                         break;
708                 default:        
709                         Int3();
710                 }
711         }
712
713         return str;
714 }
715
716 #define DELAY_TARGET_TIME       (12*1000)               //      time in milliseconds until a ship can target a new enemy after an order.
717
718 //      Make enemy ships turn more slowly at lower skill levels.
719 float   Turn_time_skill_level_scale[NUM_SKILL_LEVELS] = {3.0f, 2.2f, 1.6f, 1.3f, 1.0f};
720
721 //      Maximum number of simultaneous homing weapons on player based on skill level.
722 int     Max_allowed_player_homers[NUM_SKILL_LEVELS] = {2, 3, 4, 7, 99};
723
724 //      Number of ships that can attack another ship at a given skill level.
725 int     Skill_level_max_attackers[NUM_SKILL_LEVELS] = {2, 3, 4, 5, 99};
726
727 //      How long until next predict position.
728 fix Skill_level_delay[NUM_SKILL_LEVELS] = {2*F1_0, 3*F1_0/2, 4*F1_0/3, F1_0/2, 0};
729
730 //      AI ships link primary weapons if energy levels greater than the following amounts:
731 float   Link_energy_levels_always[NUM_SKILL_LEVELS] = {100.0f, 80.0f, 60.0f, 40.0f, 20.0f};     //      always link
732 float   Link_energy_levels_maybe[NUM_SKILL_LEVELS] = {90.0f, 60.0f, 40.0f, 20.0f, 10.0f};       //      link if hull strength low
733
734 //      Seconds to add to time it takes to get enemy in range.  Only for player's enemies.
735 float   In_range_time[NUM_SKILL_LEVELS] = {2.0f, 1.4f, 0.75f, 0.0f, -1.0f};
736
737 //      No matter what, a random unit vector gets scaled by this amount in firing at an enemy.
738 //      Note that for shorter in-range times, these values get scaled, so a value of 0.5f is meaningful.
739 float   Aiming_error[NUM_SKILL_LEVELS] = {3.0f, 2.2f, 1.3f, 0.7f, 0.2f};
740
741 //      Chance a countermeasure will be fired based on skill level.
742 float Cmeasure_fire_chance[NUM_SKILL_LEVELS] = {0.2f, 0.3f, 0.5f, 0.9f, 1.1f};  //      Note, this gets scaled by ai_class
743
744 float Shield_manage_delays[NUM_SKILL_LEVELS] = {5.0f, 4.0f, 2.5f, 1.2f, 0.1f};
745
746 // accuracy we feed into the beam weapons based upon skill system
747 // float Beam_accuracy[NUM_SKILL_LEVELS] = {2.0f, 1.5f, 1.0f, 0.7f, 0.4f};
748
749 extern float Ship_fire_delay_scale_hostile[NUM_SKILL_LEVELS];
750 extern float Ship_fire_delay_scale_friendly[NUM_SKILL_LEVELS];
751
752 pnode           Path_points[MAX_PATH_POINTS];
753 pnode           *Ppfp;                  //      Free pointer in path points.
754
755 float   AI_frametime;
756
757 char *Ai_class_names[MAX_AI_CLASSES];
758
759 // global for rearm status for teams
760 int Ai_friendly_rearm_timestamp, Ai_hostile_rearm_timestamp, Ai_neutral_rearm_timestamp, Ai_traitor_rearm_timestamp, Ai_unknown_rearm_timestamp;
761
762 // globals for dealing with when to fire huge secondary weapons
763 #define MAX_HUGE_SECONDARY_INFO 10
764
765 typedef struct {
766         int team;
767         int weapon_index;
768         int max_fire_count;
769         char    *shipname;
770 } huge_fire_info;
771
772 huge_fire_info Ai_huge_fire_info[MAX_HUGE_SECONDARY_INFO];
773
774 int Ai_last_arrive_path;        // index of ship_bay path used by last arrival from a fighter bay
775
776 // forward declarations
777 int     ai_return_path_num_from_dockbay(object *dockee_objp, int dockbay_index);
778 void    create_model_exit_path(object *pl_objp, object *mobjp, int path_num, int count=1);
779 void    copy_xlate_model_path_points(object *objp, model_path *mp, int dir, int count, int path_num, pnode *pnp, int randomize_pnt=-1);
780
781 // ai_set_rearm_status takes a team (friendly, hostile, neutral) and a time.  This function
782 // sets the timestamp used to tell is it is a good time for this team to rearm.  Once the timestamp
783 // is no longer valid, then rearming is not a "good time"
784 // not safe.  Called from sexpression code.
785 void ai_set_rearm_status( int team, int time )
786 {
787         SDL_assert( time >= 0 );
788
789         switch (team) {
790         case TEAM_FRIENDLY:
791                 Ai_friendly_rearm_timestamp = timestamp( time * 1000 );
792                 break;
793         case TEAM_HOSTILE:
794                 Ai_hostile_rearm_timestamp = timestamp( time * 1000 );
795                 break;
796         case TEAM_NEUTRAL:
797                 Ai_neutral_rearm_timestamp = timestamp( time * 1000 );
798                 break;
799         case TEAM_TRAITOR:
800                 Ai_traitor_rearm_timestamp = timestamp( time * 1000 );
801                 break;
802         case TEAM_UNKNOWN:
803                 Ai_traitor_rearm_timestamp = timestamp( time * 1000 );
804                 break;
805         default:
806                 Int3();
807                 break;
808         }
809 }
810
811 // int ai_good_time_to_rearm returns true(1) or false(0) if it is "safe" for the given
812 // object to rearm.  "safe" is currently defined by the mission designer using the good/bad
813 // time to rearm sexpressions.  This status is currently team based.  This function could
814 // be easily expended to further the definition of "safe"
815 int ai_good_time_to_rearm( object *objp )
816 {
817         int team, status;
818
819         SDL_assert(objp->type == OBJ_SHIP);
820         team = Ships[objp->instance].team;
821         status = 0;
822
823         switch(team) {
824         case TEAM_FRIENDLY:
825                 status = timestamp_valid(Ai_friendly_rearm_timestamp);
826                 break;
827         case TEAM_HOSTILE:
828                 status = timestamp_valid(Ai_hostile_rearm_timestamp);
829                 break;
830         case TEAM_NEUTRAL:
831                 status = timestamp_valid(Ai_neutral_rearm_timestamp);
832                 break;
833         case TEAM_TRAITOR:
834                 status = timestamp_valid(Ai_traitor_rearm_timestamp);
835                 break;
836         case TEAM_UNKNOWN:
837                 status = timestamp_valid(Ai_unknown_rearm_timestamp);
838                 break;
839         default:
840                 Int3();
841                 break;
842         }
843
844         return status;
845 }
846
847 // functions to deal with letting the ai know about good times to fire powerful secondary
848 // weapons.
849
850 // this function is entry point from sexpression code to set internal data for use by ai code.
851 void ai_good_secondary_time( int team, int weapon_index, int max_fire_count, char *shipname )
852 {
853         int i, index;
854
855         // find an open slot to put this data
856         for ( i = 0; i < MAX_HUGE_SECONDARY_INFO; i++ ) {
857                 if ( Ai_huge_fire_info[i].weapon_index == -1 )
858                         break;
859         }
860
861         SDL_assert( i < MAX_HUGE_SECONDARY_INFO );                      // we've run out of room
862
863         Ai_huge_fire_info[i].weapon_index = weapon_index;
864         Ai_huge_fire_info[i].team = team;
865         Ai_huge_fire_info[i].max_fire_count = max_fire_count;
866
867         Ai_huge_fire_info[i].shipname = ai_get_goal_ship_name( shipname, &index );
868 }
869
870 // function called internally to the ai code to tell whether or not weapon_num can be fired
871 // from firer_objp at target_objp.  This function will resolve the team for the firer.
872 // returns:
873 //              -1  -- when conditions don't allow firer to fire weapon_num on target_objp
874 //              >=0 -- when conditions allow firer to fire.  Return value is max number of weapon_nums
875 //           which can be fired on target_objp
876 int is_preferred_weapon(int weapon_num, object *firer_objp, object *target_objp)
877 {
878         int i, firer_team, target_signature;
879         ship *firer_ship;
880         huge_fire_info *hfi = NULL;
881
882         SDL_assert( firer_objp->type == OBJ_SHIP );
883         firer_ship = &Ships[firer_objp->instance];
884         firer_team = firer_ship->team;
885
886         // get target object's signature and try to find it in the list.
887         target_signature = target_objp->signature;
888         for ( i = 0; i < MAX_HUGE_SECONDARY_INFO; i++ ) {
889                 int ship_index, signature;
890
891                 hfi = &Ai_huge_fire_info[i];
892                 if ( hfi->weapon_index == -1 )
893                         continue;
894
895                 ship_index = ship_name_lookup( hfi->shipname );
896                 if ( ship_index == -1 )
897                         continue;
898
899                 signature = Objects[Ships[ship_index].objnum].signature;
900
901                 // sigatures, weapon_index, and team must match
902                 if ( (signature == target_signature) && (hfi->weapon_index == weapon_num) && (hfi->team == firer_team) )
903                         break;
904         }
905
906         // return -1 if not found
907         if ( i == MAX_HUGE_SECONDARY_INFO )
908                 return -1;
909
910         // otherwise, we can return the max number of weapons we can fire against target_objps
911
912         return hfi->max_fire_count;
913 }
914
915 // function to clear out secondary firing infomration between levels
916 void ai_init_secondary_info()
917 {
918         int i;
919
920         // clear out the data for dealing with when ai ships can fire huge secondary weapons
921         for (i = 0; i < MAX_HUGE_SECONDARY_INFO; i++ ) {
922                 Ai_huge_fire_info[i].weapon_index = -1;
923                 Ai_huge_fire_info[i].team = -1;
924                 Ai_huge_fire_info[i].max_fire_count = -1;
925                 Ai_huge_fire_info[i].shipname = NULL;
926         }
927 }
928
929
930 //      Garbage collect the Path_points buffer.
931 //      Scans all objects, looking for used Path_points records.
932 //      Compresses Path_points buffer, updating aip->path_start and aip->path_cur indices.
933 //      Updates Ppfp to point to first free record.
934 //      This function is fairly fast.  Its worst-case running time is proportional to
935 //      3*MAX_PATH_POINTS + MAX_OBJECTS
936 //      Things to do to optimize this function:
937 //              1. if (t != 0) xlt++; can be replaced by xlt += t; assuming t can only be 0 or 1.
938 //              2. When pp_xlate is getting stuffed the first time, note highest index and use that 
939 //                      instead of MAX_PATH_POINTS in following two for loops.
940 void garbage_collect_path_points()
941 {
942         int     i;
943         int     pp_xlate[MAX_PATH_POINTS];
944         object  *A;
945         ship_obj        *so;
946
947         //      Scan all objects and create Path_points xlate table.
948         for (i=0; i<MAX_PATH_POINTS; i++)
949                 pp_xlate[i] = 0;
950
951         //      in pp_xlate, mark all used Path_point records
952         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
953                 A = &Objects[so->objnum];
954                 ship    *shipp = &Ships[A->instance];
955                 if (shipp->ai_index != -1) {
956                         ai_info *aip = &Ai_info[shipp->ai_index];
957
958                         if ((aip->path_length > 0) && (aip->path_start > -1)) {
959
960                                 for (i=aip->path_start; i<aip->path_start + aip->path_length; i++) {
961                                         SDL_assert(pp_xlate[i] == 0);   //      If this is not 0, then two paths use this point!
962                                         pp_xlate[i] = 1;
963                                 }
964                         }
965                 }
966         }
967
968         //      Now, stuff xlate index in pp_xlate.  This is the number to translate any path_start
969         //      or path_cur index to.
970         int     xlt = 0;
971         for (i=0; i<MAX_PATH_POINTS; i++) {
972                 int     t = pp_xlate[i];
973
974                 pp_xlate[i] = xlt;
975                 if (t != 0)
976                         xlt++;
977         }
978         
979         //      Update global Path_points free pointer.
980         Ppfp = &Path_points[xlt];
981
982         //      Now, using pp_xlate, fixup all aip->path_cur and aip->path_start indices
983         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
984                 A = &Objects[so->objnum];
985                 ship    *shipp = &Ships[A->instance];
986                 if (shipp->ai_index != -1) {
987                         ai_info *aip = &Ai_info[shipp->ai_index];
988
989                         if ((aip->path_length > 0) && (aip->path_start > -1)) {
990                                 SDL_assert(aip->path_start < MAX_PATH_POINTS);
991                                 aip->path_start = pp_xlate[aip->path_start];
992
993                                 SDL_assert((aip->path_cur >= 0) && (aip->path_cur < MAX_PATH_POINTS));
994                                 aip->path_cur = pp_xlate[aip->path_cur];
995                         }
996                 }
997         }
998
999         //      Now, compress the buffer.
1000         for (i=0; i<MAX_PATH_POINTS; i++)
1001                 if (i != pp_xlate[i])
1002                         Path_points[pp_xlate[i]] = Path_points[i];
1003
1004 }
1005
1006 //      Hash two values together, return result.
1007 //      Hash function: curval shifted right circular by one, newval xored in.
1008 int hash(unsigned int curval, int newval)
1009 {
1010         int     addval = curval & 1;
1011
1012         curval >>= 1;
1013         if (addval)
1014                 curval |= 0x80000000;
1015         curval ^= newval;
1016
1017         return curval;
1018 }
1019
1020 //      Hash some information in an object together.
1021 //      On 2/20/97, the information is position and orientation.
1022 int create_object_hash(object *objp)
1023 {
1024         int     *ip;
1025         unsigned int    hashval = 0;
1026         int     i;
1027
1028         ip = (int *) &objp->orient;
1029
1030         for (i=0; i<9; i++) {
1031                 hashval = hash(hashval, *ip);
1032                 ip++;
1033         }
1034
1035         ip = (int *) &objp->pos;
1036
1037         for (i=0; i<3; i++) {
1038                 hashval = hash(hashval, *ip);
1039                 ip++;
1040         }
1041
1042         return hashval;
1043 }
1044
1045 //      Stuff a list of NUM_SKILL_LEVELS floats at *plist.
1046 void parse_float_list(float *plist)
1047 {
1048         int     i;
1049
1050         for (i=0; i<NUM_SKILL_LEVELS; i++) {
1051                 stuff_float(&plist[i]);
1052         }
1053 }
1054
1055 void parse_ai_class()
1056 {
1057         ai_class        *aicp = &Ai_classes[Num_ai_classes];
1058
1059         required_string("$Name:");
1060         stuff_string(aicp->name, F_NAME, NULL);
1061
1062         Ai_class_names[Num_ai_classes] = aicp->name;
1063
1064         required_string("$accuracy:");
1065         parse_float_list(aicp->ai_accuracy);
1066
1067         required_string("$evasion:");
1068         parse_float_list(aicp->ai_evasion);
1069
1070         required_string("$courage:");
1071         parse_float_list(aicp->ai_courage);
1072
1073         required_string("$patience:");
1074         parse_float_list(aicp->ai_patience);
1075 }
1076
1077 void parse_aitbl()
1078 {
1079         // open localization
1080         lcl_ext_open();
1081
1082         read_file_text("ai.tbl");
1083
1084         reset_parse();
1085
1086         Num_ai_classes = 0;
1087
1088         required_string("#AI Classes");
1089
1090         while (required_string_either("#End", "$Name:")) {
1091                 SDL_assert( Num_ai_classes < MAX_AI_CLASSES);
1092
1093                 parse_ai_class();
1094
1095                 Num_ai_classes++;
1096         }
1097
1098         // close localization
1099         lcl_ext_close();
1100 }
1101
1102 static int ai_inited = 0;
1103
1104 //========================= BOOK-KEEPING FUNCTIONS =======================
1105
1106 // Called once at game start-up
1107 void ai_init()
1108 {
1109         if ( !ai_inited )       {
1110                 // Do the first time initialization stuff here
1111                 try {
1112                         parse_aitbl();                  
1113                 } catch (parse_error_t rval) {
1114                         Error(LOCATION, "Error parsing 'ai.tbl'\r\nError code = %i.\r\n", (int)rval);
1115                 }
1116
1117                 ai_inited = 1;
1118         }
1119
1120         init_semirand();
1121         
1122         ai_level_init();
1123 }
1124
1125 // this inits the ai.  You should be able to call this between
1126 // levels to reset everything.
1127 void ai_level_init()
1128 {
1129         int i;
1130  
1131         // Do the stuff to reset all ai stuff here
1132         for (i=0; i<MAX_AI_INFO ; i++) {
1133                 Ai_info[i].shipnum = -1;
1134         }
1135         Ai_goal_signature = 0;
1136         Ai_friendly_rearm_timestamp = timestamp(-1);
1137         Ai_hostile_rearm_timestamp = timestamp(-1);
1138         Ai_neutral_rearm_timestamp = timestamp(-1);
1139         Ai_traitor_rearm_timestamp = timestamp(-1);
1140
1141         // clear out the stuff needed for AI firing powerful secondary weapons
1142         ai_init_secondary_info();
1143
1144         Ai_last_arrive_path=0;
1145 }
1146
1147 // BEGIN STEALTH
1148 // -----------------------------------------------------------------------------
1149 // Check if object is a stealth ship
1150 int is_object_stealth_ship(object* objp)
1151 {
1152         if (objp->type == OBJ_SHIP) {
1153                 if (Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_STEALTH) {
1154                         return 1;
1155                 }
1156         }
1157
1158         // not stealth ship
1159         return 0;
1160 }
1161
1162 // -----------------------------------------------------------------------------
1163 // Init necessary ai info for new stealth target
1164 void init_ai_stealth_info(ai_info *aip, object *stealth_objp)
1165 {
1166         SDL_assert(is_object_stealth_ship(stealth_objp));
1167
1168         // set necessary ai info for new stealth target
1169         aip->stealth_last_pos = stealth_objp->pos;
1170         aip->stealth_velocity = stealth_objp->phys_info.vel;
1171         aip->stealth_last_visible_stamp = timestamp();
1172 }
1173
1174 // -----------------------------------------------------------------------------
1175 // Check whether Pl_objp can see a stealth ship object
1176 #define STEALTH_INVISIBLE                       0
1177 #define STEALTH_VISIBLE                         1
1178 #define STEALTH_FULLY_TARGETABLE        2
1179
1180 float get_skill_stealth_dist_scaler()
1181 {
1182         // return dist scaler based on skill level
1183         switch (Game_skill_level) {
1184         case 0: // very easy
1185                 return 0.65f;
1186
1187         case 1: // easy
1188                 return 0.9f;
1189
1190         case 2: // medium
1191                 return 1.0f;
1192
1193         case 3: // hard
1194                 return 1.1f;
1195
1196         case 4: // insane
1197                 return 1.3f;
1198
1199         default:
1200                 Int3();
1201         }
1202
1203         return 1.0f;
1204 }
1205
1206 float get_skill_stealth_dot_scaler()
1207 {
1208         // return multiplier on dot based on skill level
1209         switch (Game_skill_level) {
1210         case 0: // very easy
1211                 return 1.3f;
1212
1213         case 1: // easy
1214                 return 1.1f;
1215
1216         case 2: // medium
1217                 return 1.0f;
1218
1219         case 3: // hard
1220                 return 0.9f;
1221
1222         case 4: // insane
1223                 return 0.7f;
1224
1225         default:
1226                 Int3();
1227         }
1228
1229         return 1.0f;
1230 }
1231
1232 int ai_is_stealth_visible(object *viewer_objp, object *stealth_objp)
1233 {
1234         vector vec_to_stealth;
1235         float dot_to_stealth, dist_to_stealth, max_stealth_dist;
1236
1237         SDL_assert(stealth_objp->type == OBJ_SHIP);
1238         SDL_assert(viewer_objp->type == OBJ_SHIP);
1239
1240         // check if stealth ship
1241         SDL_assert(Ship_info[Ships[stealth_objp->instance].ship_info_index].flags & SIF_STEALTH);
1242
1243         // check if in neb and below awac level for visible
1244         if ( !ship_is_visible_by_team(stealth_objp->instance, Ships[viewer_objp->instance].team) ) {
1245                 vm_vec_sub(&vec_to_stealth, &stealth_objp->pos, &viewer_objp->pos);
1246                 dist_to_stealth = vm_vec_mag_quick(&vec_to_stealth);
1247                 dot_to_stealth = vm_vec_dotprod(&viewer_objp->orient.v.fvec, &vec_to_stealth) / dist_to_stealth;
1248
1249                 // get max dist at which stealth is visible
1250                 max_stealth_dist = get_skill_stealth_dist_scaler() * STEALTH_MAX_VIEW_DIST;
1251
1252                 // now check if within view frustrum
1253                 float needed_dot_to_stealth;
1254                 if (dist_to_stealth < 100) {
1255                         needed_dot_to_stealth = 0.0f;
1256                 } else {
1257                         needed_dot_to_stealth = get_skill_stealth_dot_scaler() * float(STEALTH_VIEW_CONE_DOT) * (dist_to_stealth / max_stealth_dist);
1258                 }
1259                 if (dot_to_stealth > needed_dot_to_stealth) {
1260                         if (dist_to_stealth < max_stealth_dist) {
1261                                 return STEALTH_VISIBLE;
1262                         }
1263                 }
1264
1265                 // not within frustrum
1266                 return STEALTH_INVISIBLE;
1267         }
1268
1269         // visible by awacs level
1270         return STEALTH_FULLY_TARGETABLE;
1271 }
1272
1273 // END STEALTH
1274
1275 //      Compute dot product of direction vector and forward vector.
1276 //      Direction vector is vector from one object to other object.
1277 //      Forward vector is the forward vector of the ship.
1278 //      If from_dot == NULL, don't fill it in.
1279 float compute_dots(object *objp, object *other_objp, float *to_dot, float *from_dot)
1280 {
1281         vector  v2o;
1282         float           dist;
1283
1284         dist = vm_vec_normalized_dir(&v2o, &other_objp->pos, &objp->pos);
1285
1286         *to_dot = vm_vec_dot(&objp->orient.v.fvec, &v2o);
1287
1288         if (from_dot != NULL)
1289                 *from_dot = - vm_vec_dot(&other_objp->orient.v.fvec, &v2o);
1290
1291         return dist;
1292 }
1293
1294 // -----------------------------------------------------------------------------
1295 // update estimated stealth info
1296 // this is a "cheat" update
1297 // error increases with time not seen, true distance away, dot to enemey
1298 // this is done only if we can not see the stealth target
1299 // need to infer its position either by weapon fire pos or last know pos
1300 void update_ai_stealth_info_with_error(ai_info *aip/*, int no_error*/)
1301 {
1302 //      object *ship;
1303         object *stealth_objp;
1304         /*
1305         float error_time_mult, error_dist_mult, error_dot_mult, error_mult;
1306         float pos_error, vel_error;
1307         vector error_vec, vec_to_stealth;
1308         float dist_to_stealth, dot_to_stealth;
1309         float delta_time, delta_capped;
1310         */
1311
1312         // make sure I am targeting a stealth ship
1313         SDL_assert( is_object_stealth_ship(&Objects[aip->target_objnum]) );
1314         stealth_objp = &Objects[aip->target_objnum];
1315
1316         // my_ship
1317 //      ship = &Objects[Ships[aip->shipnum].objnum];
1318
1319         // if update is due to weapon fire, get exact stealth position
1320 //      if (no_error) {
1321         aip->stealth_last_pos = stealth_objp->pos;
1322         aip->stealth_velocity = stealth_objp->phys_info.vel;
1323         aip->stealth_last_visible_stamp = timestamp();
1324 //              return;
1325 //      }
1326 /*
1327         // get time since last seen
1328         delta_time = 0.001f * (timestamp() - aip->stealth_last_visible_stamp);
1329
1330         // we don't want our "cheat" guess to more off than what we would get from extrapolating from last visible
1331         // only update if stealth info is "old"
1332         if ( (delta_time) < 0.5 ) {
1333                 return;
1334         }
1335
1336         // find vec_to_stealth and dist
1337         vm_vec_sub(&vec_to_stealth, &stealth_objp->pos, &ship->pos);
1338         dist_to_stealth = vm_vec_normalize_quick(&vec_to_stealth);
1339         dot_to_stealth = vm_vec_dotprod(&vec_to_stealth, &ship->orient.v.fvec);
1340
1341         // put cap on time
1342         delta_capped = delta_time;
1343         if (delta_time > 5.0) {
1344                 delta_capped = 5.0f;
1345         }
1346
1347         // erorr_time_mult (for 0-5) -> (1-6)
1348         error_time_mult = (1.0f + delta_capped);
1349
1350         // error_dot_mult (-1 to 1) -> (1-3)
1351         error_dot_mult = (2 - dot_to_stealth);
1352
1353         // error_dist_mult (0-1000+) -> (1-4)
1354         error_dist_mult = dist_to_stealth * 4.0f * 0.001f;
1355         if (error_dist_mult < 1) {
1356                 error_dist_mult = 1.0f;
1357         } else if (error_dist_mult > 4) {
1358                 error_dist_mult = 4.0f;
1359         }
1360
1361         // multiply error out
1362         error_mult = error_time_mult * error_dot_mult * error_dist_mult;
1363
1364         float base_pos_error = 10;
1365         float base_vel_error = 2;
1366
1367         // find the position and velocity error magnitude;
1368         pos_error = base_pos_error * error_mult;
1369         vel_error = base_vel_error * error_mult;
1370
1371         // get an error that changes slowly over time
1372         static_randvec( ((int)aip ^ (Missiontime >> 18)) & 7, &error_vec);
1373         vm_vec_zero(&error_vec);
1374
1375         // update pos and vel with error
1376         vm_vec_scale_add(&aip->stealth_velocity, &stealth_objp->phys_info.vel, &error_vec, vel_error);
1377
1378         // revise last "known" position to arrive at last pos with given error
1379         vm_vec_scale_add(&aip->stealth_last_pos, &stealth_objp->pos, &error_vec, pos_error);
1380         vm_vec_scale_add2(&aip->stealth_last_pos, &aip->stealth_velocity, -(0.001f * delta_time));
1381         */
1382 }
1383
1384 //      Update danger_weapon_objnum and signature in ai_info to say this weapon is to be avoided.
1385 void ai_update_danger_weapon(int attacked_objnum, int weapon_objnum)
1386 {
1387         object  *objp, *weapon_objp;
1388         ai_info *aip;
1389         float           old_dist, new_dist;
1390         float           old_dot, new_dot;
1391         object  *old_weapon_objp = NULL;
1392
1393         if ((attacked_objnum == -1) || (weapon_objnum == -1)) {
1394                 return;
1395         }
1396
1397         objp = &Objects[attacked_objnum];
1398
1399         // AL 2-24-98: If this isn't a ship, we don't need to worry about updating weapon_objnum (ie it would be
1400         //                                      an asteroid or bomb).
1401         if ( objp->type != OBJ_SHIP ) {
1402                 return;
1403         }
1404
1405         weapon_objp = &Objects[weapon_objnum];
1406
1407         aip = &Ai_info[Ships[objp->instance].ai_index];
1408
1409         // if my taraget is a stealth ship and is not visible
1410         if (aip->target_objnum >= 0) {
1411                 if ( is_object_stealth_ship(&Objects[aip->target_objnum]) ) {
1412                         if ( ai_is_stealth_visible(objp, &Objects[aip->target_objnum]) == STEALTH_INVISIBLE ) {
1413                                 // and the weapon is coming from that stealth ship
1414                                 if (weapon_objp->parent == aip->target_objnum) {
1415                                         // update my position estimate for stealth ship
1416                                         update_ai_stealth_info_with_error(aip/*, 1*/);
1417                                 }
1418                         }
1419                 }
1420         }
1421
1422         if (aip->danger_weapon_objnum != -1) {
1423                 old_weapon_objp = &Objects[aip->danger_weapon_objnum];
1424                 if ((old_weapon_objp->type == OBJ_WEAPON) && (old_weapon_objp->signature == aip->danger_weapon_signature)) {
1425                         ;
1426                 } else {
1427                         aip->danger_weapon_objnum = -1;
1428                 }
1429         }
1430
1431         new_dist = compute_dots(weapon_objp, objp, &new_dot, NULL);
1432
1433         if (aip->danger_weapon_objnum == -1) {
1434                 if (new_dist < 1500.0f) {
1435                         if (new_dot > 0.5f) {
1436                                 aip->danger_weapon_objnum = weapon_objnum;
1437                                 aip->danger_weapon_signature = weapon_objp->signature;
1438                         }
1439                 }
1440         } else {
1441                 SDL_assert(old_weapon_objp != NULL);
1442                 old_dist = compute_dots(old_weapon_objp, objp, &old_dot, NULL);
1443         
1444                 if (old_dot < 0.5f) {
1445                         aip->danger_weapon_objnum = -1;
1446                         old_dist = 9999.9f;
1447                 }
1448
1449                 if ((new_dot > 0.5f) && (new_dot > old_dot-0.01f)) {
1450                         if (new_dist < old_dist) {
1451                                 aip->danger_weapon_objnum = weapon_objnum;
1452                                 aip->danger_weapon_signature = weapon_objp->signature;
1453                         }
1454                 }
1455         }
1456 }
1457
1458 //      If rvec != NULL, use it to match bank by calling vm_matrix_interpolate.
1459 //      (rvec defaults to NULL)
1460 void ai_turn_towards_vector(vector *dest, object *objp, 
1461                                                                          float frametime, float turn_time, vector *slide_vec, vector *rel_pos, float bank_override, int flags, vector *rvec)
1462 {
1463         //matrix        goal_orient;
1464         matrix  curr_orient;
1465         vector  vel_in, vel_out, desired_fvec, src;
1466         float           delta_time;
1467         physics_info    *pip;
1468         vector  vel_limit, acc_limit;
1469         float           delta_bank;
1470
1471         //      Don't allow a ship to turn if it has no engine strength.
1472         // AL 3-12-98: objp may not always be a ship!
1473         if ( objp->type == OBJ_SHIP ) {
1474                 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f)
1475                         return;
1476         }
1477                         
1478         //nprintf(("AI", "Ship %s turning towards point %7.3f %7.3f %7.3f\n", Ships[objp->instance].ship_name, dest->x, dest->y, dest->z));
1479         pip = &objp->phys_info;
1480
1481         vel_in = pip->rotvel;
1482         curr_orient = objp->orient;
1483         delta_time = flFrametime;
1484
1485         SDL_assert(turn_time > 0.0f);
1486         
1487         //      Scale turn_time based on skill level and team.
1488         if (!(flags & AITTV_FAST)){
1489                 if (objp->type == OBJ_SHIP){
1490                         if (Ships[objp->instance].team != Ships[Player_obj->instance].team){
1491                                 turn_time *= Turn_time_skill_level_scale[Game_skill_level];
1492                         }
1493                 }
1494         }
1495
1496         //      Set max turn rate.
1497         vel_limit.xyz.x = 2*PI/turn_time;
1498         vel_limit.xyz.y = 2*PI/turn_time;
1499         vel_limit.xyz.z = 2*PI/turn_time;
1500
1501         //      Set rate at which ship can accelerate to its rotational velocity.
1502         //      For now, weapons just go much faster.
1503         acc_limit = vel_limit;
1504         if (objp->type == OBJ_WEAPON)
1505                 vm_vec_scale(&acc_limit, 8.0f);
1506
1507         src = objp->pos;
1508
1509         if (rel_pos != NULL) {
1510                 vector  gun_point;
1511                 vm_vec_unrotate(&gun_point, rel_pos, &objp->orient);
1512                 vm_vec_add2(&src, &gun_point);
1513         }
1514
1515         vm_vec_normalized_dir(&desired_fvec, dest, &src);
1516
1517         //      Since ship isn't necessarily moving in the direction it's pointing, sometimes it's better
1518         //      to be moving towards goal rather than just pointing.  So, if slide_vec is !NULL, try to
1519         //      make ship move towards goal, not point at goal.
1520         if (slide_vec != NULL) {
1521                 vm_vec_add2(&desired_fvec, slide_vec);
1522                 vm_vec_normalize(&desired_fvec);
1523         }
1524
1525         //      Should be more general case here.  Currently, anything that is not a weapon will bank when it turns.
1526         if (objp->type == OBJ_WEAPON)
1527                 delta_bank = 0.0f;
1528         else if ((bank_override) && (Ships[objp->instance].team & opposing_team_mask(Player_ship->team))) {     //      Theoretically, this will only happen for Shivans.
1529                 delta_bank = bank_override;
1530                 //nprintf(("AI", "%i: %7.3f\n", Framecount, bank_override));
1531         } else {
1532                 delta_bank = vm_vec_dot(&curr_orient.v.rvec, &objp->last_orient.v.rvec);
1533                 delta_bank = 100.0f * (1.0f - delta_bank);
1534                 if (vm_vec_dot(&objp->last_orient.v.fvec, &objp->orient.v.rvec) < 0.0f)
1535                         delta_bank = -delta_bank;
1536
1537                 //nprintf(("AI", "%s: Frame %i: delta bank = %7.3f\n", Ships[objp->instance].ship_name, Framecount, delta_bank));
1538         }
1539
1540         //      Dave Andsager: The non-indented lines here are debug code to help you track down the problem in the physics
1541         //      that is causing ships to inexplicably rotate very far.  If you hit the Int3(), set the next statement to be
1542         //      the one marked "HERE".  (Do this clicking the cursor there, then right clicking.  Choose the right option.)
1543         //      This will allow you to rerun vm_forward_interpolate() with the values that caused the error.
1544         //      Note, you'll need to enable the Int3() about ten lines below.
1545 #ifndef NDEBUG
1546 vector tvec = objp->orient.v.fvec;
1547 vector  vel_in_copy;
1548 matrix  objp_orient_copy;
1549
1550 vel_in_copy = vel_in;
1551 objp_orient_copy = objp->orient;
1552
1553 vel_in = vel_in_copy;   //      HERE
1554 objp->orient = objp_orient_copy;
1555 #endif
1556         if (rvec != NULL) {
1557                 matrix  out_orient, goal_orient;
1558
1559                 vm_vector_2_matrix(&goal_orient, &desired_fvec, NULL, rvec);
1560                 vm_matrix_interpolate(&goal_orient, &curr_orient, &vel_in, delta_time, &out_orient, &vel_out, &vel_limit, &acc_limit);
1561                 objp->orient = out_orient;
1562         } else {
1563                 vm_forward_interpolate(&desired_fvec, &curr_orient, &vel_in, delta_time, delta_bank, &objp->orient, &vel_out, &vel_limit, &acc_limit);
1564         }
1565 #ifndef NDEBUG
1566 if (!((objp->type == OBJ_WEAPON) && (Weapon_info[Weapons[objp->instance].weapon_info_index].subtype == WP_MISSILE))) {
1567         if (delta_time < 0.25f && vm_vec_dot(&objp->orient.v.fvec, &tvec) < 0.1f)
1568                 Int3(); //      Get Andsager.  A ship has turned too far in one frame.
1569 }
1570 #endif
1571
1572         pip->rotvel = vel_out;
1573 }
1574
1575 void init_ship_info()
1576 {
1577         int     i;
1578
1579         if (Ship_info_inited)
1580                 return;
1581
1582         for (i=0; i<MAX_SHIP_TYPES; i++) {
1583                 Ship_info[i].min_speed = - Ship_info[i].max_rear_vel;
1584                 Ship_info[i].max_accel = Ship_info[i].max_vel.xyz.z;
1585         }
1586
1587         Ship_info_inited = 1;
1588
1589 }
1590
1591 //      Set aip->target_objnum to objnum
1592 //      Update aip->previous_target_objnum.
1593 //      If new target (objnum) is different than old target, reset target_time.
1594 int set_target_objnum(ai_info *aip, int objnum)
1595 {
1596 /*
1597         char    old_name[32], new_name[32];
1598
1599         if (!timestamp_elapsed(aip->ok_to_target_timestamp))
1600                 return aip->target_objnum;
1601
1602         if (Player_ship && (Ships[aip->shipnum].team == Player_ship->team)) {
1603                 if (aip->target_objnum == -1)
1604                         strcpy(old_name, "none");
1605                 else
1606                         strcpy(old_name, Ships[Objects[aip->target_objnum].instance].ship_name);
1607
1608                 if (objnum == -1)
1609                         strcpy(new_name, "none");
1610                 else
1611                         strcpy(new_name, Ships[Objects[objnum].instance].ship_name);
1612
1613                 nprintf(("AI", "Ship %s changing target from %s to %s\n", Ships[aip->shipnum].ship_name, old_name, new_name));
1614         }
1615 */
1616
1617         // AL 2-25-97: Ensure that a protected ship isn't being set as a target (for non-players only)
1618         /*
1619         if ( objnum >= 0 ) {
1620                 if ( !(Objects[Ships[aip->shipnum].objnum].flags & OF_PLAYER_SHIP) ) {
1621                         if ( Objects[objnum].flags & OF_PROTECTED ) {
1622                                 // AL 2-26-97: removing Int3() until issue with setting OF_PROTECTED in ai_set_attack_subsystem()
1623                                 //Int3();                                                               // this should not happen
1624                                 return aip->target_objnum;              // don't change targets
1625                         }
1626                 }
1627         }
1628         */
1629
1630         if ((aip != Player_ai) && (!timestamp_elapsed(aip->ok_to_target_timestamp))) {
1631                 return aip->target_objnum;
1632         }
1633
1634         if (aip->target_objnum == objnum) {
1635                 aip->previous_target_objnum = aip->target_objnum;
1636         } else {
1637                 aip->previous_target_objnum = aip->target_objnum;
1638
1639                 // ignore this assert if a multiplayer observer
1640                 if((Game_mode & GM_MULTIPLAYER) && (aip == Player_ai) && (Player_obj->type == OBJ_OBSERVER)){
1641                 } else {
1642                         SDL_assert(objnum != Ships[aip->shipnum].objnum);       //      make sure not targeting self
1643                 }
1644
1645                 // if stealth target, init ai_info for stealth
1646                 if ( (objnum > 0) && is_object_stealth_ship(&Objects[objnum]) ) {
1647                         init_ai_stealth_info(aip, &Objects[objnum]);
1648                 }
1649
1650                 aip->target_objnum = objnum;
1651                 aip->target_time = 0.0f;
1652                 aip->target_signature = Objects[objnum].signature;
1653                 // clear targeted subsystem
1654                 set_targeted_subsys(aip, NULL, -1);
1655         }
1656         
1657         return aip->target_objnum;
1658 }
1659
1660 int ai_select_primary_weapon(object *objp, object *other_objp, int flags);
1661
1662 //      Make new_subsys the targeted subsystem of ship *aip.
1663 ship_subsys *set_targeted_subsys(ai_info *aip, ship_subsys *new_subsys, int parent_objnum)
1664 {
1665         SDL_assert(aip != NULL);
1666
1667         aip->last_subsys_target = aip->targeted_subsys;
1668         aip->targeted_subsys = new_subsys;
1669         aip->targeted_subsys_parent = parent_objnum;
1670
1671         if ( new_subsys ) {
1672                 // Make new_subsys target
1673                 if (new_subsys->system_info->type == SUBSYSTEM_ENGINE) {
1674                         if ( aip != Player_ai ) {
1675                                 ai_select_primary_weapon(&Objects[Ships[aip->shipnum].objnum], &Objects[parent_objnum], WIF_PUNCTURE);
1676                                 ship_primary_changed(&Ships[aip->shipnum]);     // AL: maybe send multiplayer information when AI ship changes primaries
1677                         }
1678                 }
1679
1680                 if ( aip == Player_ai ) {
1681                         hud_lock_reset(0.5f);
1682                 }
1683
1684         } else {
1685                 // Cleanup any subsys path information if it exists
1686                 ai_big_subsys_path_cleanup(aip);
1687         }
1688         
1689         return aip->targeted_subsys;
1690 }                                                                                         
1691
1692 // called to init the data for single ai object.  At this point,
1693 // the ship and the object and the ai_info are are correctly
1694 // linked together. Ai_info[ai_index].shipnum is the only valid field 
1695 // in ai_info.
1696 //      This is called right when the object is parsed, so you can't assume much
1697 //      has been initialized.  For example, wings, waypoints, goals are probably
1698 //      not yet loaded. --MK, 10/8/96
1699 void ai_object_init(object * obj, int ai_index)
1700 {
1701         ai_info *aip;
1702         SDL_assert(ai_index >= 0 && ai_index < MAX_AI_INFO);
1703
1704         aip = &Ai_info[ai_index];
1705
1706         aip->type = 0;          //      0 means not in use.
1707         aip->wing = -1;         //      Member of what wing? -1 means none.
1708         aip->ai_class = Ship_info[Ships[obj->instance].ship_info_index].ai_class;
1709         aip->behavior = AIM_NONE;
1710 }
1711
1712 //      If *aip is docked, set max acceleration to A->mass/(A->mass + B->mass) where A is *aip and B is dock object
1713 void adjust_accel_for_docking(ai_info *aip)
1714 {
1715         if (aip->dock_objnum != -1) {
1716                 object  *obj2p = &Objects[aip->dock_objnum];
1717                 object  *obj1p;
1718
1719                 obj1p = &Objects[Ships[aip->shipnum].objnum];
1720
1721                 if (obj2p->signature == aip->dock_signature) {
1722                         float   ratio;
1723
1724                         ratio = obj1p->phys_info.mass / (obj1p->phys_info.mass + obj2p->phys_info.mass);
1725
1726                         // put cap on how much ship can slow down
1727 #ifdef MAKE_FS1
1728                         // FS1 can go slower, perhaps down to 0, but I'll cap it at .25 just in case
1729                         if (ratio < 0.25f) {
1730                                 ratio = 0.25f;
1731                         }
1732 #else
1733                         if (ratio < 0.8) {
1734                                 ratio = 0.8f;
1735                         }
1736 #endif
1737
1738                         if (AI_ci.forward > ratio) {
1739                                 AI_ci.forward = ratio;
1740                         }
1741                 }
1742         }
1743 }
1744
1745 // -------------------------------------------------------------------
1746 void accelerate_ship(ai_info *aip, float accel)
1747 {
1748         aip->prev_accel = accel;
1749         AI_ci.forward = accel;
1750         adjust_accel_for_docking(aip);
1751 }
1752
1753 //      --------------------------------------------------------------------------
1754 void change_acceleration(ai_info *aip, float delta_accel)
1755 {
1756         float   new_accel;
1757
1758         if (delta_accel < 0.0f) {
1759                 if (aip->prev_accel > 0.0f)
1760                         aip->prev_accel = 0.0f;
1761         } else if (aip->prev_accel < 0.0f)
1762                 aip->prev_accel = 0.0f;
1763
1764         new_accel = aip->prev_accel + delta_accel * flFrametime;
1765
1766         if (new_accel > 1.0f)
1767                 new_accel = 1.0f;
1768         else if (new_accel < -1.0f)
1769                 new_accel = -1.0f;
1770         
1771         aip->prev_accel = new_accel;
1772
1773         AI_ci.forward = new_accel;
1774         adjust_accel_for_docking(aip);
1775 }
1776
1777 void set_accel_for_target_speed(object *objp, float tspeed)
1778 {
1779         float   max_speed;
1780         ai_info *aip;
1781
1782         aip = &Ai_info[Ships[objp->instance].ai_index];
1783
1784         max_speed = Ships[objp->instance].current_max_speed;
1785
1786         AI_ci.forward = tspeed/max_speed;
1787         aip->prev_accel = AI_ci.forward;
1788
1789         adjust_accel_for_docking(aip);
1790 }
1791
1792 //      Stuff perim_point with a point on the perimeter of the sphere defined by object *objp
1793 //      on the vector from the center of *objp through the point *vp.
1794 void project_point_to_perimeter(vector *perim_point, vector *pos, float radius, vector *vp)
1795 {
1796         vector  v1;
1797         float           mag;
1798
1799         vm_vec_sub(&v1, vp, pos);
1800         mag = vm_vec_mag(&v1);
1801
1802         if (mag == 0.0f) {
1803                 Warning(LOCATION, "projectable point is at center of sphere.");
1804                 (void) vm_vec_make(&v1, 0.0f, radius, 0.0f);
1805         } else {
1806                 vm_vec_normalize(&v1);
1807                 vm_vec_scale(&v1, 1.1f * radius + 10.0f);
1808         }
1809
1810         vm_vec_add2(&v1, pos);
1811         *perim_point = v1;
1812 }
1813
1814 //      Stuff tan1 with tangent point on sphere.  tan1 is point nearer to *p1
1815 //      *p0 is point through which tangents pass.
1816 //      *centerp is center of sphere.
1817 //      *p1 is another point in space to define the plane in which tan1, tan2 reside.
1818 //      radius is the radius of the sphere.
1819 //      Note, this is a very approximate function just for AI.
1820 //      Note also: On 12/26/96, p1 is used to define the plane perpendicular to that which
1821 //      contains the tangent point.
1822 void get_tangent_point(vector *tan1, vector *p0, vector *centerp, vector *p1, float radius)
1823 {
1824         vector  dest_vec, v2c, perp_vec, temp_vec, v2;
1825         float           dist, ratio;
1826
1827         //      Detect condition of point inside sphere.
1828         if (vm_vec_dist(p0, centerp) < radius)
1829                 project_point_to_perimeter(tan1, centerp, radius, p0);
1830         else {
1831                 vm_vec_normalized_dir(&v2c, centerp, p0);
1832
1833                 //      Compute perpendicular vector using p0, centerp, p1
1834                 vm_vec_normal(&temp_vec, p0, centerp, p1);
1835                 vm_vec_sub(&v2, centerp, p0);
1836                 vm_vec_cross(&perp_vec, &temp_vec, &v2);
1837
1838                 vm_vec_normalize(&perp_vec);
1839
1840                 dist = vm_vec_dist_quick(p0, centerp);
1841                 ratio = dist / radius;
1842
1843                 if (ratio < 2.0f)
1844                         vm_vec_scale_add(&dest_vec, &perp_vec, &v2c, ratio-1.0f);
1845                 else
1846                         vm_vec_scale_add(&dest_vec, &v2c, &perp_vec, (1.0f + 1.0f/ratio));
1847
1848                 vm_vec_scale_add(tan1, p0, &dest_vec, dist + radius);
1849         }
1850 }
1851
1852 //      --------------------------------------------------------------------------
1853 //      Given an object and a point, turn towards the point, resulting in
1854 // approach behavior.
1855 void turn_towards_point(object *objp, vector *point, vector *slide_vec, float bank_override)
1856 {
1857         ai_info *aip;
1858         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
1859         
1860         // check if in formation and if not leader, don't change rotvel.xyz.z (bank to match leader elsewhere)
1861         if (aip->ai_flags & AIF_FORMATION) {
1862                 if (&Objects[aip->goal_objnum] != objp) {
1863                         float rotvel_z = objp->phys_info.rotvel.xyz.z;
1864                         ai_turn_towards_vector(point, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, slide_vec, NULL, bank_override, 0);
1865                         objp->phys_info.rotvel.xyz.z = rotvel_z;
1866                 }
1867         } else {
1868                 // normal turn
1869                 ai_turn_towards_vector(point, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, slide_vec, NULL, bank_override, 0);
1870         }
1871 }
1872
1873 //      --------------------------------------------------------------------------
1874 //      Given an object and a point, turn away from the point, resulting in avoidance behavior.
1875 //      Note: Turn away at full speed, not scaled down by skill level.
1876 void turn_away_from_point(object *objp, vector *point, float bank_override)
1877 {
1878         vector  opposite_point;
1879
1880         vm_vec_sub(&opposite_point, &objp->pos, point);
1881         vm_vec_add2(&opposite_point, &objp->pos);
1882
1883         ai_turn_towards_vector(&opposite_point, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, NULL, NULL, bank_override, AITTV_FAST);
1884 }
1885
1886
1887 //      --------------------------------------------------------------------------
1888 //      Given an object and a point, turn tangent to the point, resulting in
1889 // a circling behavior.
1890 //      Make object *objp turn around the point *point with a radius of radius.
1891 //      Note that this isn't the same as following a circle of radius radius with
1892 //      center *point, but it should be adequate.
1893 //      Note that if you want to circle an object without hitting it, you should use
1894 //      about twice that object's radius for radius, else you'll certainly bump into it.
1895 //      Return dot product to goal point.
1896 float turn_towards_tangent(object *objp, vector *point, float radius)
1897 {
1898         vector  vec_to_point;
1899         vector  goal_point;
1900         vector  perp_point;                             //      point radius away from *point on vector to objp->pos
1901         vector  up_vec, perp_vec;
1902
1903         vm_vec_normalized_dir(&vec_to_point, point, &objp->pos);
1904         vm_vec_crossprod(&up_vec, &vec_to_point, &objp->orient.v.fvec);
1905         vm_vec_crossprod(&perp_vec, &vec_to_point, &up_vec);
1906
1907         vm_vec_scale_add(&perp_point, point, &vec_to_point, -radius);
1908         if (vm_vec_dot(&objp->orient.v.fvec, &perp_vec) > 0.0f) {
1909                 vm_vec_scale_add(&goal_point, &perp_point, &perp_vec, radius);
1910         } else {
1911                 vm_vec_scale_add(&goal_point, &perp_point, &perp_vec, -radius);
1912         }
1913
1914 //      Ai_info[Ships[objp->instance].ai_index].goal_point = goal_point;
1915         turn_towards_point(objp, &goal_point, NULL, 0.0f);
1916
1917         vector  v2g;
1918
1919         vm_vec_normalized_dir(&v2g, &goal_point, &objp->pos);
1920         return vm_vec_dot(&objp->orient.v.fvec, &v2g);
1921 }
1922
1923 float turn_toward_tangent_with_axis(object *objp, object *center_objp, float radius)
1924 {
1925         vector r_vec, theta_vec;
1926         vector center_vec, vec_on_cylinder, sph_r_vec;
1927         float center_obj_z;
1928
1929         // find closest z of center objp
1930         vm_vec_sub(&sph_r_vec, &objp->pos, &center_objp->pos);
1931         center_obj_z = vm_vec_dotprod(&sph_r_vec, &center_objp->orient.v.fvec);
1932
1933         // find pt on axis with closest z
1934         vm_vec_scale_add(&center_vec, &center_objp->pos, &center_objp->orient.v.fvec, center_obj_z);
1935
1936         // get r_vec
1937         vm_vec_sub(&r_vec, &objp->pos, &center_vec);
1938 //      float r_mag = vm_vec_normalize_quick(&r_vec);
1939 //      mprintf(("cur_r: %.1f, desired_r: %.1f\n", r_mag, radius));
1940         SDL_assert( (vm_vec_dotprod(&r_vec, &center_objp->orient.v.fvec) < 0.0001));
1941
1942         // get theta vec - perp to r_vec and z_vec
1943         vm_vec_crossprod(&theta_vec, &center_objp->orient.v.fvec, &r_vec);
1944
1945 #ifndef NDEBUG
1946         float mag = vm_vec_normalize(&theta_vec);
1947         SDL_assert(mag > 0.9999 && mag < 1.0001);
1948 #endif
1949
1950         vector temp;
1951         vm_vec_crossprod(&temp, &r_vec, &theta_vec);
1952
1953 #ifndef NDEBUG
1954         float dot = vm_vec_dotprod(&temp, &center_objp->orient.v.fvec);
1955         SDL_assert( dot >0.9999 && dot < 1.0001);
1956 #endif
1957
1958         // find pt on clylinder with closest z
1959         vm_vec_scale_add(&vec_on_cylinder, &center_vec, &r_vec, radius);
1960
1961         vector goal_pt, v2g;
1962         vm_vec_scale_add(&goal_pt, &vec_on_cylinder, &theta_vec, radius);
1963
1964 //      Ai_info[Ships[objp->instance].ai_index].goal_point = goal_pt;
1965         turn_towards_point(objp, &goal_pt, NULL, 0.0f);
1966
1967         vm_vec_normalized_dir(&v2g, &goal_pt, &objp->pos);
1968         return vm_vec_dot(&objp->orient.v.fvec, &v2g);
1969 }
1970
1971 //      Returns a point radius units away from *point that *objp should turn towards to orbit *point
1972 void get_tangent_point(vector *goal_point, object *objp, vector *point, float radius)
1973 {
1974         vector  vec_to_point;
1975         vector  perp_point;                             //      point radius away from *point on vector to objp->pos
1976         vector  up_vec, perp_vec;
1977
1978         vm_vec_normalized_dir(&vec_to_point, point, &objp->pos);
1979         vm_vec_crossprod(&up_vec, &vec_to_point, &objp->orient.v.fvec);
1980         vm_vec_crossprod(&perp_vec, &vec_to_point, &up_vec);
1981         vm_vec_normalize(&perp_vec);
1982
1983         vm_vec_scale_add(&perp_point, point, &vec_to_point, -radius);
1984
1985         if (vm_vec_dot(&objp->orient.v.fvec, &perp_vec) > 0.0f) {
1986                 vm_vec_scale_add(goal_point, &perp_point, &perp_vec, radius);
1987         } else {
1988                 vm_vec_scale_add(goal_point, &perp_point, &perp_vec, -radius);
1989         }
1990 }
1991
1992 int     Player_attacking_enabled = 1;
1993
1994 // -----------------------------------------------------------------------------
1995 // Determine whether an object is targetable within a nebula
1996 int object_is_targetable(object *target, ship *viewer)
1997 {
1998         int stealth_ship = 0;
1999
2000         // if target is ship, check if visible by team
2001         if (target->type == OBJ_SHIP) {
2002                 stealth_ship = (Ship_info[Ships[target->instance].ship_info_index].flags & SIF_STEALTH);
2003                 if ( ship_is_visible_by_team(target->instance, viewer->team) == 1) {
2004                         return 1;
2005                 }
2006         }
2007
2008         // for AI partially targetable works as fully targetable, except for stealth ship
2009         if (stealth_ship) {
2010                 // if not team targetable, check if within frustrum
2011                 if ( ai_is_stealth_visible(&Objects[viewer->objnum], target) == STEALTH_VISIBLE ) {
2012                         return 1;
2013                 } else {
2014                         return 0;
2015                 }
2016         }
2017
2018         // if not fully targetable by team, check awacs level with viewer
2019         // allow targeting even if only only partially targetable to player
2020         float radar_return = awacs_get_level(target, viewer);
2021         if ( radar_return > 0.4 ) {
2022                 return 1;
2023         } else {
2024                 return 0;
2025         }
2026 }
2027
2028 //      Return number of enemies attacking object objnum
2029 //
2030 // AL 10.26.97: Also include turrets on large ships when couting enemies attacking
2031 int num_enemies_attacking(int objnum)
2032 {
2033         object          *objp;
2034         ship                    *sp;
2035         ship_subsys     *ssp;
2036         ship_obj                *so;
2037         int                     count;
2038
2039         count = 0;
2040
2041         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2042                 objp = &Objects[so->objnum];
2043                 SDL_assert(objp->instance != -1);
2044                 sp = &Ships[objp->instance];
2045
2046                 if (Ai_info[sp->ai_index].target_objnum == objnum)
2047                         count++;
2048
2049                 // consider turrets that may be attacking objnum (but only turrets on SIF_BIG_SHIP ships)
2050                 if ( Ship_info[sp->ship_info_index].flags & SIF_BIG_SHIP ) {
2051
2052                         // loop through all the subsystems, check if turret has objnum as a target
2053                         ssp = GET_FIRST(&sp->subsys_list);
2054                         while ( ssp != END_OF_LIST( &sp->subsys_list ) ) {
2055
2056                                 if ( ssp->system_info->type == SUBSYSTEM_TURRET ) {
2057                                         if ( (ssp->turret_enemy_objnum == objnum) && (ssp->current_hits > 0) ) {
2058                                                 count++;
2059                                         }
2060                                 }
2061                                 ssp = GET_NEXT( ssp );
2062                         } // end while
2063                 }
2064         }
2065
2066         return count;
2067 }
2068
2069 //      Get the team to fire on given an object.
2070 int get_enemy_team_mask(int objnum)
2071 {
2072         int     my_team, enemy_team_mask;
2073
2074         my_team = Ships[Objects[objnum].instance].team;
2075
2076         if (Mission_all_attack) {
2077                 //      All teams attack all teams.
2078                 switch (my_team) {
2079                 case TEAM_FRIENDLY:
2080                         enemy_team_mask = TEAM_HOSTILE | TEAM_NEUTRAL | TEAM_TRAITOR;
2081                         break;
2082                 case TEAM_HOSTILE:
2083                         enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_TRAITOR;
2084                         break;
2085                 case TEAM_NEUTRAL:
2086                         enemy_team_mask = TEAM_FRIENDLY | TEAM_HOSTILE | TEAM_TRAITOR;
2087                         break;
2088                 case TEAM_UNKNOWN:
2089                         enemy_team_mask = TEAM_HOSTILE;
2090                         break;
2091                 case TEAM_TRAITOR:
2092                         enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_HOSTILE | TEAM_TRAITOR;
2093                         break;
2094                 default:
2095                         enemy_team_mask = TEAM_HOSTILE;
2096                         Int3();                 //      Illegal value for team!
2097                         break;
2098                 }
2099         } else {
2100                 switch (my_team) {
2101                 case TEAM_FRIENDLY:
2102                         enemy_team_mask = TEAM_HOSTILE | TEAM_NEUTRAL | TEAM_TRAITOR;
2103                         break;
2104                 case TEAM_HOSTILE:
2105                         enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_TRAITOR;
2106                         break;
2107                 case TEAM_NEUTRAL:
2108                         enemy_team_mask = TEAM_FRIENDLY | TEAM_TRAITOR;
2109                         break;
2110                 case TEAM_UNKNOWN:
2111                         enemy_team_mask = TEAM_HOSTILE;
2112                         break;
2113                 case TEAM_TRAITOR:
2114                         enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_HOSTILE | TEAM_TRAITOR;
2115                         break;
2116                 default:
2117                         enemy_team_mask = TEAM_HOSTILE;
2118                         Int3();                 //      Illegal value for team!
2119                         break;
2120                 }
2121         }
2122
2123         return enemy_team_mask;
2124 }
2125
2126 //      Scan all the ships in *objp's wing.
2127 //      Return the lowest maximum speed of a ship in the wing.
2128 //      Current maximum speed (based on energy settings) is shipp->current_max_speed
2129 float get_wing_lowest_max_speed(object *objp)
2130 {
2131         ship            *shipp;
2132         ai_info *aip;
2133         float           lowest_max_speed;
2134         int             wingnum;
2135         object  *o;
2136         ship_obj        *so;
2137
2138         SDL_assert(objp->type == OBJ_SHIP);
2139         SDL_assert((objp->instance >= 0) && (objp->instance < MAX_OBJECTS));
2140         shipp = &Ships[objp->instance];
2141         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
2142         aip = &Ai_info[shipp->ai_index];
2143
2144         wingnum = aip->wing;
2145
2146         lowest_max_speed = shipp->current_max_speed;
2147
2148         if ( wingnum == -1 )
2149                 return lowest_max_speed;
2150
2151         SDL_assert(wingnum >= 0);
2152
2153         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2154                 o = &Objects[so->objnum];
2155                 ship    *oshipp = &Ships[o->instance];
2156                 ai_info *oaip = &Ai_info[oshipp->ai_index];
2157
2158                 if ((oaip->mode == AIM_WAYPOINTS) && (oaip->wing == wingnum)) {
2159                         //      Note: If a ship in the wing has a super low max speed, probably its engines are disabled.  So, fly along and
2160                         //      ignore the poor guy.
2161                         float   cur_max = oshipp->current_max_speed;
2162
2163                         if (oaip->ai_flags & AIF_DOCKED) {
2164                                 if (oaip->dock_objnum > -1)
2165                                         if (Objects[oaip->dock_objnum].type == OBJ_SHIP) 
2166                                                 cur_max *= o->phys_info.mass/(o->phys_info.mass + Objects[oaip->dock_objnum].phys_info.mass);
2167                         }
2168                                                         
2169                         if ((oshipp->current_max_speed > 5.0f) && (cur_max < lowest_max_speed)) {
2170                                 lowest_max_speed = cur_max;
2171                         }
2172                 }
2173         }
2174
2175         return lowest_max_speed;
2176 }
2177
2178 /*
2179 //      Tell everyone to ignore object objnum.
2180 void set_global_ignore_object(int objnum)
2181 {
2182         int     i;
2183
2184         SDL_assert(Objects[objnum].type == OBJ_SHIP);
2185
2186         nprintf(("AI", "Telling everyone to ignore object %s\n", Ships[Objects[objnum].instance].ship_name));
2187
2188         for (i=0; i<MAX_IGNORE_OBJECTS; i++) {
2189                 if (Ignore_objects[i].objnum == -1) {
2190                         Ignore_objects[i].objnum = objnum;
2191                         Ignore_objects[i].signature = Objects[objnum].signature;
2192                         break;
2193                 }
2194         }
2195
2196         if (i == MAX_IGNORE_OBJECTS) {
2197                 //      Couldn't find a free slot, but maybe one of these objects has died.
2198                 for (i=0; i<MAX_IGNORE_OBJECTS; i++) {
2199                         int     o = Ignore_objects[i].objnum;
2200                         if (Objects[o].type != OBJ_SHIP)
2201                                 break;          //      Not a ship, so use this slot.
2202                         if (Objects[o].signature != Ignore_objects[i].signature)
2203                                 break;          //      Signatures don't match, so use this slot.
2204                 }
2205
2206                 if (i != MAX_IGNORE_OBJECTS) {
2207                         Ignore_objects[i].objnum = objnum;
2208                         Ignore_objects[i].signature = Objects[objnum].signature;
2209                 } else {
2210                         nprintf(("Warning", "Ignore_objects buffer full.  Stealing a slot to ignore object #%i\n"));
2211                         Int3();
2212
2213                         int     r;
2214
2215                         r = objnum % MAX_IGNORE_OBJECTS;
2216
2217                         Ignore_objects[r].objnum = objnum;
2218                         Ignore_objects[r].signature = Objects[objnum].signature;
2219                 }
2220         }
2221 }
2222
2223 */
2224
2225 //      Determine if object objnum is supposed to be ignored by object with ai_info *aip.
2226 //      Return:
2227 //              TRUE    if objnum is aip->ignore_objnum (and signatures match)
2228 //                              or objnum is in ignore wing
2229 //              FALSE   otherwise
2230 int is_ignore_object(ai_info *aip, int objnum)
2231 {
2232
2233 /*      //      First, scan all objects in global array of objects to be ignored.
2234         for (int i=0; i<MAX_IGNORE_OBJECTS; i++)
2235                 if (Ignore_objects[i].objnum != -1)
2236                         if (objnum == Ignore_objects[i].objnum)
2237                                 if (Objects[Ignore_objects[i].objnum].signature == Ignore_objects[i].signature)
2238                                         return 1;
2239 */
2240
2241         //      Didn't find in global list.  Now check 
2242         if (aip->ignore_objnum == UNUSED_OBJNUM)
2243                 return 0;                                                                       //      Not ignoring anything.
2244         else if (aip->ignore_objnum >= 0) {             //      This means it's ignoring an object, not a wing.
2245                 if (aip->ignore_objnum == objnum) {
2246                         if (Objects[aip->ignore_objnum].signature == aip->ignore_signature) {
2247                                 return 1;
2248                         } else {
2249                                 aip->ignore_objnum = UNUSED_OBJNUM;
2250                                 return 0;
2251                         }
2252                 } else {
2253                         return 0;
2254                 }
2255         } else {                                                                                        //      Ignoring a wing.
2256                 Int3(); // Should never happen.  I thought I removed this behavior! -- MK, 5/17/98
2257                 return 0;
2258 /*              int     ignore_wingnum = -(aip->ignore_objnum + 1);
2259
2260                 SDL_assert(ignore_wingnum < MAX_WINGS);
2261                 SDL_assert(aip->shipnum >= 0);
2262                 return (Ships[Objects[objnum].instance].wingnum == ignore_wingnum);
2263 */      }
2264 }
2265
2266 // -----------------------------------------------------------------------------
2267
2268 // given a ship with bounding box and a point, find the closest point on the bbox
2269 int get_nearest_bbox_point(object *ship_obj, vector *start, vector *box_pt)
2270 {
2271         vector temp, rf_start;
2272         polymodel *pm;
2273         pm = model_get(Ship_info[Ships[ship_obj->instance].ship_info_index].modelnum);
2274
2275         // get start in ship rf
2276         vm_vec_sub(&temp, start, &ship_obj->pos);
2277         vm_vec_rotate(&rf_start, &temp, &ship_obj->orient);
2278
2279         // find box_pt
2280         int inside = project_point_onto_bbox(&pm->mins, &pm->maxs, &rf_start, &temp);
2281
2282         // get box_pt in world rf
2283         vm_vec_unrotate(box_pt, &temp, &ship_obj->orient);
2284         vm_vec_add2(box_pt, &ship_obj->pos);
2285
2286         return inside;
2287 }
2288
2289
2290 typedef struct eval_nearest_objnum {
2291         int     objnum;
2292         object *trial_objp;
2293         int     enemy_team_mask;
2294         int     enemy_wing;
2295         float   range;
2296         int     max_attackers;
2297         int     nearest_objnum;
2298         float   nearest_dist;
2299         int     check_danger_weapon_objnum;
2300 } eval_nearest_objnum;
2301
2302
2303 void evaluate_object_as_nearest_objnum(eval_nearest_objnum *eno)
2304 {
2305         ai_info *aip;
2306         ship_subsys     *attacking_subsystem;
2307
2308         aip = &Ai_info[Ships[Objects[eno->objnum].instance].ai_index];
2309
2310         attacking_subsystem = aip->targeted_subsys;
2311
2312         if ((attacking_subsystem != NULL) || !(eno->trial_objp->flags & OF_PROTECTED)) {
2313                 if ( OBJ_INDEX(eno->trial_objp) != eno->objnum ) {
2314 #ifndef NDEBUG
2315                         if (!Player_attacking_enabled && (eno->trial_objp == Player_obj))
2316                                 return;
2317 #endif
2318                         //      If only supposed to attack ship in a specific wing, don't attack other ships.
2319                         if ((eno->enemy_wing != -1) && (Ships[eno->trial_objp->instance].wingnum != eno->enemy_wing))
2320                                 return;
2321
2322                         //      Don't keep firing at a ship that is in its death throes.
2323                         if (Ships[eno->trial_objp->instance].flags & SF_DYING)
2324                                 return;
2325
2326                         if (is_ignore_object(aip, ((eno->trial_objp)-Objects)))
2327                                 return;
2328
2329                         if (eno->trial_objp->flags & OF_PROTECTED)
2330                                 return;
2331
2332                         if (Ships[eno->trial_objp->instance].flags & SF_ARRIVING)
2333                                 return;
2334
2335                         ship_info *sip = &Ship_info[Ships[eno->trial_objp->instance].ship_info_index];
2336
2337                         if (sip->flags & (SIF_NO_SHIP_TYPE | SIF_NAVBUOY))
2338                                 return;
2339
2340                         if (Ships[eno->trial_objp->instance].team & eno->enemy_team_mask) {
2341                                 float   dist;
2342                                 int     num_attacking;
2343
2344                                 // Allow targeting of stealth in nebula by his firing at me
2345                                 // This is done for a specific ship, not generally.
2346                                 if ( !eno->check_danger_weapon_objnum ) {
2347                                         // check if can be targeted if inside nebula
2348                                         if ( !object_is_targetable(eno->trial_objp, &Ships[Objects[eno->objnum].instance]) ) {
2349                                                 // check if stealth ship is visible, but not "targetable"
2350                                                 if ( !((sip->flags & SIF_STEALTH) && ai_is_stealth_visible(&Objects[eno->objnum], eno->trial_objp)) ) {
2351                                                         return;
2352                                                 }
2353                                         }
2354                                 }
2355
2356                                 // if objnum is BIG or HUGE, find distance to bbox
2357                                 if (sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
2358                                         vector box_pt;
2359                                         // check if inside bbox
2360                                         int inside = get_nearest_bbox_point(eno->trial_objp, &Objects[eno->objnum].pos, &box_pt);
2361                                         if (inside) {
2362                                                 dist = 10.0f;
2363                                                 // on the box
2364                                         } else {
2365                                                 dist = vm_vec_dist_quick(&Objects[eno->objnum].pos, &box_pt);
2366                                         }
2367                                 } else {
2368                                         dist = vm_vec_dist_quick(&Objects[eno->objnum].pos, &eno->trial_objp->pos);
2369                                 }
2370                                 
2371                                 //      Make it more likely that fighters (or bombers) will be picked as an enemy by scaling up distance for other types.
2372                                 if ((Ship_info[Ships[eno->trial_objp->instance].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER))) {
2373                                         dist = dist * 0.5f;
2374                                 }
2375
2376                                 num_attacking = num_enemies_attacking(eno->trial_objp-Objects);
2377                                 if ((sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) || (num_attacking < eno->max_attackers)) {
2378                                         if (!(sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))){
2379                                                 dist *= (float) (num_attacking+2)/2.0f;                         //      prevents lots of ships from attacking same target
2380                                         }
2381
2382                                         if (eno->trial_objp->flags & OF_PLAYER_SHIP){
2383                                                 dist *= 1.0f + (NUM_SKILL_LEVELS - Game_skill_level - 1)/NUM_SKILL_LEVELS;      //      Favor attacking non-players based on skill level.
2384                                         }
2385
2386                                         if (dist < eno->nearest_dist) {
2387                                                 eno->nearest_dist = dist;
2388                                                 eno->nearest_objnum = eno->trial_objp-Objects;
2389                                         }
2390                                 }
2391                         }
2392                 }
2393         }
2394
2395 }
2396
2397
2398 //      Given an object and an enemy team, return the index of the nearest enemy object.
2399 //      Unless aip->targeted_subsys != NULL, don't allow to attack objects
2400 //      with OF_PROTECTED bit set.
2401 //      Ship must be within range "range".
2402 //      Don't attack a ship that already has at least max_attackers attacking it.
2403 int get_nearest_objnum(int objnum, int enemy_team_mask, int enemy_wing, float range, int max_attackers)
2404 {
2405         object  *danger_weapon_objp;
2406         ai_info *aip;
2407         ship_obj        *so;
2408
2409         // initialize eno struct
2410         eval_nearest_objnum eno;
2411         eno.enemy_team_mask = enemy_team_mask;
2412         eno.enemy_wing = enemy_wing;
2413         eno.max_attackers = max_attackers;
2414         eno.objnum = objnum;
2415         eno.range = range;
2416         eno.nearest_dist = range;
2417         eno.nearest_objnum = -1;
2418         eno.check_danger_weapon_objnum = 0;
2419
2420         // go through the list of all ships and evaluate as potential targets
2421         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2422                 eno.trial_objp = &Objects[so->objnum];
2423                 evaluate_object_as_nearest_objnum(&eno);
2424
2425         }
2426
2427         // check if danger_weapon_objnum has will show a stealth ship
2428         aip = &Ai_info[Ships[Objects[objnum].instance].ai_index];
2429         if (aip->danger_weapon_objnum >= 0) {
2430                 danger_weapon_objp = &Objects[aip->danger_weapon_objnum];
2431                 // validate weapon
2432                 if (danger_weapon_objp->signature == aip->danger_weapon_signature) {
2433                         SDL_assert(danger_weapon_objp->type == OBJ_WEAPON);
2434                         // check if parent is a ship
2435                         if (danger_weapon_objp->parent >= 0) {
2436                                 if ( is_object_stealth_ship(&Objects[danger_weapon_objp->parent]) ) {
2437                                         // check if stealthy
2438                                         if ( ai_is_stealth_visible(&Objects[objnum], &Objects[danger_weapon_objp->parent]) != STEALTH_FULLY_TARGETABLE ) {
2439                                                 // check if weapon is laser
2440                                                 if (Weapon_info[Weapons[danger_weapon_objp->instance].weapon_info_index].subtype == WP_LASER) {
2441                                                         // check stealth ship by its laser fire
2442                                                         eno.check_danger_weapon_objnum = 1;
2443                                                         eno.trial_objp = &Objects[danger_weapon_objp->parent];
2444                                                         evaluate_object_as_nearest_objnum(&eno);
2445                                                 }
2446                                         }
2447                                 }
2448                         }
2449                 }
2450         }
2451
2452         //      If only looking for target in certain wing and couldn't find anything in
2453         //      that wing, look for any object.
2454         if ((eno.nearest_objnum == -1) && (enemy_wing != -1)) {
2455                 return get_nearest_objnum(objnum, enemy_team_mask, -1, range, max_attackers);
2456         }
2457
2458         return eno.nearest_objnum;
2459 }
2460
2461 //      Given an object and an enemy team, return the index of the nearest enemy object.
2462 //      Unlike find_enemy or find_nearest_objnum, this doesn't care about things like the protected flag or number
2463 //      of enemies attacking.
2464 //      It is used to find the nearest enemy to determine things like whether to rearm.
2465 int find_nearby_hostile(int objnum, int enemy_team_mask, float range, int *count)
2466 {
2467         int             nearest_objnum;
2468         float           nearest_dist;
2469         object  *objp;
2470         ship_obj        *so;
2471
2472         nearest_objnum = -1;
2473         nearest_dist = range;
2474
2475         *count = 0;
2476
2477         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2478                 objp = &Objects[so->objnum];
2479
2480                 if ( OBJ_INDEX(objp) != objnum ) {
2481                         if (Ships[objp->instance].flags & SF_DYING)
2482                                 continue;
2483
2484                         if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_NO_SHIP_TYPE | SIF_NAVBUOY))
2485                                 continue;
2486
2487                         if (Ships[objp->instance].team & enemy_team_mask) {
2488                                 float   dist;
2489
2490                                 dist = vm_vec_dist_quick(&Objects[objnum].pos, &objp->pos) - objp->radius*0.75f;
2491                                 
2492                                 if (dist < range) {
2493                                         (*count)++;
2494
2495                                         if (dist < nearest_dist) {
2496                                                 nearest_dist = dist;
2497                                                 nearest_objnum = objp-Objects;
2498                                         }
2499                                 }
2500                         }
2501                 }
2502         }
2503
2504         return nearest_objnum;
2505 }
2506
2507 // return !0 if objp can be considered for a turret target, 0 otherwise
2508 // input:       objp                            =>      object that turret is considering as an enemy
2509 //                              turret_parent   =>      object index for ship that turret sits on
2510 int valid_turret_enemy(object *objp, object *turret_parent)
2511 {
2512         if ( objp == turret_parent ) {
2513                 return 0;
2514         }
2515
2516         if ( objp->type == OBJ_ASTEROID ) {
2517                 return 1;
2518         }
2519
2520         if ( objp->type == OBJ_SHIP ) {
2521                 ship *shipp;
2522                 shipp = &Ships[objp->instance];
2523
2524                 // don't fire at ships with protected bit set!!!
2525                 if ( objp->flags & OF_PROTECTED ) {
2526                         return 0;
2527                 }
2528
2529                 if ( !(Ship_info[shipp->ship_info_index].flags & SIF_DO_COLLISION_CHECK)) {
2530                         return 0;
2531                 }
2532
2533                 if (shipp->flags & SF_ARRIVING) {
2534                         return 0;
2535                 }
2536
2537                 return 1;
2538         }
2539
2540         if ( objp->type == OBJ_WEAPON ) {
2541                 if ( Weapon_info[Weapons[objp->instance].weapon_info_index].wi_flags & WIF_BOMB ) {
2542                         if ( obj_team(turret_parent) != Weapons[objp->instance].team ) {
2543                                 return 1;
2544                         }
2545                 }
2546         }
2547
2548         return 0;
2549 }
2550
2551 // return 1 if objp is in fov of the specified turret, tp.  Otherwise return 0.
2552 //      dist = distance from turret to center point of object
2553 int object_in_turret_fov(object *objp, model_subsystem *tp, vector *tvec, vector *tpos, float dist)
2554 {
2555         vector  v2e;
2556         float           dot;
2557         vm_vec_normalized_dir(&v2e, &objp->pos, tpos);
2558         dot = vm_vec_dot(&v2e, tvec);
2559
2560         dot += objp->radius / (dist + objp->radius);
2561
2562         if ( dot >= tp->turret_fov ) {
2563                 return 1;
2564         }
2565
2566         return 0;
2567 }
2568
2569 // return 1 if bomb_objp is headed towards ship_objp
2570 int bomb_headed_towards_ship(object *bomb_objp, object *ship_objp)
2571 {
2572         float           dot;
2573         vector  bomb_to_ship_vector;
2574
2575         vm_vec_normalized_dir(&bomb_to_ship_vector, &ship_objp->pos, &bomb_objp->pos);
2576         dot = vm_vec_dot(&bomb_objp->orient.v.fvec, &bomb_to_ship_vector);
2577
2578         if ( dot > 0 ) {
2579                 return 1;
2580         }
2581
2582         return 0;
2583 }
2584
2585 // nubmer of live turrets with target_objnum 
2586 int num_turrets_attacking(object *turret_parent, int target_objnum) 
2587 {
2588         ship_subsys *ss;
2589         ship *shipp;
2590         int count = 0;
2591         shipp = &Ships[turret_parent->instance];
2592
2593         SDL_assert(turret_parent->type == OBJ_SHIP);
2594         SDL_assert(Objects[target_objnum].type == OBJ_SHIP);
2595
2596         for (ss=GET_FIRST(&shipp->subsys_list); ss!=END_OF_LIST(&shipp->subsys_list); ss=GET_NEXT(ss)) {
2597                 // check if subsys is alive
2598                 if (ss->current_hits <= 0.0f) {
2599                         continue;
2600                 }
2601
2602                 // check if it's a turret
2603                 if (ss->system_info->type != SUBSYSTEM_TURRET) {
2604                         continue;
2605                 }
2606
2607                 // if the turret is locked
2608                 if(ss->weapons.flags & SW_FLAG_TURRET_LOCK){
2609                         continue;
2610                 }               
2611
2612                 // check if turret is targeting target_objnum
2613                 if (ss->turret_enemy_objnum == target_objnum) {
2614                         count++;
2615                 }
2616         }
2617
2618         return count;
2619 }
2620
2621 float Lethality_range_const = 2.0f;
2622 DCF(lethality_range, "N for modifying range: 1 / (1+N) at 100")
2623 {
2624         dc_get_arg(ARG_FLOAT);
2625         Lethality_range_const = Dc_arg_float;
2626 }
2627
2628 float Player_lethality_bump[NUM_SKILL_LEVELS] = {
2629         // 0.0f, 5.0f, 10.0f, 25.0f, 40.0f
2630         0.0f, 0.0f, 0.0f, 0.0f, 0.0f
2631 };
2632
2633 // evaluate obj as posssible target for turret
2634 void evaluate_obj_as_target(object *objp, eval_enemy_obj_struct *eeo)
2635 {
2636         object  *turret_parent_obj = &Objects[eeo->turret_parent_objnum];
2637         ship            *shipp;
2638         model_subsystem *tp = eeo->turret_subsys->system_info;
2639         float dist;
2640
2641         // Don't look for bombs when weapon system is not ok
2642         if (objp->type == OBJ_WEAPON && !eeo->weapon_system_ok) {
2643                 return;
2644         }
2645
2646         if ( !valid_turret_enemy(objp, turret_parent_obj) ) {
2647                 return;
2648         }
2649
2650 #ifndef NDEBUG
2651         if (!Player_attacking_enabled && (objp == Player_obj)) {
2652                 return;
2653         }
2654 #endif
2655
2656         if ( objp->type == OBJ_SHIP ) {
2657                 shipp = &Ships[objp->instance];
2658
2659                 // check on enemy team
2660                 if ( !(shipp->team & eeo->enemy_team_mask) ) {
2661                         return;
2662                 }
2663
2664                 // check if protected
2665                 if (objp->flags & OF_PROTECTED) {
2666                         return;
2667                 }
2668
2669                 // check if beam protected
2670                 if (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM) {
2671                         if (objp->flags & OF_BEAM_PROTECTED) {
2672                                 return;
2673                         }
2674                 }
2675
2676                 if (eeo->big_only_flag) {
2677                         if (!(Ship_info[shipp->ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
2678                                 return;
2679                         }
2680                 }
2681
2682                 // check if     turret flagged to only target tagged ships
2683                 if ( (eeo->turret_subsys->weapons.flags & SW_FLAG_TAGGED_ONLY) && !ship_is_tagged(objp) ) {
2684                         return;
2685                 }
2686
2687                 // check if valid target in nebula
2688                 if ( !object_is_targetable(objp, &Ships[Objects[eeo->turret_parent_objnum].instance]) ) {
2689                         // BYPASS ocassionally for stealth
2690                         int try_anyway = FALSE;
2691                         if ( is_object_stealth_ship(objp) ) {
2692                                 float turret_stealth_find_chance = 0.5f;
2693                                 float speed_mod = -0.1f + vm_vec_mag_quick(&objp->phys_info.vel) / 70.0f;
2694                                 if (frand() > (turret_stealth_find_chance + speed_mod)) {
2695                                         try_anyway = TRUE;
2696                                 }
2697                         }
2698
2699                         if (!try_anyway) {
2700                                 return;
2701                         }
2702                 }
2703
2704         } else {
2705                 shipp = NULL;
2706         }
2707
2708         // modify dist for BIG|HUGE, getting closest point on bbox, if not inside
2709         dist = vm_vec_dist_quick(eeo->tpos, &objp->pos) - objp->radius;
2710         if (dist < 0.0f) {
2711                 dist = 0.0f;
2712         }
2713
2714         // check if object is a bomb attacking the turret parent
2715         // check if bomb is homing on the turret parent ship
2716         if (objp->type == OBJ_WEAPON) {
2717                 if ( Weapons[objp->instance].homing_object == &Objects[eeo->turret_parent_objnum] ) {
2718                         if ( dist < eeo->nearest_homing_bomb_dist ) {
2719                                 if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2720                                         eeo->nearest_homing_bomb_dist = dist;
2721                                         eeo->nearest_homing_bomb_objnum = OBJ_INDEX(objp);
2722                                 }
2723                         }
2724                 // if not homing, check if bomb is flying towards ship
2725                 } else if ( bomb_headed_towards_ship(objp, &Objects[eeo->turret_parent_objnum]) ) {
2726                         if ( dist < eeo->nearest_bomb_dist ) {
2727                                 if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2728                                         eeo->nearest_bomb_dist = dist;
2729                                         eeo->nearest_bomb_objnum = OBJ_INDEX(objp);
2730                                 }
2731                         }
2732                 }
2733         } // end weapon section
2734
2735         // maybe recalculate dist for big or huge ship
2736 //      if (shipp && (Ship_info[shipp->ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
2737 //              fvi_ray_boundingbox(min, max, start, direction, hit);
2738 //              dist = vm_vec_dist_quick(hit, tvec);
2739 //      }
2740
2741         // check for nearest attcker
2742         if ( (shipp) && (dist < eeo->weapon_travel_dist) ) {
2743                 ai_info *aip = &Ai_info[shipp->ai_index];
2744
2745                 // modify distance based on number of turrets from my ship attacking enemy (add 10% per turret)
2746                 // dist *= (num_enemies_attacking(OBJ_INDEX(objp))+2)/2;        //      prevents lots of ships from attacking same target
2747                 int num_att_turrets = num_turrets_attacking(turret_parent_obj, OBJ_INDEX(objp));
2748                 dist *= (1.0f + 0.1f*num_att_turrets);
2749
2750                 // return if we're over the cap
2751                 int max_turrets = 3 + Game_skill_level * Game_skill_level;
2752                 if (num_att_turrets > max_turrets) {
2753                         return;
2754                 }
2755
2756                 // modify distance based on lethality of objp to my ship
2757                 float active_lethality = aip->lethality;
2758                 if (objp->flags & OF_PLAYER_SHIP) {
2759                         active_lethality += Player_lethality_bump[Game_skill_level];
2760                 }
2761
2762                 dist /= (1.0f + 0.01f*Lethality_range_const*active_lethality);
2763
2764                 // Make level 2 tagged ships more likely to be targeted
2765                 if (shipp->level2_tag_left > 0.0f) {
2766                         dist *= 0.3f;
2767                 }
2768
2769                 // check if objp is targeting the turret's ship, or if objp has just hit the turret's ship
2770                 if ( aip->target_objnum == eeo->turret_parent_objnum || aip->last_objsig_hit == Objects[eeo->turret_parent_objnum].signature ) {
2771                         // A turret will always target a ship that is attacking itself... self-preservation!
2772                         if ( aip->targeted_subsys == eeo->turret_subsys ) {
2773                                 dist *= 0.5f;   // highest priority
2774                         }
2775                 }
2776
2777                 // maybe update nearest attacker
2778                 if ( dist < eeo->nearest_attacker_dist ) {
2779                         if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2780                                 // nprintf(("AI", "Nearest enemy = %s, dist = %7.3f, dot = %6.3f, fov = %6.3f\n", Ships[objp->instance].ship_name, dist, vm_vec_dot(&v2e, tvec), tp->turret_fov));
2781                                 eeo->nearest_attacker_dist = dist;
2782                                 eeo->nearest_attacker_objnum = OBJ_INDEX(objp);
2783                         }
2784                 }
2785         } // end ship section
2786
2787 #ifdef MAKE_FS1
2788         // check if object is an asteroid attacking the turret parent - taylor
2789         if (objp->type == OBJ_ASTEROID) {
2790                 if ( eeo->turret_parent_objnum == asteroid_collide_objnum(objp) ) {
2791                         // give priority to the closest asteroid *impact* (ms intervals)
2792                         dist *= 0.9f + (0.01f * asteroid_time_to_impact(objp));
2793
2794                         if (dist < eeo->nearest_dist ) {
2795                                 if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2796                                         eeo->nearest_dist = dist;
2797                                         eeo->nearest_objnum = OBJ_INDEX(objp);
2798                                 }
2799                         }
2800                 }
2801         } // end asteroid selection
2802 #endif
2803 }
2804
2805 // return 0 only if objnum is beam protected and turret is beam turret
2806 int is_target_beam_valid(ship_subsys *turret_subsys, int objnum)
2807 {
2808         // check if turret has beam weapon
2809         model_subsystem *tp = turret_subsys->system_info;
2810
2811         if (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM) {
2812                 if (Objects[objnum].flags & OF_BEAM_PROTECTED) {
2813                         return 0;
2814                 }
2815
2816                 if (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_HUGE) {
2817                         if (Objects[objnum].type == OBJ_SHIP && !(Ship_info[Ships[Objects[objnum].instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) ) {
2818                                 return 0;
2819                         }
2820                 }
2821         }
2822
2823         return 1;
2824 }
2825
2826
2827 //      Given an object and an enemy team, return the index of the nearest enemy object.
2828 //
2829 // input:
2830 //                              turret_parent_objnum    => parent objnum for the turret
2831 //                              turret_subsys                   => pointer to system_info for the turret subsystem
2832 //                              enemy_team_mask         => OR'ed TEAM_ flags for the enemy of the turret parent ship
2833 //                              tpos                                            => position of turret (world coords)
2834 //                              tvec                                            => forward vector of turret (world coords)
2835 //                              current_enemy                   =>      objnum of current turret target
2836 int get_nearest_turret_objnum(int turret_parent_objnum, ship_subsys *turret_subsys, int enemy_team_mask, vector *tpos, vector *tvec, int current_enemy, int big_only_flag)
2837 {
2838         float                                   weapon_travel_dist;
2839         int                                     weapon_system_ok;
2840         object                          *objp;
2841         model_subsystem *tp;
2842         eval_enemy_obj_struct eeo;
2843
2844         // list of stuff to go thru
2845         ship_obj                *so;
2846         missile_obj *mo;
2847
2848         tp = turret_subsys->system_info;
2849         weapon_travel_dist = SDL_min(Weapon_info[tp->turret_weapon_type].lifetime * Weapon_info[tp->turret_weapon_type].max_speed, Weapon_info[tp->turret_weapon_type].weapon_range);
2850
2851         // Set flag based on strength of weapons subsystem.  If weapons subsystem is destroyed, don't let turrets fire at bombs
2852         weapon_system_ok = 0;
2853         if ( ship_get_subsystem_strength( &Ships[Objects[turret_parent_objnum].instance], SUBSYSTEM_WEAPONS ) > 0 ) {
2854                 weapon_system_ok = 1;
2855         }
2856
2857         // Initialize eeo struct.
2858         eeo.turret_parent_objnum = turret_parent_objnum;
2859         eeo.weapon_system_ok = weapon_system_ok;
2860         eeo.weapon_travel_dist = weapon_travel_dist;
2861         eeo.big_only_flag = big_only_flag;
2862         eeo.enemy_team_mask = enemy_team_mask;
2863         eeo.current_enemy = current_enemy;
2864         eeo.tpos = tpos;
2865         eeo.tvec = tvec;
2866         eeo.turret_subsys = turret_subsys;
2867
2868         eeo.nearest_attacker_dist = 99999.0f;
2869         eeo.nearest_attacker_objnum = -1;
2870
2871         eeo.nearest_homing_bomb_dist = 99999.0f;
2872         eeo.nearest_homing_bomb_objnum = -1;
2873
2874         eeo.nearest_bomb_dist = 99999.0f;
2875         eeo.nearest_bomb_objnum = -1;
2876
2877         eeo.nearest_dist = 99999.0f;
2878         eeo.nearest_objnum = -1;
2879
2880
2881         // Missile_obj_list
2882         for( mo = GET_FIRST(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
2883                 objp = &Objects[mo->objnum];
2884                 evaluate_obj_as_target(objp, &eeo);
2885         }
2886         // highest priority
2887         if ( eeo.nearest_homing_bomb_objnum != -1 ) {                                   // highest priority is an incoming homing bomb
2888                 return eeo.nearest_homing_bomb_objnum;
2889         } else if ( eeo.nearest_bomb_objnum != -1 ) {                                   // next highest priority is an incoming dumbfire bomb
2890                 return eeo.nearest_bomb_objnum;
2891         }
2892
2893
2894         // Ship_used_list
2895         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2896                 objp = &Objects[so->objnum];
2897                 evaluate_obj_as_target(objp, &eeo);
2898         }
2899
2900         SDL_assert(eeo.nearest_attacker_objnum < 0 || is_target_beam_valid(turret_subsys, eeo.nearest_attacker_objnum));
2901                 // next highest priority is attacking ship
2902         if ( eeo.nearest_attacker_objnum != -1 ) {                      // next highest priority is an attacking ship
2903                 return eeo.nearest_attacker_objnum;
2904          }
2905
2906
2907 #if !(defined(FS2_DEMO) || defined(FS1_DEMO))
2908                 asteroid_obj *ao;
2909         // Asteroid_obj_list
2910         for( ao = GET_FIRST(&Asteroid_obj_list); ao != END_OF_LIST(&Asteroid_obj_list); ao = GET_NEXT(ao) ) {
2911                 objp = &Objects[ao->objnum];
2912                 evaluate_obj_as_target(objp, &eeo);
2913         }
2914 #endif
2915
2916         return eeo.nearest_objnum;                                                                              // lowest priority is the closest enemy objnum
2917 }
2918
2919 //      Return timestamp until a ship can find an enemy.
2920 //      Yes, no parameters.  Based solely on skill level.
2921 int get_enemy_timestamp()
2922 {
2923         return (NUM_SKILL_LEVELS - Game_skill_level) * ( (myrand() % 500) + 500);
2924 }
2925
2926 // -------------------------------------------------------------------
2927 //      Return objnum if enemy found, else return -1;
2928 //      Don't attack a ship that already has at least max_attackers attacking it.
2929 int find_enemy(int objnum, float range, int max_attackers)
2930 {
2931         int     enemy_team_mask;
2932
2933         enemy_team_mask = get_enemy_team_mask(objnum);
2934
2935         //      if target_objnum != -1, use that as goal.
2936         ai_info *aip = &Ai_info[Ships[Objects[objnum].instance].ai_index];
2937         if (timestamp_elapsed(aip->choose_enemy_timestamp)) {
2938                 aip->choose_enemy_timestamp = timestamp(get_enemy_timestamp());
2939                 if (aip->target_objnum != -1) {
2940                         int     target_objnum = aip->target_objnum;
2941
2942                         // DKA don't undo object as target in nebula missions.
2943                         // This could cause attack on ship on fringe on nebula to stop if attackee moves our of nebula range.  (BAD)
2944                         if (Objects[target_objnum].signature == aip->target_signature) {
2945                                 if (Ships[Objects[target_objnum].instance].team & enemy_team_mask) {
2946                                         if (!(Objects[target_objnum].flags & OF_PROTECTED)) {
2947                                                 // nprintf(("AI", "Frame %i: Object %i resuming goal of object %i\n", AI_FrameCount, objnum, target_objnum));
2948                                                 return target_objnum;
2949                                         }
2950                                 }
2951                         } else {
2952                                 aip->target_objnum = -1;
2953                                 aip->target_signature = -1;
2954                         }
2955                 }
2956                 return get_nearest_objnum(objnum, enemy_team_mask, aip->enemy_wing, range, max_attackers);
2957         } else {
2958                 aip->target_objnum = -1;
2959                 aip->target_signature = -1;
2960                 return -1;
2961         }
2962
2963 }
2964
2965 int Use_parent_target = 0;
2966 DCF_BOOL(use_parent_target, Use_parent_target)
2967
2968 // -------------------------------------------------------------------
2969 //      Return objnum if enemy found, else return -1;
2970 //
2971 // input:
2972 //                              turret_subsys   => pointer to turret subsystem
2973 //                              objnum                  => parent objnum for the turret
2974 //                              tpos                            => position of turret (world coords)
2975 //                              tvec                            => forward vector of turret (world coords)
2976 //                              current_enemy   =>      objnum of current turret target
2977 int find_turret_enemy(ship_subsys *turret_subsys, int objnum, vector *tpos, vector *tvec, int current_enemy, float fov, int big_only_flag = 0)
2978 {
2979         int                                     enemy_team_mask, enemy_objnum;
2980         model_subsystem *tp;
2981         ship_info                       *sip;
2982
2983         tp = turret_subsys->system_info;
2984         enemy_team_mask = get_enemy_team_mask(objnum);
2985
2986         //      If a small ship and target_objnum != -1, use that as goal.
2987         ai_info *aip = &Ai_info[Ships[Objects[objnum].instance].ai_index];
2988         sip = &Ship_info[Ships[Objects[objnum].instance].ship_info_index];
2989
2990         if ((sip->flags & SIF_SMALL_SHIP) && (aip->target_objnum != -1)) {
2991                 int target_objnum = aip->target_objnum;
2992
2993                 if (Objects[target_objnum].signature == aip->target_signature) {
2994                         if (Ships[Objects[target_objnum].instance].team & enemy_team_mask) {
2995                                 if ( !(Objects[target_objnum].flags & OF_PROTECTED) ) {         // check this flag as well.
2996                                         // nprintf(("AI", "Frame %i: Object %i resuming goal of object %i\n", AI_FrameCount, objnum, target_objnum));
2997                                         return target_objnum;
2998                                 }
2999                         }
3000                 } else {
3001                         aip->target_objnum = -1;
3002                         aip->target_signature = -1;
3003                 }
3004         // Not small or small with target objnum
3005         } else {
3006                 // maybe use aip->target_objnum as next target
3007                 if ((frand() < 0.8f) && (aip->target_objnum != -1) && Use_parent_target) {
3008
3009                         //check if aip->target_objnum is valid target
3010                         int target_flags = Objects[aip->target_objnum].flags;
3011                         if ( target_flags & OF_PROTECTED ) {
3012                                 // AL 2-27-98: why is a protected ship being targeted?
3013                                 set_target_objnum(aip, -1);
3014                                 return -1;
3015                         }
3016
3017                         // maybe use ship target_objnum if valid for turret
3018                         // check for beam weapon and beam protected
3019                         if ( !((target_flags & OF_BEAM_PROTECTED) && (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM)) ) {
3020                                 if ( Objects[aip->target_objnum].type == OBJ_SHIP ) {
3021                                         // check for huge weapon and huge ship
3022                                         if ( !big_only_flag || (Ship_info[Ships[Objects[aip->target_objnum].instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) ) {
3023                                                 // check for tagged only and tagged ship
3024                                                 if ( (turret_subsys->weapons.flags & SW_FLAG_TAGGED_ONLY) && ship_is_tagged(&Objects[aip->target_objnum]) ) {
3025                                                         // select new target if aip->target_objnum is out of field of view
3026                                                         vector v2e;
3027                                                         float dot;//, dist;
3028                                                         /*dist =*/ vm_vec_normalized_dir(&v2e, &Objects[aip->target_objnum].pos, tpos);
3029                                                         dot = vm_vec_dot(&v2e, tvec);
3030                                                         //      MODIFY FOR ATTACKING BIG SHIP
3031                                                         // dot += (0.5f * Objects[aip->target_objnum].radius / dist);
3032                                                         if (dot > fov) {
3033                                                                 return aip->target_objnum;
3034                                                         }
3035                                                 }
3036                                         }
3037                                 }
3038                         }
3039                 }
3040         }
3041
3042         enemy_objnum = get_nearest_turret_objnum(objnum, turret_subsys, enemy_team_mask, tpos, tvec, current_enemy, big_only_flag);
3043         if ( enemy_objnum >= 0 ) {
3044                 SDL_assert( !((Objects[enemy_objnum].flags & OF_BEAM_PROTECTED) && (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM)) );
3045                 if ( Objects[enemy_objnum].flags & OF_PROTECTED ) {
3046                         Int3();
3047                         enemy_objnum = aip->target_objnum;
3048                 }
3049         }
3050
3051         return enemy_objnum;
3052 }
3053
3054 //      If issued an order to a ship that's awaiting repair, abort that process.
3055 //      However, do not abort process for an object that is currently being repaired -- let it finish.
3056 void ai_set_goal_maybe_abort_dock(object *objp, ai_info *aip)
3057 {
3058         if (aip->ai_flags & AIF_AWAITING_REPAIR) {
3059                 object  *repair_obj;
3060
3061                 if (aip->dock_objnum == -1) {
3062                         repair_obj = NULL;
3063                 } else {
3064                         repair_obj = &Objects[aip->dock_objnum];
3065                 }
3066                 ai_do_objects_repairing_stuff( objp, repair_obj, REPAIR_INFO_ABORT );
3067         }
3068         aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP);    //      Might request again after 30 seconds.
3069 }
3070
3071 void force_avoid_player_check(object *objp, ai_info *aip)
3072 {
3073         if (Ships[objp->instance].team == Player_ship->team){
3074                 aip->avoid_check_timestamp = timestamp(0);              //      Force a check for collision next frame.
3075         }
3076 }
3077
3078 //      --------------------------------------------------------------------------
3079 //      Set *attacked as object to attack for object *attacker
3080 //      If attacked == NULL, then attack any enemy object.
3081 //      Attack point *rel_pos on object.  This is for supporting attacking subsystems.
3082 void ai_attack_object(object *attacker, object *attacked, int priority, ship_subsys *ssp)
3083 {
3084         ai_info *aip;
3085
3086         SDL_assert(attacker != NULL);
3087         SDL_assert(attacker->instance != -1);
3088         SDL_assert(Ships[attacker->instance].ai_index != -1);
3089
3090         aip = &Ai_info[Ships[attacker->instance].ai_index];
3091         force_avoid_player_check(attacker, aip);
3092
3093         aip->ok_to_target_timestamp = timestamp(0);             //      Guarantee we can target.
3094
3095 //      if (!SDL_strncasecmp(Ships[attacker->instance].ship_name, NOX("Kami"), 4)) {
3096 //              aip->ai_flags |= AIF_KAMIKAZE;
3097 //              aip->ai_flags |= AIF_NO_DYNAMIC;
3098 //      }
3099
3100         if (attacker == attacked) {
3101                 Int3();         //      Bogus!  Who tried to get me to attack myself!  Trace out and fix!
3102                 return;
3103         }
3104
3105         //      Only set to chase if a fighter or bomber, otherwise just return.
3106         if (!(Ship_info[Ships[attacker->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
3107 //              nprintf(("AI","Note: AI ship %s refusing to set AI mode to AIM_CHASE\n", Ships[attacker->instance].ship_name));
3108 //              return;
3109                 nprintf(("AI", "AI ship %s is large ship ordered to attack %s\n", Ships[attacker->instance].ship_name, (attacked) ? Ships[attacked->instance].ship_name : "<none>"));
3110         }
3111
3112         //      This is how "engage enemy" gets processed
3113         if (attacked == NULL) {
3114                 aip->choose_enemy_timestamp = timestamp(0);
3115                 // nebula safe
3116                 set_target_objnum(aip, find_enemy(attacker-Objects, 99999.9f, 4));
3117         } else {
3118                 // check if we can see atacked in nebula
3119                 if (aip->target_objnum != attacked - Objects) {
3120                         aip->aspect_locked_time = 0.0f;
3121                 }
3122                 set_target_objnum(aip, attacked - Objects);
3123         }
3124
3125         ai_set_goal_maybe_abort_dock(attacker, aip);
3126         aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);     //      No dynamic targeting for 7 seconds.
3127
3128         if (is_ignore_object(aip, aip->target_objnum)) {
3129                 aip->ignore_objnum = UNUSED_OBJNUM;
3130         }
3131
3132         aip->mode = AIM_CHASE;
3133         aip->submode = SM_ATTACK;       // AL 12-15-97: need to set submode?  I got an assert() where submode was bogus
3134                                                                                 //                                       for AIM_CHASE... it may have been not set correctly here
3135         if (ssp == NULL) {
3136                 set_targeted_subsys(aip, NULL, -1);
3137                 if (aip->target_objnum != -1) {
3138                         //nprintf(("AI", "Unprotecting ship %s\n", Ships[Objects[aip->target_objnum].instance].ship_name));
3139                         Objects[aip->target_objnum].flags &= ~OF_PROTECTED;     //      If ship had been protected, unprotect it.
3140                 }
3141         } else {
3142                 Int3(); //      Not supported yet!
3143         }
3144 }
3145
3146 //      --------------------------------------------------------------------------
3147 //      Set *attacked as object to attack for object *attacker
3148 //      Attack point *rel_pos on object.  This is for supporting attacking subsystems.
3149 void ai_attack_wing(object *attacker, int wingnum, int priority)
3150 {
3151         ai_info *aip;
3152
3153         SDL_assert(attacker != NULL);
3154         SDL_assert(attacker->instance != -1);
3155         SDL_assert(Ships[attacker->instance].ai_index != -1);
3156         SDL_assert(wingnum != -1);
3157
3158         if ( (wingnum < 0) || (wingnum > MAX_WINGS) ) {
3159                 return;
3160         }
3161
3162         aip = &Ai_info[Ships[attacker->instance].ai_index];
3163
3164         aip->enemy_wing = wingnum;
3165         aip->mode = AIM_CHASE;
3166         aip->submode = SM_ATTACK;       // AL 12-15-97: need to set submode?  I got an assert() where submode was bogus
3167                                                                                 //                                       for AIM_CHASE... it may have been not set correctly here
3168
3169         aip->ok_to_target_timestamp = timestamp(0);             //      Guarantee we can target.
3170
3171         int count = Wings[wingnum].current_count;
3172         if (count > 0) {
3173                 int     index;
3174
3175                 index = (int) (frand() * count);
3176
3177                 if (index >= count)
3178                         index = 0;
3179
3180                 set_target_objnum(aip, Ships[Wings[wingnum].ship_index[index]].objnum);
3181
3182                 ai_set_goal_maybe_abort_dock(attacker, aip);
3183                 aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);     //      No dynamic targeting for 7 seconds.
3184         }
3185 }
3186
3187 //      --------------------------------------------------------------------------
3188 //      Set *evaded as object for *evader to evade.
3189 void ai_evade_object(object *evader, object *evaded, int priority)
3190 {
3191         ai_info *aip;
3192
3193         SDL_assert(evader != NULL);
3194         SDL_assert(evaded != NULL);
3195         SDL_assert(evader->instance != -1);
3196         SDL_assert(Ships[evader->instance].ai_index != -1);
3197
3198         if (evaded == evader) {
3199                 Int3(); //      Bogus!  Who tried to get me to evade myself!  Trace out and fix!
3200                 return;
3201         }
3202
3203         aip = &Ai_info[Ships[evader->instance].ai_index];
3204
3205         set_target_objnum(aip, evaded - Objects);
3206         aip->mode = AIM_EVADE;
3207
3208 }
3209
3210 //      Ignore some object without changing mode.
3211 void ai_ignore_object(object *ignorer, object *ignored, int priority)
3212 {
3213         ai_info *aip;
3214
3215         SDL_assert(ignorer != NULL);
3216         SDL_assert(ignored != NULL);
3217         SDL_assert(ignorer->instance != -1);
3218         SDL_assert(Ships[ignorer->instance].ai_index != -1);
3219         SDL_assert(ignorer != ignored);
3220
3221         aip = &Ai_info[Ships[ignorer->instance].ai_index];
3222
3223         //      MK, 5/17/98, removing ignoring of wings.
3224         //      It's too confusing.  It often causes mysterious behavior in which fighters unexpectedly refuse to attack anything.
3225 /*      if (Ships[ignored->instance].wingnum > -1) {
3226                 int wingnum, i;
3227
3228                 wingnum = Ships[ignored->instance].wingnum;
3229                 aip->ignore_objnum = -(wingnum+1);
3230                 // set protected bit for each ship in a wing
3231                 //      MK, 4/23/98: Only set for fighters if they are the original "ignored" object
3232                 for (i = 0; i < Wings[wingnum].current_count; i++ ) {
3233                         object  *objp;
3234
3235                         objp = &Objects[Ships[Wings[wingnum].ship_index[i]].objnum];
3236                         if (objp != ignored) {
3237                                 if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER))
3238                                         continue;
3239                         }
3240
3241                         Objects[Ships[Wings[wingnum].ship_index[i]].objnum].flags |= OF_PROTECTED;
3242                 }
3243
3244         } else {
3245         */ {
3246                 aip->ignore_objnum = ignored - Objects;
3247                 aip->ignore_signature = ignored->signature;
3248                 aip->ai_flags &= ~AIF_TEMPORARY_IGNORE;
3249                 ignored->flags |= OF_PROTECTED;                                 // set protected bit of ignored ship.
3250         }
3251
3252 }
3253
3254 //      Ignore some object without changing mode.
3255 void ai_ignore_wing(object *ignorer, int wingnum, int priority)
3256 {
3257         ai_info *aip;
3258
3259         SDL_assert(ignorer != NULL);
3260         SDL_assert(ignorer->instance != -1);
3261         SDL_assert(Ships[ignorer->instance].ai_index != -1);
3262         SDL_assert((wingnum >= 0) && (wingnum < MAX_WINGS));
3263
3264         aip = &Ai_info[Ships[ignorer->instance].ai_index];
3265
3266         aip->ignore_objnum = -(wingnum +1);
3267         aip->ai_flags &= ~AIF_TEMPORARY_IGNORE;
3268 }
3269
3270
3271 //      Add a path point in the global buffer Path_points.
3272 //      modify_index = index in Path_points at which to store path point.
3273 //      If modify_index == -1, then create a new point.
3274 //      If a new point is created (ie, modify_index == -1), then Ppfp is updated.
3275 void add_path_point(vector *pos, int path_num, int path_index, int modify_index)
3276 {
3277         pnode   *pnp;
3278
3279         if (modify_index == -1) {
3280                 SDL_assert(Ppfp-Path_points < MAX_PATH_POINTS-1);
3281                 pnp = Ppfp;
3282                 Ppfp++;
3283         } else {
3284                 SDL_assert((modify_index >= 0) && (modify_index < MAX_PATH_POINTS-1));
3285                 pnp = &Path_points[modify_index];
3286         }
3287
3288         pnp->pos = *pos;
3289         pnp->path_num = path_num;
3290         pnp->path_index = path_index;
3291 }
3292
3293 //      Given two points on a sphere, the center of the sphere and the radius, return a
3294 //      point on the vector through the midpoint of the chord on the sphere.
3295 void bisect_chord(vector *p0, vector *p1, vector *centerp, float radius)
3296 {
3297         vector  tvec;
3298         vector  new_pnt;
3299
3300         vm_vec_add(&tvec, p0, p1);
3301         vm_vec_sub2(&tvec, centerp);
3302         vm_vec_sub2(&tvec, centerp);
3303         if (vm_vec_mag_quick(&tvec) < 0.1f) {
3304                 vm_vec_sub(&tvec, p0, p1);
3305                 if (fl_abs(tvec.xyz.x) <= fl_abs(tvec.xyz.z)){
3306                         tvec.xyz.x = -tvec.xyz.z;
3307                 } else {
3308                         tvec.xyz.y = -tvec.xyz.x;
3309                 }
3310         }
3311
3312         vm_vec_normalize(&tvec);
3313         vm_vec_scale(&tvec, radius);
3314         vm_vec_add(&new_pnt, centerp, &tvec);
3315
3316         add_path_point(&new_pnt, -1, -1, -1);
3317 }
3318                         
3319 //      Create a path from the current position to a goal position.
3320 //      The current position is in the current object and the goal position is
3321 //      in the goal object.
3322 //      It is ok to intersect the current object, but not the goal object.
3323 //      This function is useful for creating a path to an initial point near a large
3324 //      object.
3325 //
3326 // input:       subsys_path:    optional param (default 0), indicates this is a path to a subsystem
3327 void create_path_to_point(vector *curpos, vector *goalpos, object *curobjp, object *goalobjp, int subsys_path)
3328 {
3329         //      If can't cast vector to goalpos, then create an intermediate point.
3330         if (pp_collide(curpos, goalpos, goalobjp, curobjp->radius)) {
3331                 vector  tan1;
3332                 float           radius;
3333
3334                 // If this is a path to a subsystem, use SUBSYS_PATH_DIST as the radius for the object you are
3335                 // trying to avoid.  This is needed since subsystem paths extend out to SUBSYS_PATH_DIST, and we
3336                 // want ships to reach their path destination without flying to points that sit on the radius of
3337                 // a small ship
3338                 radius = goalobjp->radius;
3339                 if (subsys_path) {
3340                         if ( SUBSYS_PATH_DIST > goalobjp->radius ) {
3341                                 radius = SUBSYS_PATH_DIST;
3342                         }
3343                 }
3344
3345                 //      The intermediate point is at the intersection of:
3346                 //              tangent to *goalobjp sphere at point *goalpos
3347                 //              tangent to *goalobjp sphere through point *curpos in plane defined by *curpos, *goalpos, goalobjp->pos
3348                 //      Note, there are two tangents through *curpos, unless *curpos is on the
3349                 //      sphere.  The tangent that causes the nearer intersection (to *goalpos) is chosen.
3350                 get_tangent_point(&tan1, curpos, &goalobjp->pos, goalpos, radius);
3351
3352                 //      If we can't reach tan1 from curpos, insert a new point.
3353                 if (pp_collide(&tan1, curpos, goalobjp, curobjp->radius))
3354                         bisect_chord(curpos, &tan1, &goalobjp->pos, radius);
3355
3356                 add_path_point(&tan1, -1, -1, -1);
3357
3358                 //      If we can't reach goalpos from tan1, insert a new point.
3359                 if (pp_collide(goalpos, &tan1, goalobjp, curobjp->radius))
3360                         bisect_chord(goalpos, &tan1, &goalobjp->pos, radius);
3361         }
3362
3363 }
3364
3365 //      Given an object and a model path, globalize the points on the model
3366 //      and copy into the global path list.
3367 //      If pnp != NULL, then modify, in place, the path points.  This is used to create new
3368 //      globalized points when the base object has moved.
3369 // input:       randomize_pnt   => optional parameter (default value -1), add random vector in sphere to this path point
3370 void copy_xlate_model_path_points(object *objp, model_path *mp, int dir, int count, int path_num, pnode *pnp, int randomize_pnt)
3371 {
3372         matrix  m;
3373         int             i;
3374         vector  v1;
3375         int             pp_index;               //      index in Path_points at which to store point, if this is a modify-in-place (pnp ! NULL)
3376         int             start_index, finish_index;
3377         
3378         // nprintf(("AI", "Creating path for object %s in frame #%i\n", Ships[objp->instance].ship_name, AI_FrameCount));
3379         
3380         //      Initialize pp_index.
3381         //      If pnp == NULL, that means we're creating new points.  If not NULL, then modify in place.
3382         if (pnp == NULL)
3383                 pp_index = -1;                  //      This tells add_path_point to create a new point.
3384         else
3385                 pp_index = 0;                   //      pp_index will get assigned to index in Path_points to reuse.
3386
3387         vm_copy_transpose_matrix(&m, &objp->orient);
3388
3389         if (dir == 1) {
3390                 start_index = 0;
3391                 finish_index = SDL_min(count, mp->nverts);
3392         } else {
3393                 SDL_assert(dir == -1);  //      direction must be up by 1 or down by 1 and it's neither!
3394                 start_index = mp->nverts-1;
3395                 finish_index = SDL_max(-1, mp->nverts-1-count);
3396         }
3397
3398         int offset = 0;
3399         for (i=start_index; i != finish_index; i += dir) {
3400                 //      Globalize the point.
3401                 vm_vec_rotate(&v1, &mp->verts[i].pos, &m);
3402                 vm_vec_add2(&v1, &objp->pos);
3403
3404                 if ( randomize_pnt == i ) {
3405                         vector v_rand;
3406                         static_randvec(OBJ_INDEX(objp), &v_rand);
3407                         vm_vec_scale(&v_rand, 30.0f);
3408                         vm_vec_add2(&v1, &v_rand);
3409                 }
3410
3411                 if (pp_index != -1)
3412                         pp_index = pnp-Path_points + offset;
3413
3414                 add_path_point(&v1, path_num, i, pp_index);
3415                 offset++;
3416         }
3417 }
3418
3419
3420 //      For pl_objp, create a path along path path_num into mobjp.
3421 //      The tricky part of this problem is creating the entry to the first point on the
3422 //      predefined path.  The points on this entry path are based on the location of Pl_objp
3423 //      relative to the start of the path.
3424 //
3425 // input:
3426 //                              subsys_path:    optional param (default 0), indicating this is a path to a subsystem
3427 void create_model_path(object *pl_objp, object *mobjp, int path_num, int subsys_path)
3428 {       
3429         ship                    *shipp = &Ships[pl_objp->instance];
3430         ai_info         *aip = &Ai_info[shipp->ai_index];
3431
3432         ship_info       *osip = &Ship_info[Ships[mobjp->instance].ship_info_index];
3433         polymodel       *pm = model_get(osip->modelnum);
3434         model_path      *mp;
3435         pnode                   *ppfp_start = Ppfp;
3436         matrix          m;
3437         vector          gp0;
3438
3439         SDL_assert(path_num >= 0);
3440
3441         //      Do garbage collection if necessary.
3442         if (Ppfp-Path_points + 64 > MAX_PATH_POINTS) {
3443                 garbage_collect_path_points();
3444                 ppfp_start = Ppfp;
3445         }
3446
3447         aip->path_start = Ppfp - Path_points;
3448         SDL_assert(path_num < pm->n_paths);
3449         
3450         mp = &pm->paths[path_num];
3451
3452         SDL_assert(Ppfp-Path_points + mp->nverts + 4 < MAX_PATH_POINTS);
3453
3454         vm_copy_transpose_matrix(&m, &mobjp->orient);
3455         vm_vec_rotate(&gp0, &mp->verts[0].pos, &m);
3456         vm_vec_add2(&gp0, &mobjp->pos);
3457
3458         if (pp_collide(&pl_objp->pos, &gp0, mobjp, pl_objp->radius)) {
3459                 vector  perim_point1;
3460                 vector  perim_point2;
3461
3462                 perim_point2 = pl_objp->pos;
3463                 
3464                 //      If object that wants to dock is inside bounding sphere of object it wants to dock with, make it fly out.
3465                 //      Assume it can fly "straight" out to the bounding sphere.
3466                 if (vm_vec_dist_quick(&pl_objp->pos, &mobjp->pos) < mobjp->radius) {
3467                         project_point_to_perimeter(&perim_point2, &mobjp->pos, mobjp->radius, &pl_objp->pos);
3468                         add_path_point(&perim_point2, path_num, -1, -1);
3469                 }
3470
3471                 //      If last point on pre-defined path is inside bounding sphere, create a new point on the surface of the sphere.
3472                 if (vm_vec_dist_quick(&mobjp->pos, &gp0) < mobjp->radius) {
3473                         project_point_to_perimeter(&perim_point1, &mobjp->pos, mobjp->radius, &gp0);
3474                         create_path_to_point(&perim_point2, &perim_point1, pl_objp, mobjp, subsys_path);
3475                         add_path_point(&perim_point1, path_num, -1, -1);
3476                 } else {                //      The predefined path extends outside the sphere.  Create path to that point.
3477                         create_path_to_point(&perim_point2, &gp0, pl_objp, mobjp, subsys_path);
3478                 }
3479         }
3480
3481         // AL 12-31-97: If following a subsystem path, add random vector to second last path point
3482         if ( subsys_path ) {
3483                 copy_xlate_model_path_points(mobjp, mp, 1, mp->nverts, path_num, NULL, mp->nverts-2);
3484         } else {
3485                 copy_xlate_model_path_points(mobjp, mp, 1, mp->nverts, path_num, NULL);
3486         }
3487
3488         aip->path_cur = aip->path_start;
3489         aip->path_dir = PD_FORWARD;
3490         aip->path_objnum = mobjp-Objects;
3491         aip->mp_index = path_num;
3492         aip->path_length = Ppfp - ppfp_start;
3493         aip->path_next_check_time = timestamp(1);
3494
3495         aip->path_goal_obj_hash = create_object_hash(&Objects[aip->path_objnum]);
3496
3497         aip->path_next_create_time = timestamp(1000);   //      OK to try to create one second later
3498         aip->path_create_pos = pl_objp->pos;
3499         aip->path_create_orient = pl_objp->orient;
3500
3501         aip->ai_flags &= ~AIF_USE_EXIT_PATH;                    // ensure this flag is cleared
3502 }
3503
3504 //      For pl_objp, create a path along path path_num into mobjp.
3505 //      The tricky part of this problem is creating the entry to the first point on the
3506 //      predefined path.  The points on this entry path are based on the location of pl_objp
3507 //      relative to the start of the path.
3508 void create_model_exit_path(object *pl_objp, object *mobjp, int path_num, int count)
3509 {       
3510         ship                    *shipp = &Ships[pl_objp->instance];
3511         ai_info         *aip = &Ai_info[shipp->ai_index];
3512
3513         ship_info       *osip = &Ship_info[Ships[mobjp->instance].ship_info_index];
3514         polymodel       *pm = model_get(osip->modelnum);
3515         model_path      *mp;
3516         pnode                   *ppfp_start = Ppfp;
3517
3518         aip->path_start = Ppfp - Path_points;
3519         SDL_assert(path_num < pm->n_paths);
3520         
3521         mp = &pm->paths[path_num];
3522
3523         SDL_assert(Ppfp-Path_points + mp->nverts + 4 < MAX_PATH_POINTS);
3524
3525         copy_xlate_model_path_points(mobjp, mp, -1, count, path_num, NULL);
3526
3527         aip->path_cur = aip->path_start;
3528         aip->path_dir = PD_FORWARD;
3529         aip->path_objnum = mobjp-Objects;
3530         aip->mp_index = path_num;
3531         aip->path_length = Ppfp - ppfp_start;
3532         aip->path_next_check_time = timestamp(1);
3533
3534         aip->ai_flags |= AIF_USE_EXIT_PATH;             // mark as exit path, referenced in maybe
3535 }
3536
3537 //      Return true if the vector from curpos to goalpos intersects with any ship other than the ignore objects.
3538 //      Calls pp_collide
3539 int pp_collide_any(vector *curpos, vector *goalpos, float radius, object *ignore_objp1, object *ignore_objp2, int big_only_flag)
3540 {
3541         ship_obj        *so;    
3542
3543         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
3544                 object *objp = &Objects[so->objnum];
3545
3546                 if (big_only_flag) {
3547                         if (!(Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)))
3548                                 continue;
3549                 }
3550
3551                 if ((objp != ignore_objp1) && (objp != ignore_objp2)) {
3552                         if (pp_collide(curpos, goalpos, objp, radius))
3553                                 return OBJ_INDEX(objp);
3554                 }
3555         }
3556
3557         return -1;
3558 }
3559
3560 //      Used to create docking paths and other pre-defined paths through ships.
3561 //      Creates a path in absolute space.
3562 //      Create a path into the object objnum.
3563 //
3564 // input:
3565 //      pl_objp:                        object that will use the path
3566 //      objnum:                 Object to find path to.
3567 //      path_num:               model path index to use
3568 //      exit_flag:              true means this is an exit path in the model
3569 // subsys_path: optional param (default 0) that indicates this is a path to a subsystem
3570 //      Exit:
3571 //      ai_info struct in Pl_objp gets stuffed with information to enable Pl_objp to fly the path.
3572 void ai_find_path(object *pl_objp, int objnum, int path_num, int exit_flag, int subsys_path)
3573 {
3574         ai_info *aip = &Ai_info[Ships[pl_objp->instance].ai_index];
3575
3576         SDL_assert(path_num >= 0);
3577
3578         //      This is test code, find an object with paths.
3579         if (objnum != -1) {
3580                 object  *objp = &Objects[objnum];
3581
3582                 if (objp->type == OBJ_SHIP) {
3583 #ifndef NDEBUG
3584                         polymodel *pm = model_get( Ships[objp->instance].modelnum );
3585                         SDL_assert(pm->n_paths > path_num);
3586 #endif
3587                         aip->goal_objnum = objp-Objects;
3588                         aip->goal_signature = objp->signature;
3589                         if (exit_flag)
3590                                 create_model_exit_path(pl_objp, objp, path_num);
3591                         else
3592                                 create_model_path(pl_objp, objp, path_num, subsys_path);
3593                         return;
3594                 }
3595
3596         }
3597 }
3598
3599 extern int vector_object_collision(vector *start_pos, vector *end_pos, object *objp, float radius_scale);
3600
3601 //      Maybe make *objp avoid a player object.
3602 //      For now, 4/6/98, only check Player_obj.
3603 //      If player collision would occur, set AIF_AVOIDING_SMALL_SHIP bit in ai_flags.
3604 //      Set aip->avoid_goal_point
3605 int maybe_avoid_player(object *objp, vector *goal_pos)
3606 {
3607         ai_info *aip;
3608         vector  cur_pos, new_goal_pos;
3609         object  *player_objp;
3610         vector  n_vec_to_goal, n_vec_to_player;
3611
3612         aip = &Ai_info[Ships[objp->instance].ai_index];
3613
3614         if (!timestamp_elapsed(aip->avoid_check_timestamp))
3615                 return 0;
3616
3617         player_objp = Player_obj;
3618
3619         float   speed_time;
3620
3621         //      How far two ships could be apart and still collide within one second.
3622         speed_time = player_objp->phys_info.speed + objp->phys_info.speed;
3623
3624         float   obj_obj_dist;
3625
3626         obj_obj_dist = vm_vec_dist_quick(&player_objp->pos, &objp->pos);
3627
3628         if (obj_obj_dist > speed_time*2.0f)
3629                 return 0;
3630
3631         cur_pos = objp->pos;
3632
3633         new_goal_pos = *goal_pos;
3634
3635         float dist = vm_vec_normalized_dir(&n_vec_to_goal, goal_pos, &objp->pos);
3636         vm_vec_normalized_dir(&n_vec_to_player, &player_objp->pos, &objp->pos);
3637
3638         if (dist > speed_time*2.0f) {
3639                 vm_vec_scale_add(&new_goal_pos, &objp->pos, &n_vec_to_goal, 200.0f);
3640         }
3641
3642         if (vector_object_collision(&objp->pos, &new_goal_pos, player_objp, 1.5f)) {
3643                 aip->ai_flags |= AIF_AVOIDING_SMALL_SHIP;
3644
3645                 vector  avoid_vec;
3646
3647                 vm_vec_sub(&avoid_vec, &n_vec_to_goal, &n_vec_to_player);
3648                 if (vm_vec_mag_quick(&avoid_vec) < 0.01f) {
3649                         vm_vec_copy_scale(&avoid_vec, &objp->orient.v.rvec, frand()-0.5f);
3650                         vm_vec_scale_add2(&avoid_vec, &objp->orient.v.uvec, frand()-0.5f);
3651                         vm_vec_normalize(&avoid_vec);
3652                 } else {
3653                         vector  tvec1;
3654                         vm_vec_normalize(&avoid_vec);
3655                         vm_vec_crossprod(&tvec1, &n_vec_to_goal, &avoid_vec);
3656                         vm_vec_crossprod(&avoid_vec, &tvec1, &n_vec_to_player);
3657                 }
3658
3659                 //      Now, avoid_vec is a vector perpendicular to the vector to the player and the direction *objp
3660                 //      should fly in to avoid the player while still approaching its goal.
3661                 vm_vec_scale_add(&aip->avoid_goal_point, &player_objp->pos, &avoid_vec, 400.0f);
3662
3663                 aip->avoid_check_timestamp = timestamp(1000);
3664
3665                 return 1;
3666         } else {
3667                 aip->ai_flags &= ~AIF_AVOIDING_SMALL_SHIP;
3668                 aip->avoid_check_timestamp = timestamp((int) (obj_obj_dist/200.0f) + 500);
3669
3670                 return 0;
3671         }
3672 }
3673
3674 //      Make object *still_objp enter AIM_STILL mode.
3675 //      Make it point at view_pos.
3676 void ai_stay_still(object *still_objp, vector *view_pos)
3677 {
3678         ship    *shipp;
3679         ai_info *aip;
3680
3681         SDL_assert(still_objp->type == OBJ_SHIP);
3682         SDL_assert((still_objp->instance >= 0) && (still_objp->instance < MAX_OBJECTS));
3683
3684         shipp = &Ships[still_objp->instance];
3685         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
3686
3687         aip = &Ai_info[shipp->ai_index];
3688
3689         aip->mode = AIM_STILL;
3690
3691         //      If view_pos not NULL, point at that point.  Else, point at a point directly in front of ship.  Ie, don't turn.
3692         if (view_pos != NULL)
3693                 aip->goal_point = *view_pos;
3694         else
3695                 vm_vec_scale_add(&aip->goal_point, &still_objp->pos, &still_objp->orient.v.fvec, 100.0f);
3696 }
3697
3698 // code which is called from ai_dock_with_object and ai_dock to set flags and apprioriate variable
3699 // when two objects have completed docking.  used because we can dock object initially at misison load
3700 // time (meaning that ai_dock() might never get called).  docker has docked with dockee (i.e. docker
3701 // would be a freighter and dockee would be a cargo).
3702 void ai_do_objects_docked_stuff(object *docker, object *dockee)
3703 {
3704         ai_info *aip, *other_aip;
3705
3706         aip = &Ai_info[Ships[docker->instance].ai_index];
3707         other_aip = &Ai_info[Ships[dockee->instance].ai_index];
3708
3709         // set the flags and dock_objnum for both objects
3710         aip->ai_flags |= AIF_DOCKED;
3711         aip->dock_objnum = OBJ_INDEX(dockee);
3712         other_aip->ai_flags |= AIF_DOCKED;
3713         other_aip->dock_objnum = OBJ_INDEX(docker);
3714         aip->dock_signature = dockee->signature;
3715         other_aip->dock_signature = docker->signature;
3716
3717         // add multiplayer hook here to deal with docked objects.  We need to only send information
3718         // about the object that is docking.  Both flags will get updated.
3719         if ( MULTIPLAYER_MASTER )
3720                 send_ai_info_update_packet( docker, AI_UPDATE_DOCK );
3721
3722 }
3723
3724 // code which is called when objects become undocked. Equivalent of above function.
3725 // dockee might not be valid since this code can get called to cleanup after a ship
3726 // has blown up!
3727 void ai_do_objects_undocked_stuff( object *docker, object *dockee )
3728 {
3729         ai_info *aip, *other_aip;
3730
3731         // add multiplayer hook here to deal with undocked objects.  Do it before we
3732         // do anything else.  We don't need to send info for both objects, since we can find
3733         // it be dock_objnum
3734         if ( MULTIPLAYER_MASTER )
3735                 send_ai_info_update_packet( docker, AI_UPDATE_UNDOCK );
3736
3737         aip = &Ai_info[Ships[docker->instance].ai_index];
3738
3739         // set the flags and dock_objnum for both objects
3740         aip->ai_flags &= ~(AIF_DOCKED | AIF_BEING_REPAIRED);
3741         aip->dock_objnum = -1;
3742         
3743         if ( dockee != NULL ) {
3744                 other_aip = &Ai_info[Ships[dockee->instance].ai_index];
3745                 other_aip->ai_flags &= ~(AIF_DOCKED | AIF_BEING_REPAIRED);
3746                 other_aip->dock_objnum = -1;
3747         }
3748
3749 }
3750
3751
3752 //      --------------------------------------------------------------------------
3753 //      Interface from goals code to AI.
3754 //      Cause *docker to dock with *dockee.
3755 //      priority is priority of goal from goals code.
3756 //      dock_type is:
3757 //              AIDO_DOCK               set goal of docking
3758 //              AIDO_DOCK_NOW   immediately dock, used for ships that need to be docked at mission start
3759 //              AIDO_UNDOCK             set goal of undocking
3760 void ai_dock_with_object(object *docker, object *dockee, int priority, int dock_type, int docker_index, int dockee_index)
3761 {
3762         ai_info         *aip;
3763         ai_info         *dockee_aip;
3764
3765         SDL_assert(docker != NULL);
3766         SDL_assert(dockee != NULL);
3767         SDL_assert(docker->instance != -1);
3768         SDL_assert(Ships[docker->instance].ai_index != -1);
3769         SDL_assert(Ships[dockee->instance].ai_index != -1);
3770         SDL_assert( docker_index != -1 );
3771         SDL_assert( dockee_index != -1 );
3772
3773         aip = &Ai_info[Ships[docker->instance].ai_index];
3774
3775         if ((aip->ai_flags & AIF_DOCKED) && (dock_type == AIDO_DOCK)) {
3776         //      object  *dockee2;
3777         //      int             docker_index2, dockee_index2;
3778
3779                 SDL_assert(aip->dock_objnum > -1);
3780         //      dockee2 = &Objects[aip->dock_objnum];
3781         //      docker_index2 = aip->dock_index;
3782         //      dockee_index2 = aip->dockee_index;
3783                 // MWA -- 2/9/98.  use the goal code to undock the ships since goals might need to get removed
3784                 // and that code will do it properly.  I'd actually be surprised if we got into this code anymore
3785                 // since the outer layer goal code should deal with this issue....but who knows...
3786                 ai_add_goal_ship_internal( aip, AI_GOAL_UNDOCK, NULL, -1, -1, 0 );
3787
3788                 // old code below
3789                 //ai_dock_with_object(docker, dockee2, priority, AIDO_UNDOCK, docker_index2, dockee_index2);
3790                 nprintf(("AI", "Ship %s told to dock with %s, but it was already docked with %s.\n", Ships[docker->instance].ship_name, Ships[dockee->instance].ship_name, Ships[Objects[aip->dock_objnum].instance].ship_name));
3791                 nprintf(("AI", "...so ship %s will now undock.\n", Ships[docker->instance].ship_name));
3792                 return;
3793         }
3794
3795         dockee_aip = &Ai_info[Ships[dockee->instance].ai_index];
3796
3797         aip->goal_objnum = dockee - Objects;
3798         aip->goal_signature = dockee->signature;
3799
3800         aip->mode = AIM_DOCK;
3801
3802         switch (dock_type) {
3803         case AIDO_DOCK:
3804                 aip->submode = AIS_DOCK_0;
3805                 break;
3806         case AIDO_DOCK_NOW:
3807                 aip->submode = AIS_DOCK_3A;
3808                 break;
3809         case AIDO_UNDOCK:
3810                 aip->submode = AIS_UNDOCK_0;
3811                 break;
3812         default:
3813                 Int3();         //      Bogus dock_type.
3814         }
3815
3816         aip->submode_start_time = Missiontime;
3817         aip->dock_index = docker_index;
3818         aip->dockee_index = dockee_index;
3819
3820         dockee_aip->dock_index = dockee_index;
3821         dockee_aip->dockee_index = docker_index;
3822
3823         // get the path number to the docking point on the dockee.  Each docking point contains a list
3824         // of paths that the point can be reached by.  Pick the first path in the path list for now.
3825         // We only want to do this stuff if we are docking!!!  Be sure to set the path index
3826         if ((dock_type == AIDO_DOCK) || (dock_type == AIDO_DOCK_NOW)) {
3827 #ifndef NDEBUG
3828                 polymodel *pm = model_get( Ships[dockee->instance].modelnum );
3829                 SDL_assert( pm->docking_bays[dockee_index].num_spline_paths > 0 );
3830 #endif
3831
3832                 // only set the dock path index if we are docking.  undocking will assume that dock_path_index
3833                 // already set from some other docking command
3834                 aip->dock_path_index = dockee_index;
3835                 dockee_aip->dock_path_index = docker_index;
3836         }
3837
3838         if (dock_type != AIDO_DOCK_NOW) {
3839                 int path_num;
3840                 //      Note: Second parameter is dock path index.  This should be specified as an
3841                 //      _input_ to this function and passed through.  The path index should be already
3842                 // set for the undock function
3843                 path_num = ai_return_path_num_from_dockbay(dockee, dockee_index);
3844                 ai_find_path(docker, dockee-Objects, path_num, 0);
3845 //              ai_find_path(dockee-Objects, dockee_index, 0);
3846         } else {
3847                 dock_orient_and_approach(docker, dockee, DOA_DOCK_STAY);
3848                 //aip->dock_objnum = OBJ_INDEX(dockee);
3849                 ai_do_objects_docked_stuff( docker, dockee );
3850         }
3851
3852 }
3853
3854 //      Cause a ship to fly its waypoints.
3855 //      flags tells:
3856 //              WPF_REPEAT      Set -> repeat waypoints.
3857 void ai_start_waypoints(object *objp, int waypoint_list_index, int wp_flags)
3858 {
3859         ai_info *aip;
3860
3861         SDL_assert(waypoint_list_index < Num_waypoint_lists);
3862
3863         //nprintf(("AI", "Frame %i: Ship %s instructed to fly waypoint list #%i\n", AI_FrameCount, Ships[objp->instance].ship_name, waypoint_list_index));
3864         aip = &Ai_info[Ships[objp->instance].ai_index];
3865
3866         if ( (aip->mode == AIM_WAYPOINTS) && (aip->wp_index == waypoint_list_index) )
3867                 return;
3868
3869         aip->ai_flags |= AIF_FORMATION_WING;
3870         aip->ai_flags &= ~AIF_FORMATION_OBJECT;
3871         aip->wp_list = waypoint_list_index;
3872         aip->wp_index = 0;
3873         aip->wp_flags = wp_flags;
3874         aip->mode = AIM_WAYPOINTS;
3875
3876         SDL_assert(aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC);
3877 }
3878
3879 //      Make *objp stay within dist units of *other_objp
3880 void ai_do_stay_near(object *objp, object *other_objp, float dist)
3881 {
3882         ai_info *aip;
3883
3884         SDL_assert(objp != other_objp);         //      Bogus!  Told to stay near self.
3885         SDL_assert(objp->type == OBJ_SHIP);
3886         SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
3887
3888         aip = &Ai_info[Ships[objp->instance].ai_index];
3889
3890         aip->mode = AIM_STAY_NEAR;
3891         aip->submode = -1;
3892         aip->stay_near_distance = dist;
3893         aip->goal_objnum = other_objp-Objects;
3894         aip->goal_signature = other_objp->signature;
3895
3896 }
3897
3898 //      Make object *objp form on wing of object *goal_objp
3899 void ai_form_on_wing(object *objp, object *goal_objp)
3900 {
3901         ai_info *aip;
3902         ship                    *shipp;
3903         ship_info       *sip;
3904
3905         // objp == goal_objp sometimes in multiplayer when someone leaves a game -- make a simple
3906         // out for this case.
3907         if ( Game_mode & GM_MULTIPLAYER ) {
3908                 if ( objp == goal_objp ) {
3909                         return;
3910                 }
3911         }
3912
3913         SDL_assert(objp != goal_objp);          //      Bogus!  Told to form on own's wing!
3914
3915         shipp = &Ships[objp->instance];
3916         sip = &Ship_info[shipp->ship_info_index];
3917
3918         //      Only fighters or bombers allowed to form on wing.
3919         if (!(sip->flags & (SIF_FIGHTER | SIF_BOMBER))) {
3920                 nprintf(("AI", "Warning: Ship %s tried to form on player's wing, but not fighter or bomber.\n", shipp->ship_name));
3921                 return;
3922         }
3923
3924         aip = &Ai_info[Ships[objp->instance].ai_index];
3925
3926         aip->ai_flags &= ~AIF_FORMATION_WING;
3927         aip->ai_flags |= AIF_FORMATION_OBJECT;
3928
3929         aip->goal_objnum = goal_objp-Objects;
3930         ai_set_goal_maybe_abort_dock(objp, aip);
3931         aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME*4);           //      Super extra long time until can target another ship.
3932
3933 }
3934
3935 //      Given an object and an object on whose wing to form, return slot to use.
3936 //      Optimize:
3937 //              This function is called per object in formation per frame.  Should store slot in ai_info struct.
3938 int ai_formation_object_get_slotnum(int objnum, object *objp)
3939 {
3940         int     slotnum = 1;                    //      Note: Slot #0 means leader, which isn't someone who was told to form-on-wing.
3941         object *o;
3942
3943         for ( o = GET_FIRST(&obj_used_list); o != END_OF_LIST(&obj_used_list); o = GET_NEXT(o) ) {
3944                 if (objp == o)
3945                         break;
3946                 else if (o->type == OBJ_SHIP)
3947                         if (Ai_info[Ships[o->instance].ai_index].ai_flags & AIF_FORMATION_OBJECT)
3948                                 if (Ai_info[Ships[o->instance].ai_index].goal_objnum == objnum)
3949                                         slotnum++;
3950         }
3951
3952         SDL_assert(o != END_OF_LIST(&obj_used_list));   //      Didn't find objp in list of used ships.  Impossible!
3953
3954         return slotnum;
3955 }
3956
3957 #define BIGNUM  100000.0f
3958
3959 int Debug_k = 0;
3960
3961 //      Given an attacker's position and a target's position and velocity, compute the time of
3962 //      intersection of a weapon fired by the attacker with speed weapon_speed.
3963 //      Return this value.  Return value of 0.0f means no collision is possible.
3964 float compute_collision_time(vector *targpos, vector *targvel, vector *attackpos, float weapon_speed)
3965 {
3966         vector  vec_to_target;
3967         float           pos_dot_vel;
3968         float           vel_sqr;
3969         float           discrim;
3970
3971         vm_vec_sub(&vec_to_target, targpos, attackpos);
3972         pos_dot_vel = vm_vec_dot(&vec_to_target, targvel);
3973         vel_sqr = vm_vec_dot(targvel, targvel) - weapon_speed*weapon_speed;
3974         discrim = pos_dot_vel*pos_dot_vel - vel_sqr*vm_vec_dot(&vec_to_target, &vec_to_target);
3975
3976         if (discrim > 0.0f) {
3977                 float   t1, t2, t_solve;
3978
3979                 t1 = (-pos_dot_vel + fl_sqrt(discrim)) / vel_sqr;
3980                 t2 = (-pos_dot_vel - fl_sqrt(discrim)) / vel_sqr;
3981
3982                 t_solve = BIGNUM;
3983
3984                 if (t1 > 0.0f)
3985                         t_solve = t1;
3986                 if ((t2 > 0.0f) && (t2 < t_solve))
3987                         t_solve = t2;
3988
3989                 if (t_solve < BIGNUM-1.0f) {
3990                         return t_solve + Debug_k * flFrametime;
3991                 }
3992         }
3993
3994         return 0.0f;
3995 }
3996
3997
3998 //      --------------------------------------------------------------------------
3999 //      If far away, use player's speed.
4000 //      If in between, lerp between player and laser speed
4001 //      If close, use laser speed.
4002 // Want to know how much time it will take to get to the enemy.
4003 // This function doesn't account for the fact that by the time the player
4004 // (or his laser) gets to the current enemy position, the enemy will have moved.
4005 // This is dealt with in polish_predicted_enemy_pos.
4006 float compute_time_to_enemy(float dist_to_enemy, object *pobjp, object *eobjp)
4007 {
4008         float   time_to_enemy;
4009         float   pl_speed = pobjp->phys_info.speed;
4010         float   max_laser_distance, max_laser_speed;
4011         int     bank_num, weapon_num;
4012         ship    *shipp = &Ships[pobjp->instance];
4013
4014         bank_num = shipp->weapons.current_primary_bank;
4015         weapon_num = shipp->weapons.primary_bank_weapons[bank_num];
4016         max_laser_speed = Weapon_info[weapon_num].max_speed;
4017         max_laser_distance = max_laser_speed * Weapon_info[weapon_num].lifetime;
4018
4019         //      If pretty far away, use player's speed to predict position, else
4020         //      use laser's speed because when close, we care more about hitting
4021         //      with a laser than about causing ship:ship rendezvous.
4022         if (dist_to_enemy > 1.5 * max_laser_distance) {
4023                 if (pl_speed > 0.0f)
4024                         time_to_enemy = dist_to_enemy/pl_speed;
4025                 else
4026                         time_to_enemy = 1.0f;
4027         } else if (dist_to_enemy > 1.1*max_laser_distance) {
4028                 if (pl_speed > 0.1f) {
4029                         float   scale;
4030
4031                         scale = (float) ((dist_to_enemy - max_laser_distance) / max_laser_distance);
4032                 
4033                         time_to_enemy = (float) (dist_to_enemy/(pl_speed * scale + max_laser_speed * (1.0f - scale)));
4034                 } else
4035                         time_to_enemy = 2.0f;
4036         } else
4037                 time_to_enemy = (float) (dist_to_enemy/max_laser_speed);
4038
4039         // return time_to_enemy * (1.0f + Ai_info[Ships[pobjp->instance].ai_index].lead_scale);
4040         return time_to_enemy + flFrametime;
4041 }
4042
4043 //      Stuff *dot and *tts.
4044 //      *dot is always computed.  If dot is less than zero, the magnitude is
4045 //      incorrect, not having been divided by distance.
4046 //      If *dot is > 0.0f, then tts is computed.  This is the time it will take object
4047 //      *objp to get to *pos, assuming it moves right at it.
4048 void fds_aux(float *dot, float *tts, vector *pos, float dtime, object *objp)
4049 {
4050         vector  v2s;
4051
4052         vm_vec_sub(&v2s, pos, &objp->pos);
4053         *dot = vm_vec_dot(&v2s, &objp->orient.v.fvec);
4054
4055         if (*dot > 0.0f) {
4056                 float   dist;
4057
4058                 dist = vm_vec_dist(&objp->pos, pos);
4059
4060                 if (dist > 0.1f)
4061                         *dot /= dist;
4062                 else
4063                         *dot = 1.0f;
4064
4065                 if (objp->phys_info.speed > 0.1f)
4066                         *tts = dist / objp->phys_info.speed;
4067                 else
4068                         *tts = dist * 100.0f;
4069         }
4070 }
4071
4072 /*
4073 //      Return index of weapon that could hit object *sobjp within dtime seconds.
4074 //      Actual time until impact returned in *atime.
4075 int find_danger_weapon(object *sobjp, float dtime, float *atime, float dot_threshhold)
4076 {
4077         object  *objp, *best_objp = NULL;
4078         float           best_tts = 1000.0f;
4079
4080         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
4081                 if ((objp->type == OBJ_WEAPON) && (sobjp-Objects != objp->parent)) {
4082                         float           dot, tts;
4083                         // vector       psp;            //      Predicted ship position.
4084
4085                         //      Get dot and time to current ship position.
4086                         fds_aux(&dot, &tts, &sobjp->pos, dtime, objp);
4087
4088                         //      If dot and tts are in plausible range, do more expensive stuff.
4089                         if (dot > 0.98f) {
4090 //                              float   dot_from_sobjp;
4091                                 vector  v2e;
4092
4093                                 vm_vec_normalized_dir(&v2e, &objp->pos, &sobjp->pos);
4094 //                              dot_from_sobjp = vm_vec_dot(&sobjp->orient.v.fvec, &v2e);
4095 //                              if (dot_from_sobjp >= dot_threshhold)
4096                                         if (tts < dtime) {
4097                                                 if (tts < best_tts) {
4098                                                         best_tts = tts;
4099                                                         best_objp = objp;
4100                                                 }
4101                                         }
4102                         }
4103                 }
4104         }
4105
4106         *atime = best_tts;
4107
4108         if (best_objp != NULL)
4109                 return best_objp-Objects;
4110         else
4111                 return -1;
4112 }
4113 */
4114
4115 //      --------------------------------------------------------------------------
4116 void ai_set_positions(object *pl_objp, object *en_objp, ai_info *aip, vector *player_pos, vector *enemy_pos)
4117 {
4118         *player_pos = pl_objp->pos;
4119
4120         if (aip->next_predict_pos_time > Missiontime) {
4121                 *enemy_pos = aip->last_predicted_enemy_pos;
4122         } else {
4123                 *enemy_pos = en_objp->pos;
4124
4125                 aip->next_predict_pos_time = Missiontime + Skill_level_delay[Game_skill_level];
4126                 aip->last_predicted_enemy_pos = *enemy_pos;
4127         }
4128
4129
4130 }
4131
4132 //      --------------------------------------------------------------------------
4133 int find_nearest_waypoint(object *objp)
4134 {
4135         int     i;
4136         float   dist, min_dist, dot;
4137         int     min_ind;
4138         int     wp_listnum;
4139         waypoint_list   *wpl;
4140
4141         wp_listnum = Ai_info[Ships[objp->instance].ai_index].wp_list;
4142         SDL_assert(wp_listnum > 0);
4143         wpl = &Waypoint_lists[wp_listnum];
4144
4145         min_dist = 999999.0f;
4146         min_ind = -1;
4147
4148         for (i=0; i<wpl->count; i++) {
4149                 dist = vm_vec_dist_quick(&objp->pos, &wpl->waypoints[i]);
4150                 dot = vm_vec_dot_to_point(&objp->orient.v.fvec, &objp->pos, &wpl->waypoints[i]);
4151                 dist = (float) (dist * (1.25 - dot));
4152                 if (dist < min_dist) {
4153                         min_dist = dist;
4154                         min_ind = i;
4155                 }
4156         }
4157
4158         SDL_assert(min_ind != -1);
4159
4160         return min_ind;
4161 }
4162
4163 //      Given an ai_info struct, by reading current goal and path information,
4164 //      extract base path information and return in pmp and pmpv.
4165 //      Return true if found, else return false.
4166 //      false means the current point is not on the original path.
4167 int get_base_path_info(int path_cur, int goal_objnum, model_path **pmp, mp_vert **pmpv)
4168 {
4169         pnode                   *pn = &Path_points[path_cur];
4170         ship_info       *sip = &Ship_info[Ships[Objects[goal_objnum].instance].ship_info_index];
4171         polymodel       *pm = model_get(sip->modelnum);
4172         //static        int     debug_last_index = -1;  // no longer used
4173         *pmpv = NULL;
4174         *pmp = NULL;
4175
4176         if (pn->path_num != -1) {
4177                 *pmp = &pm->paths[pn->path_num];
4178                 if (pn->path_index != -1)
4179                         *pmpv = &(*pmp)->verts[pn->path_index];
4180                 else
4181                         return 0;
4182         } else
4183                 return 0;
4184
4185 /*      if (debug_last_index != *pmpv-(*pmp)->verts) {
4186                 debug_last_index = *pmpv-(*pmp)->verts;
4187                 nprintf(("AI", "Point %i has %i turrets: ", *pmpv-(*pmp)->verts, (*pmpv)->nturrets));
4188                 for (int i=0; i<(*pmpv)->nturrets; i++) {
4189                         nprintf(("AI", "%i ", (*pmpv)->turret_ids[i]));
4190                 }
4191                 nprintf(("AI", "\n"));
4192         }
4193 */
4194         return 1;
4195 }
4196
4197 //      Modify, in place, the points in a global model path.
4198 //      Only modify those points that are defined in the model path.  Don't modify the
4199 //      leadin points, such as those that are necessary to get the model on the path.
4200 void modify_model_path_points(object *objp)
4201 {       
4202         ai_info         *aip = &Ai_info[Ships[objp->instance].ai_index];
4203         object          *mobjp = &Objects[aip->path_objnum];
4204         ship_info       *osip = &Ship_info[Ships[mobjp->instance].ship_info_index];
4205         polymodel       *pm = model_get(osip->modelnum);
4206         pnode                   *pnp;
4207         int                     path_num, dir;
4208
4209         SDL_assert((aip->path_start >= 0) && (aip->path_start < MAX_PATH_POINTS));
4210
4211         pnp = &Path_points[aip->path_start];
4212         while ((pnp->path_index == -1) && (pnp-Path_points - aip->path_start < aip->path_length))
4213                 pnp++;
4214
4215         path_num = pnp->path_num;
4216         SDL_assert((path_num >= 0) && (path_num < pm->n_paths));
4217         
4218         SDL_assert(pnp->path_index != -1);      //      If this is -1, that means we never found the model path points
4219
4220         dir = 1;
4221         if ( aip->ai_flags & AIF_USE_EXIT_PATH ) {
4222                 dir = -1;
4223         }
4224
4225         copy_xlate_model_path_points(mobjp, &pm->paths[path_num], dir, pm->paths[path_num].nverts, path_num, pnp);
4226 }
4227
4228 //      Return an indication of the distance between two matrices.
4229 //      This is the sum of the distances of their dot products from 1.0f.
4230 float ai_matrix_dist(matrix *mat1, matrix *mat2)
4231 {
4232         float   t;
4233
4234         t =  1.0f - vm_vec_dot(&mat1->v.fvec, &mat2->v.fvec);
4235         t += 1.0f - vm_vec_dot(&mat1->v.uvec, &mat2->v.uvec);
4236         t += 1.0f - vm_vec_dot(&mat1->v.rvec, &mat2->v.rvec);
4237
4238         return t;
4239 }
4240
4241
4242 //      Paths are created in absolute space, so a moving object needs to have model paths within it recreated.
4243 //      This uses the hash functions which means the slightest movement will cause a recreate, though the timestamp
4244 //      prevents this from happening too often.
4245 //      force_recreate_flag TRUE means to recreate regardless of timestamp.
4246 //      Returns TRUE if path recreated.
4247 float maybe_recreate_path(object *objp, ai_info *aip, int force_recreate_flag)
4248 {
4249         int     hashval;
4250
4251         SDL_assert(&Ai_info[Ships[objp->instance].ai_index] == aip);
4252
4253         if ((aip->mode == AIM_BAY_EMERGE) || (aip->mode == AIM_BAY_DEPART))
4254                 if ((OBJ_INDEX(objp) % 4) == (Framecount % 4))
4255                         force_recreate_flag = 1;
4256
4257         //      If no path, that means we don't need one.
4258         if (aip->path_start == -1)
4259                 return 0.0f;
4260
4261         // AL 11-12-97: If AIF_USE_STATIC_PATH is set, don't try to recreate.  This is needed when ships
4262         //                                  emerge from fighter bays.  We don't need to recreate the path.. and in case the 
4263         //              parent ship dies, we still want to be able to continue on the path
4264         if ( aip->ai_flags & AIF_USE_STATIC_PATH ) 
4265                 return 0.0f;
4266
4267         if (force_recreate_flag || timestamp_elapsed(aip->path_next_create_time)) {
4268                 object  *path_objp;
4269
4270                 path_objp = &Objects[aip->path_objnum];
4271
4272                 if ((hashval = create_object_hash(path_objp)) != aip->path_goal_obj_hash) {
4273                         float dist;
4274                         
4275                         dist = vm_vec_dist_quick(&path_objp->pos, &aip->path_create_pos);
4276                         dist += ai_matrix_dist(&path_objp->orient, &aip->path_create_orient) * 25.0f;
4277
4278                         if (force_recreate_flag || (dist > 2.0f)) {
4279                                 aip->path_next_create_time = timestamp(1000);   //      Update again in as little as 1000 milliseconds, ie 1 second.
4280                                 aip->path_goal_obj_hash = hashval;
4281                                 modify_model_path_points(objp);
4282
4283                                 aip->path_create_pos = path_objp->pos;
4284                                 aip->path_create_orient = path_objp->orient;
4285                                 
4286                                 return dist;
4287                         }
4288                 }
4289         }
4290
4291         return 0.0f;
4292 }
4293
4294 //      Set acceleration for ai_dock().
4295 void set_accel_for_docking(object *objp, ai_info *aip, float dot, float dot_to_next, float dist_to_next, float dist_to_goal, ship_info *sip)
4296 {
4297         float prev_dot_to_goal = aip->prev_dot_to_goal;
4298         
4299         aip->prev_dot_to_goal = dot;
4300
4301         if (objp->phys_info.speed < 0.0f) {
4302                 accelerate_ship(aip, 1.0f/32.0f);
4303         } else if ((prev_dot_to_goal-dot) > 0.01) {
4304                 if (prev_dot_to_goal > dot + 0.05f) {
4305                         accelerate_ship(aip, 0.0f);
4306                 } else {
4307                         change_acceleration(aip, -1.0f);        //      -1.0f means subtract off flFrametime from acceleration value in 0.0..1.0
4308                 }
4309         } else {
4310                 if ((aip->mode == AIM_DOCK) && (dist_to_next < 150.0f) && (aip->path_start + aip->path_length - 2 == aip->path_cur)) {
4311                         set_accel_for_target_speed(objp, sip->max_speed * SDL_max(dist_to_next/500.0f, 1.0f));
4312                         //mprintf(("dist = %7.3f, speed = %7.3f\n", dist_to_next, objp->phys_info.speed));
4313                 } else if ((dot_to_next >= dot * .9) || (dist_to_next > 100.0f)) {
4314                         if (dist_to_goal > 200.0f)
4315                                 set_accel_for_target_speed(objp, sip->max_speed * (dot + 1.0f) / 2.0f);
4316                         else {
4317                                 float   xdot;
4318
4319                                 xdot = (dot_to_next + dot)/2.0f;
4320                                 if (xdot < 0.0f)
4321                                         xdot = 0.0f;
4322
4323                                 // AL: if following a path not in dock mode, move full speed
4324                                 if (( aip->mode != AIM_DOCK ) && (dot > 0.9f)) {
4325                                         set_accel_for_target_speed(objp, sip->max_speed*dot*dot*dot);
4326                                 } else {
4327                                         if ((aip->path_cur - aip->path_start < aip->path_length-2) && (dist_to_goal < 2*objp->radius)) {
4328                                                 //nprintf(("AI", "Target speed = %7.3f\n", dist_to_goal/8.0f));
4329                                                 set_accel_for_target_speed(objp, dist_to_goal/8.0f + 2.0f);
4330                                         } else {
4331                                                 set_accel_for_target_speed(objp, sip->max_speed * (2*xdot + 0.25f)/4.0f);
4332                                         }
4333                                 }
4334                         }
4335                 } else {
4336                         float   xdot;
4337
4338                         xdot = SDL_max(dot_to_next, 0.1f);
4339                         if ( aip->mode != AIM_DOCK ) {
4340                                 set_accel_for_target_speed(objp, sip->max_speed);
4341                         } else {
4342                                 float   speed;
4343                                 if ((aip->path_cur - aip->path_start < aip->path_length-2) && (dist_to_goal < 2*objp->radius)) {
4344                                         speed = dist_to_goal/8.0f + 2.0f;
4345                                 } else if (dist_to_goal < 4*objp->radius + 50.0f) {
4346                                         speed = dist_to_goal/4.0f + 4.0f;
4347                                 } else {
4348                                         speed = sip->max_speed * (3*xdot + 1.0f)/4.0f;
4349                                 }
4350                                 if (aip->mode == AIM_DOCK) {
4351                                         speed = speed * 2.0f + 1.0f;
4352                                         if (aip->goal_objnum != -1) {
4353                                                 speed += Objects[aip->goal_objnum].phys_info.speed;
4354                                         }
4355                                 }
4356
4357                                 set_accel_for_target_speed(objp, speed);
4358                         }
4359                 }
4360         }
4361 }
4362
4363 //      --------------------------------------------------------------------------
4364 //      Follow a path associated with a large object, such as a capital ship.
4365 //      The points defined on the path are in the object's reference frame.
4366 //      The object of interest is goal_objnum.
4367 //      The paths are defined in the model.  The path of interest is wp_list.
4368 //      The next goal point in the path is wp_index.
4369 //      wp_flags contain special information specific to the path.
4370
4371 // The path vertices are defined by model_path structs:
4372 //              typedef struct model_path {
4373 //                      char            name[MAX_NAME_LEN];                                     // name of the subsystem.  Probably displayed on HUD
4374 //                      int             nverts;
4375 //                      vector  *verts;
4376 //              } model_path;
4377
4378 //      The polymodel struct for the object contains the following:
4379 //              int                     n_paths;
4380 //              model_path      *paths;
4381
4382 //      Returns distance to goal point.
4383 float ai_path()
4384 {
4385         int             num_points;
4386         float           dot, dist_to_goal, dist_to_next, dot_to_next;
4387         ship            *shipp = &Ships[Pl_objp->instance];
4388         ship_info       *sip = &Ship_info[shipp->ship_info_index];
4389         ai_info *aip;
4390         vector  nvel_vec;
4391         float           mag;//, prev_dot_to_goal;
4392         vector  temp_vec, *slop_vec;
4393         object  *gobjp;
4394         vector  *cvp, *nvp, next_vec, gcvp, gnvp;               //      current and next vertices in global coordinates.
4395
4396         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
4397
4398         SDL_assert(aip->goal_objnum != -1);
4399         SDL_assert(Objects[aip->goal_objnum].type == OBJ_SHIP);
4400
4401         gobjp = &Objects[aip->goal_objnum];
4402
4403 #ifndef NDEBUG
4404         polymodel *pm = model_get( Ships[gobjp->instance].modelnum );
4405         SDL_assert(pm->n_paths > 0);
4406 #endif
4407
4408         if (aip->path_start == -1) {
4409                 int path_num;
4410                 path_num = ai_return_path_num_from_dockbay(&Objects[aip->goal_objnum], aip->dockee_index);
4411                 SDL_assert(aip->goal_objnum >= 0 && aip->goal_objnum < MAX_OBJECTS);
4412                 ai_find_path(Pl_objp, aip->goal_objnum, path_num, 0);
4413         }
4414
4415         // nprintf(("AI", "Frame: %i, Path index = %i/%i\n", AI_FrameCount, aip->path_cur-aip->path_start, aip->path_length));
4416
4417         maybe_recreate_path(Pl_objp, aip, 0);
4418
4419         num_points = aip->path_length;
4420
4421         //      Set cvp and nvp as pointers to current and next vertices of interest on path.
4422         cvp = &Path_points[aip->path_cur].pos;
4423         if ((aip->path_cur + aip->path_dir - aip->path_start < num_points) || (aip->path_cur + aip->path_dir < aip->path_start))
4424                 nvp = &Path_points[aip->path_cur + aip->path_dir].pos;
4425         else {
4426                 //      If this is 0, then path length must be 1 which means we have no direction!
4427                 SDL_assert((aip->path_cur - aip->path_dir >= aip->path_start) && (aip->path_cur - aip->path_dir - aip->path_start < num_points));
4428                 //      Cleanup for above SDL_assert() which we hit too near release. -- MK, 5/24/98.
4429                 if (aip->path_cur - aip->path_dir - aip->path_start >= num_points) {
4430                         if (aip->path_dir == 1)
4431                                 aip->path_cur = aip->path_start;
4432                         else
4433                                 aip->path_cur = aip->path_start + num_points - 1;
4434                 }
4435
4436                 vector  delvec;
4437                 vm_vec_sub(&delvec, cvp, &Path_points[aip->path_cur - aip->path_dir].pos);
4438                 vm_vec_normalize(&delvec);
4439                 vm_vec_scale_add(&next_vec, cvp, &delvec, 10.0f);
4440                 nvp = &next_vec;
4441         }
4442
4443         //      Interrupt if can't get to current goal point.  Debug only.
4444 /*      if (pp_collide(&Pl_objp->pos, cvp, gobjp, Pl_objp->radius)) {
4445                 Int3();
4446         }
4447 */
4448         //      See if can reach next point (as opposed to current point)
4449         //      However, don't do this if docking and next point is last point.
4450         //      That is, we don't want to pursue the last point under control of the
4451         //      path code.  In docking, this is a special hack.
4452         if ((aip->mode != AIM_DOCK) || ((aip->path_cur-aip->path_start) < num_points - 2)) {
4453                 if ((aip->path_cur + aip->path_dir > aip->path_start) && (aip->path_cur + aip->path_dir < aip->path_start + num_points-2)) {
4454                         if ( timestamp_elapsed(aip->path_next_check_time)) {
4455                                 aip->path_next_check_time = timestamp( 3000 );
4456                                 if (!pp_collide(&Pl_objp->pos, nvp, gobjp, 1.1f * Pl_objp->radius)) {
4457                                         cvp = nvp;
4458                                         aip->path_cur += aip->path_dir;
4459                                         nvp = &Path_points[aip->path_cur].pos;
4460                                         //nprintf(("AI", "Reach: Advancing from point %i to %i of %i points.\n", aip->path_cur-aip->path_dir, aip->path_cur, num_points));
4461                                 }
4462                         }
4463                 }
4464         }
4465
4466         gcvp = *cvp;
4467         gnvp = *nvp;
4468
4469         dist_to_goal = vm_vec_dist_quick(&Pl_objp->pos, &gcvp);
4470         dist_to_next = vm_vec_dist_quick(&Pl_objp->pos, &gnvp);
4471         //      Can't use fvec, need to use velocity vector because we aren't necessarily
4472         //      moving in the direction we're facing.
4473
4474 //      if (IS_VEC_NULL(&Pl_objp->phys_info.vel)) {
4475         if ( vm_vec_mag_quick(&Pl_objp->phys_info.vel) < AICODE_SMALL_MAGNITUDE ) {
4476                 mag = 0.0f;
4477                 vm_vec_zero(&nvel_vec);
4478         } else
4479                 mag = vm_vec_copy_normalize(&nvel_vec, &Pl_objp->phys_info.vel);
4480
4481         //      If moving not-very-slowly and sliding, then try to slide at goal, rather than
4482         //      point at goal.
4483         slop_vec = NULL;
4484         if (mag < 1.0f)
4485                 nvel_vec = Pl_objp->orient.v.fvec;
4486         else if (mag > 5.0f) {
4487                 float   nv_dot;
4488                 nv_dot = vm_vec_dot(&Pl_objp->orient.v.fvec, &nvel_vec);
4489                 if ((nv_dot > 0.5f) && (nv_dot < 0.97f)) {
4490                         slop_vec = &temp_vec;
4491                         vm_vec_sub(slop_vec, &nvel_vec, &Pl_objp->orient.v.fvec);
4492                 }
4493         }
4494
4495         if (dist_to_goal > 0.1f)
4496                 ai_turn_towards_vector(&gcvp, Pl_objp, flFrametime, sip->srotation_time, slop_vec, NULL, 0.0f, 0);
4497
4498         //      Code to control speed is MUCH less forgiving in path following than in waypoint
4499         //      following.  Must be very close to path or might hit objects.
4500 //      prev_dot_to_goal = aip->prev_dot_to_goal;
4501         dot = vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, &gcvp);
4502         dot_to_next = vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, &gnvp);
4503
4504         set_accel_for_docking(Pl_objp, aip, dot, dot_to_next, dist_to_next, dist_to_goal, sip);
4505         aip->prev_dot_to_goal = dot;
4506
4507 //mprintf(("Goal index = %i, dist = %7.3f, dot = %7.3f\n", wp_index, dist_to_goal, dot));
4508
4509         //      If moving at a non-tiny velocity, detect attaining path point by its being close to
4510         //      line between previous and current object location.
4511         if ((dist_to_goal < MIN_DIST_TO_WAYPOINT_GOAL) || (vm_vec_dist_quick(&Pl_objp->last_pos, &Pl_objp->pos) > 0.1f)) {
4512                 vector  nearest_point;
4513                 float           r, min_dist_to_goal;
4514
4515                 r = find_nearest_point_on_line(&nearest_point, &Pl_objp->last_pos, &Pl_objp->pos, &gcvp);
4516
4517                 //      Set min_dist_to_goal = how close must be to waypoint to pick next one.
4518                 //      If docking and this is the second last waypoint, must be very close.
4519                 if ((aip->mode == AIM_DOCK) && (aip->path_cur >= aip->path_length-2))
4520                         min_dist_to_goal = MIN_DIST_TO_WAYPOINT_GOAL;
4521                 else
4522                         min_dist_to_goal = MIN_DIST_TO_WAYPOINT_GOAL + Pl_objp->radius;
4523
4524                 if ( (vm_vec_dist_quick(&Pl_objp->pos, &gcvp) < min_dist_to_goal) ||
4525                         (((r >= 0.0f) && (r <= 1.0f)) && (vm_vec_dist_quick(&nearest_point, &gcvp) < (MIN_DIST_TO_WAYPOINT_GOAL + Pl_objp->radius)))) {
4526                         aip->path_cur += aip->path_dir;
4527                         //nprintf(("AI", " Near: Advancing from point %i to %i of %i points.\n", aip->path_cur-aip->path_dir, aip->path_cur, num_points));
4528                         if (((aip->path_cur - aip->path_start) > (num_points+1)) || (aip->path_cur < aip->path_start)) {
4529                                 SDL_assert(aip->mode != AIM_DOCK);              //      If docking, should never get this far, getting to last point handled outside ai_path()
4530                                 aip->path_dir = -aip->path_dir;
4531 //                              aip->path_cur += aip->path_dir;
4532                         }
4533                 }
4534         }
4535
4536         return dist_to_goal;
4537 }
4538
4539 void update_min_max(float val, float *min, float *max)
4540 {
4541         if (val < *min)
4542                 *min = val;
4543         else if (val > *max)
4544                 *max = val;
4545 }
4546
4547 //      Stuff bounding box of all enemy objects within "range" units of object *my_objp.
4548 //      Stuff ni min_vec and max_vec.
4549 //      Return value: Number of enemy objects in bounding box.
4550 int get_enemy_team_range(object *my_objp, float range, int enemy_team_mask, vector *min_vec, vector *max_vec)
4551 {
4552         object  *objp;
4553         ship_obj        *so;
4554         int             count = 0;
4555
4556         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
4557                 objp = &Objects[so->objnum];
4558                 if (Ships[objp->instance].team & enemy_team_mask) {
4559                         if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER | SIF_CRUISER | SIF_CAPITAL | SIF_SUPERCAP | SIF_DRYDOCK | SIF_CORVETTE | SIF_AWACS | SIF_GAS_MINER))
4560                                 if (vm_vec_dist_quick(&my_objp->pos, &objp->pos) < range) {
4561                                         if (count == 0) {
4562                                                 *min_vec = objp->pos;
4563                                                 *max_vec = objp->pos;
4564                                                 count++;
4565                                         } else {
4566                                                 update_min_max(objp->pos.xyz.x, &min_vec->xyz.x, &max_vec->xyz.x);
4567                                                 update_min_max(objp->pos.xyz.y, &min_vec->xyz.y, &max_vec->xyz.y);
4568                                                 update_min_max(objp->pos.xyz.z, &min_vec->xyz.z, &max_vec->xyz.z);
4569                                         }
4570                                 }
4571
4572                 }
4573         }
4574
4575         return count;
4576 }
4577
4578 //      Pick a relatively safe spot for objp to fly to.
4579 //      Problem:
4580 //              Finds a spot away from any enemy within a bounding box.
4581 //              Doesn't verify that "safe spot" is not near some other enemy.
4582 void ai_safety_pick_spot(object *objp)
4583 {
4584         int             objnum;
4585         int             enemy_team_mask;
4586         vector  min_vec, max_vec;
4587         vector  vec_to_center, center;
4588         vector  goal_pos;
4589
4590         objnum = OBJ_INDEX(objp);
4591
4592         enemy_team_mask = get_enemy_team_mask(objnum);
4593
4594         if (get_enemy_team_range(objp, 1000.0f, enemy_team_mask, &min_vec, &max_vec)) {
4595                 vm_vec_avg(&center, &min_vec, &max_vec);
4596                 vm_vec_normalized_dir(&vec_to_center, &center, &objp->pos);
4597
4598                 vm_vec_scale_add(&goal_pos, &center, &vec_to_center, 2000.0f);
4599         } else
4600                 vm_vec_scale_add(&goal_pos, &objp->pos, &objp->orient.v.fvec, 100.0f);
4601
4602         Ai_info[Ships[objp->instance].ai_index].goal_point = goal_pos;
4603 }
4604
4605 //      Fly to desired safe point.
4606 // Returns distance to that point.
4607 float ai_safety_goto_spot(object *objp)
4608 {
4609         float   dot, dist;
4610         ai_info *aip;
4611         vector  vec_to_goal;
4612         ship_info       *sip;
4613         float   dot_val;
4614
4615         sip = &Ship_info[Ships[objp->instance].ship_info_index];
4616
4617         aip = &Ai_info[Ships[objp->instance].ai_index];
4618         dist = vm_vec_normalized_dir(&vec_to_goal, &aip->goal_point, &objp->pos);
4619         dot = vm_vec_dot(&vec_to_goal, &objp->orient.v.fvec);
4620
4621         dot_val = (1.1f + dot) / 2.0f;
4622         if (dist > 200.0f) {
4623                 set_accel_for_target_speed(objp, sip->max_speed * dot_val);
4624         } else
4625                 set_accel_for_target_speed(objp, sip->max_speed * dot_val * (dist/200.0f + 0.2f));
4626
4627         return dist;
4628 }
4629
4630 void ai_safety_circle_spot(object *objp)
4631 {
4632         vector  goal_point;
4633         ship_info       *sip;
4634         float           dot;
4635
4636         sip = &Ship_info[Ships[objp->instance].ship_info_index];
4637
4638         goal_point = Ai_info[Ships[objp->instance].ai_index].goal_point;
4639         dot = turn_towards_tangent(objp, &goal_point, 250.0f);  //      Increased from 50 to 250 to make circling not look so wacky.
4640
4641         set_accel_for_target_speed(objp, 0.5f * (1.0f + dot) * sip->max_speed/4.0f);
4642
4643 //      float dist = vm_vec_dist_quick(&goal_point, &Pl_objp->pos);
4644 //      nprintf(("AI", "Ship %s circling %7.3f %7.3f %7.3f.  Distance = %7.3f\n", Ships[Pl_objp->instance].ship_name, goal_point.xyz.x, goal_point.xyz.y, goal_point.xyz.z, dist));
4645
4646 }
4647
4648 //      --------------------------------------------------------------------------
4649 void ai_safety()
4650 {
4651         ai_info *aip;
4652
4653         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
4654
4655         switch (aip->submode) {
4656         case AISS_1:
4657                 ai_safety_pick_spot(Pl_objp);
4658                 aip->submode = AISS_2;
4659                 aip->submode_start_time = Missiontime;
4660                 break;
4661         case AISS_1a:   //      Pick a safe point because we just got whacked!
4662                 Int3();
4663                 break;
4664         case AISS_2:
4665                 if (ai_safety_goto_spot(Pl_objp) < 25.0f) {
4666                         aip->submode = AISS_3;
4667                         aip->submode_start_time = Missiontime;
4668                 }
4669                 break;
4670         case AISS_3:
4671                 ai_safety_circle_spot(Pl_objp);
4672                 break;
4673         default:
4674                 Int3();         //      Illegal submode for ai_safety();
4675                 break;
4676         }
4677 }
4678
4679 //      --------------------------------------------------------------------------
4680 //      make Pl_objp fly waypoints.
4681 void ai_waypoints()
4682 {
4683         int             wp_index;
4684         vector  *wp_cur, *wp_next;
4685         float           dot, dist_to_goal;//, dot_to_next;
4686         ship            *shipp = &Ships[Pl_objp->instance];
4687         ship_info       *sip = &Ship_info[shipp->ship_info_index];
4688         waypoint_list   *wpl;
4689         ai_info *aip;
4690         vector  nvel_vec;
4691         float           mag;
4692         float           prev_dot_to_goal;
4693         vector  temp_vec;
4694         vector  *slop_vec;
4695
4696         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
4697
4698         wp_index = aip->wp_index;
4699
4700         if (wp_index == -1) {
4701                 ai_start_waypoints(Pl_objp, 0, WPF_REPEAT);
4702                 wp_index = aip->wp_index;
4703                 aip->wp_dir = 1;
4704         }
4705
4706         wpl = &Waypoint_lists[Ai_info[Ships[Pl_objp->instance].ai_index].wp_list];
4707
4708         SDL_assert(wpl->count); // What? Is this zero? Probably wp_index never got initialized!
4709
4710         wp_cur = &wpl->waypoints[wp_index];
4711         wp_next = &wpl->waypoints[(wp_index+1) % wpl->count];
4712
4713         dist_to_goal = vm_vec_dist_quick(&Pl_objp->pos, wp_cur);
4714
4715         //      Can't use fvec, need to use velocity vector because we aren't necessarily
4716         //      moving in the direction we're facing.
4717         // AL 23-3-98: Account for very small velocities by checking result of vm_vec_mag().
4718         //                                      If we don't vm_vec_copy_normalize() will think it is normalizing a null vector.
4719 //      if (IS_VEC_NULL(&Pl_objp->phys_info.vel)) {
4720         if ( vm_vec_mag_quick(&Pl_objp->phys_info.vel) < AICODE_SMALL_MAGNITUDE ) {
4721                 mag = 0.0f;
4722                 vm_vec_zero(&nvel_vec);
4723         } else {
4724                 mag = vm_vec_copy_normalize(&nvel_vec, &Pl_objp->phys_info.vel);
4725         }
4726
4727         //      If moving not-very-slowly and sliding, then try to slide at goal, rather than
4728         //      point at goal.
4729         slop_vec = NULL;
4730         if (mag < 1.0f) {
4731                 nvel_vec = Pl_objp->orient.v.fvec;
4732         } else if (mag > 5.0f) {
4733                 float   nv_dot;
4734                 nv_dot = vm_vec_dot(&Pl_objp->orient.v.fvec, &nvel_vec);
4735                 if ((nv_dot > 0.5f) && (nv_dot < 0.97f)) {
4736                         slop_vec = &temp_vec;
4737                         vm_vec_sub(slop_vec, &nvel_vec, &Pl_objp->orient.v.fvec);
4738                 }
4739         }
4740
4741         //      If a wing leader, take turns more slowly, based on size of wing.
4742         int     scale;
4743
4744         if (Ai_info[Ships[Pl_objp->instance].ai_index].wing >= 0) {
4745                 scale = Wings[Ai_info[Ships[Pl_objp->instance].ai_index].wing].current_count;
4746                 scale = (int) ((scale+1)/2);
4747         } else {
4748                 scale = 1;
4749         }
4750
4751         if (dist_to_goal > 0.1f) {
4752                 ai_turn_towards_vector(wp_cur, Pl_objp, flFrametime, sip->srotation_time*3.0f*scale, slop_vec, NULL, 0.0f, 0);
4753         }
4754
4755         prev_dot_to_goal = aip->prev_dot_to_goal;
4756         dot = vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, wp_cur);
4757         /*dot_to_next =*/ vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, wp_next);
4758         aip->prev_dot_to_goal = dot;
4759
4760         //      If there is no next point on the path, don't care about dot to next.
4761 //      if (wp_index + 1 >= wpl->count) {
4762 //              dot_to_next = dot;
4763 //      }
4764
4765         // nprintf(("AI", "Wp #%i, dot = %6.3f, next dot = %6.3f, dist = %7.2f\n", wp_index, dot, dot_to_next, dist_to_goal));
4766
4767         if (Pl_objp->phys_info.speed < 0.0f) {
4768                 accelerate_ship(aip, 1.0f/32);
4769         } else if (prev_dot_to_goal > dot+0.01f) {
4770                 //      We are further from pointing at our goal this frame than last frame, so slow down.
4771                 set_accel_for_target_speed(Pl_objp, Pl_objp->phys_info.speed * 0.95f);
4772         } else if (dist_to_goal < 100.0f) {
4773                 float slew_dot = vm_vec_dot(&Pl_objp->orient.v.fvec, &nvel_vec);
4774                 if (fl_abs(slew_dot) < 0.9f) {
4775                         accelerate_ship(aip, 0.0f);
4776                 } else if (dot < 0.88f + 0.1f*(100.0f - dist_to_goal)/100.0f) {
4777                         accelerate_ship(aip, 0.0f);
4778                 } else {
4779                         accelerate_ship(aip, 0.5f * dot * dot);
4780                 }
4781         } else {
4782                 float   dot1;
4783                 if (dist_to_goal < 250.0f) {
4784                         dot1 = dot*dot*dot;                             //      Very important to be pointing towards goal when nearby.  Note, cubing preserves sign.
4785                 } else {
4786                         if (dot > 0.0f) {
4787                                 dot1 = dot*dot;
4788                         } else {
4789                                 dot1 = dot;
4790                         }
4791                 }
4792
4793                 if (dist_to_goal > 100.0f + Pl_objp->radius * 2) {
4794                         if (dot < 0.2f) {
4795                                 dot1 = 0.2f;
4796                         }
4797                 }
4798
4799                 if (sip->flags & SIF_SMALL_SHIP) {
4800                         set_accel_for_target_speed(Pl_objp, dot1 * dist_to_goal/5.0f);
4801                 } else {
4802                         set_accel_for_target_speed(Pl_objp, dot1 * dist_to_goal/10.0f);
4803                 }
4804         }
4805
4806         //      Make sure not travelling too fast for someone to keep up.
4807         float   max_allowed_speed = 9999.9f;
4808
4809         if (shipp->wingnum != -1) {
4810                 max_allowed_speed = 0.9f * get_wing_lowest_max_speed(Pl_objp);
4811         }
4812
4813         // check if waypoint speed cap is set and adjust max speed
4814         if (aip->waypoint_speed_cap > 0) {
4815                 max_allowed_speed = (float) aip->waypoint_speed_cap;
4816         }
4817
4818         if (aip->prev_accel * shipp->current_max_speed > max_allowed_speed) {
4819                 accelerate_ship(aip, max_allowed_speed / shipp->current_max_speed);
4820         }
4821
4822         if (vm_vec_dist_quick(&Pl_objp->last_pos, &Pl_objp->pos) > 0.1f) {
4823                 vector  nearest_point;
4824                 float           r;
4825
4826                 r = find_nearest_point_on_line(&nearest_point, &Pl_objp->last_pos, &Pl_objp->pos, wp_cur);
4827
4828                 if ( (vm_vec_dist_quick(&Pl_objp->pos, wp_cur) < (MIN_DIST_TO_WAYPOINT_GOAL + fl_sqrt(Pl_objp->radius) + vm_vec_dist_quick(&Pl_objp->pos, &Pl_objp->last_pos))) ||
4829                         (((r >= 0.0f) && (r <= 1.0f)) && (vm_vec_dist_quick(&nearest_point, wp_cur) < (MIN_DIST_TO_WAYPOINT_GOAL + fl_sqrt(Pl_objp->radius))))) {
4830                         wp_index++;
4831                         if (wp_index >= wpl->count) {
4832                                 if (aip->wp_flags & WPF_REPEAT) {
4833                                         wp_index = 0;
4834                                 } else {
4835                                         int treat_as_ship;
4836
4837                                         // when not repeating waypoints -- mark the goal as done and put and entry into the mission log
4838                                         // we must be careful when dealing with wings.  A ship in a wing might be completing
4839                                         // a waypoint for for the entire wing, or it might be completing a goal for itself.  If
4840                                         // for itself and in a wing, treat the completion as we would a ship
4841                                         treat_as_ship = 1;
4842                                         if ( Ships[Pl_objp->instance].wingnum != -1 ) {
4843                                                 int type;
4844
4845                                                 // I don't think that you can fly waypoints as dynamic goals!!!
4846                                                 // -- This is legal, just stupid. -- SDL_assert( (aip->active_goal != AI_GOAL_NONE) && (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC) );
4847                                                 
4848                                                 //      Clean up from above SDL_assert, just in case we ship without fixing it.  (Encountered by JimB on 2/9/98)
4849                                                 if ( (aip->active_goal == AI_GOAL_NONE) || (aip->active_goal == AI_ACTIVE_GOAL_DYNAMIC) ) {
4850                                                         aip->mode = AIM_NONE;
4851                                                         Int3(); //      Look at the ship, find out of it's supposed to be flying waypoints. -- MK.
4852                                                 }
4853
4854                                                 type = aip->goals[aip->active_goal].type;
4855                                                 if ( (type == AIG_TYPE_EVENT_WING) || (type == AIG_TYPE_PLAYER_WING) ) {
4856                                                         treat_as_ship = 0;
4857                                                 } else {
4858                                                         treat_as_ship = 1;
4859                                                 }
4860                                         }
4861
4862                                         // if the ship is not in a wing, remove the goal and continue on
4863                                         if ( treat_as_ship ) {
4864                                                 ai_mission_goal_complete( aip );                                        // this call should reset the AI mode
4865                                                 mission_log_add_entry(LOG_WAYPOINTS_DONE, Ships[Pl_objp->instance].ship_name, wpl->name, -1 );
4866                                         } else {
4867                                                 // this ship is in a wing.  We must mark the goal as being completed for all ships
4868                                                 // in the wing.  We will also mark an entry in the log that the wing completed the goal
4869                                                 // not the individual ship.
4870                                                 ai_mission_wing_goal_complete( Ships[Pl_objp->instance].wingnum, &(aip->goals[aip->active_goal]) );
4871                                                 mission_log_add_entry( LOG_WAYPOINTS_DONE, Wings[Ships[Pl_objp->instance].wingnum].name, wpl->name, -1 );
4872                                         }
4873                                         //wp_index = wpl->count-1;
4874                                 }
4875                         }
4876
4877                         aip->wp_index = wp_index;
4878                 }
4879         }
4880 }
4881
4882 //      Make Pl_objp avoid En_objp
4883 //      Not like evading.  This is for avoiding a collision!
4884 //      Note, use sliding if available.
4885 void avoid_ship()
4886 {
4887         //      To avoid an object, turn towards right or left vector until facing away from object.
4888         //      To choose right vs. left, pick one that is further from center of avoid object.
4889         //      Keep turning away from until pointing away from ship.
4890         //      Stay in avoid mode until at least 3 enemy ship radii away.
4891
4892         //      Speed setting:
4893         //      If inside sphere, zero speed and turn towards outside.
4894         //      If outside sphere, inside 2x sphere, set speed percent of max to:
4895         //              SDL_max(away_dot, (dist-rad)/rad)
4896         //      where away_dot is dot(Pl_objp->v.fvec, vec_En_objp_to_Pl_objp)
4897
4898         vector  vec_to_enemy;
4899         float           away_dot;
4900         float           dist;
4901         ship            *shipp = &Ships[Pl_objp->instance];
4902         ship_info       *sip = &Ship_info[shipp->ship_info_index];
4903         ai_info *aip = &Ai_info[shipp->ai_index];
4904         vector  player_pos, enemy_pos;
4905
4906         // if we're avoiding a stealth ship, then we know where he is, update with no error
4907         if ( is_object_stealth_ship(En_objp) ) {
4908                 update_ai_stealth_info_with_error(aip/*, 1*/);
4909         }
4910
4911         ai_set_positions(Pl_objp, En_objp, aip, &player_pos, &enemy_pos);
4912         vm_vec_sub(&vec_to_enemy, &enemy_pos, &Pl_objp->pos);
4913
4914         dist = vm_vec_normalize(&vec_to_enemy);
4915         away_dot = -vm_vec_dot(&Pl_objp->orient.v.fvec, &vec_to_enemy);
4916         
4917         if ((sip->max_vel.xyz.x > 0.0f) || (sip->max_vel.xyz.y > 0.0f)) {
4918                 if (vm_vec_dot(&Pl_objp->orient.v.rvec, &vec_to_enemy) > 0.0f) {
4919                         AI_ci.sideways = -1.0f;
4920                 } else {
4921                         AI_ci.sideways = 1.0f;
4922                 }
4923                 if (vm_vec_dot(&Pl_objp->orient.v.uvec, &vec_to_enemy) > 0.0f) {
4924                         AI_ci.vertical = -1.0f;
4925                 } else {
4926                         AI_ci.vertical = 1.0f;
4927                 }
4928         }               
4929
4930         //nprintf(("AI", "Frame %i: Sliding: %s %s\n", Framecount, AI_ci.sideways < 0 ? "left" : "right", AI_ci.vertical < 0 ? "down" : "up" ));
4931         // nprintf(("AI", "away_dot = %6.3f, dist = %7.2f, dist/radsum = %6.3f\n", away_dot, dist, dist/(Pl_objp->radius + En_objp->radius)));
4932
4933         //      If in front of enemy, turn away from it.
4934         //      If behind enemy, try to get fully behind it.
4935         if (away_dot < 0.0f) {
4936                 turn_away_from_point(Pl_objp, &enemy_pos, Pl_objp->phys_info.speed);
4937         } else {
4938                 vector  goal_pos;
4939
4940                 vm_vec_scale_add(&goal_pos, &En_objp->pos, &En_objp->orient.v.fvec, -100.0f);
4941                 turn_towards_point(Pl_objp, &goal_pos, NULL, Pl_objp->phys_info.speed);
4942         }
4943
4944         //      Set speed.
4945         float   radsum = Pl_objp->radius + En_objp->radius;
4946
4947         if (dist < radsum)
4948                 accelerate_ship(aip, SDL_max(away_dot, 0.2f));
4949         else if (dist < 2*radsum)
4950                 accelerate_ship(aip, SDL_max(away_dot, (dist - radsum) / radsum)+0.2f);
4951         else
4952                 accelerate_ship(aip, 1.0f);
4953
4954 }
4955
4956 //      Maybe it's time to resume the previous AI mode in aip->previous_mode.
4957 //      Each type of previous_mode has its own criteria on when to resume.
4958 //      Return true if previous mode was resumed.
4959 int maybe_resume_previous_mode(object *objp, ai_info *aip)
4960 {
4961         //      Only (maybe) resume previous goal if current goal is dynamic.
4962         if (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC)
4963                 return 0;
4964
4965         if (aip->mode == AIM_EVADE_WEAPON) {
4966                 if (timestamp_elapsed(aip->mode_time) || (((aip->nearest_locked_object == -1) || (Objects[aip->nearest_locked_object].type != OBJ_WEAPON)) && (aip->danger_weapon_objnum == -1))) {
4967                         SDL_assert(aip->previous_mode != AIM_EVADE_WEAPON);
4968                         aip->mode = aip->previous_mode;
4969                         aip->submode = aip->previous_submode;
4970                         aip->submode_start_time = Missiontime;
4971                         aip->active_goal = AI_GOAL_NONE;
4972                         aip->mode_time = -1;                    //      Means do forever.
4973                         return 1;
4974                 }
4975         } else if ( aip->previous_mode == AIM_GUARD) {
4976                 if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
4977                         object  *guard_objp;
4978                         float   dist;
4979
4980                         guard_objp = &Objects[aip->guard_objnum];
4981                         dist = vm_vec_dist_quick(&guard_objp->pos, &objp->pos);
4982
4983                         //      If guarding ship is far away from guardee and enemy is far away from guardee,
4984                         //      then stop chasing and resume guarding.
4985                         if (dist > (MAX_GUARD_DIST + guard_objp->radius) * 6) {
4986                                 if ((En_objp != NULL) && (En_objp->type == OBJ_SHIP)) {
4987                                         if (vm_vec_dist_quick(&guard_objp->pos, &En_objp->pos) > (MAX_GUARD_DIST + guard_objp->radius) * 6) {
4988                                                 SDL_assert(aip->previous_mode == AIM_GUARD);
4989                                                 aip->mode = aip->previous_mode;
4990                                                 aip->submode = AIS_GUARD_PATROL;
4991                                                 aip->active_goal = AI_GOAL_NONE;
4992                                                 return 1;
4993                                         }
4994                                 }
4995                         }
4996                 }
4997         }
4998
4999         return 0;
5000
5001 }
5002
5003 //      Call this function if you want something to happen on average every N quarters of a second.
5004 //      The truth value returned by this function will be the same for any given quarter second interval.
5005 //      The value "num" is only passed in to get asynchronous behavior for different objects.
5006 //      modulus == 1 will always return true.
5007 //      modulus == 2 will return true half the time.
5008 //      modulus == 16 will return true for one quarter second interval every four seconds.
5009 int static_rand_timed(int num, int modulus)
5010 {
5011         if (modulus < 2)
5012                 return 1;
5013         else {
5014                 int     t;
5015
5016                 t = Missiontime >> 18;          //      Get time in quarters of a second
5017                 t += num;
5018
5019                 return !(t % modulus);
5020         }
5021 }
5022
5023 //      Maybe fire afterburner based on AI class
5024 int ai_maybe_fire_afterburner(object *objp, ai_info *aip)
5025 {
5026         if (aip->ai_class == 0)
5027                 return 0;               //      Lowest level never aburners away
5028         else  {
5029                 //      Maybe don't afterburner because of a potential collision with the player.
5030                 //      If not multiplayer, near player and player in front, probably don't afterburner.
5031                 if (!(Game_mode & GM_MULTIPLAYER)) {
5032                         if (Ships[objp->instance].team == Player_ship->team) {
5033                                 float   dist;
5034
5035                                 dist = vm_vec_dist_quick(&objp->pos, &Player_obj->pos) - Player_obj->radius - objp->radius;
5036                                 if (dist < 150.0f) {
5037                                         vector  v2p;
5038                                         float           dot;
5039
5040                                         vm_vec_normalized_dir(&v2p, &Player_obj->pos, &objp->pos);
5041                                         dot = vm_vec_dot(&v2p, &objp->orient.v.fvec);
5042
5043                                         if (dot > 0.0f) {
5044                                                 if (dot * dist > 50.0f)
5045                                                         return 0;
5046                                         }
5047                                 }
5048                         }
5049                 }
5050
5051                 if (aip->ai_class >= Num_ai_classes-2)
5052                         return 1;               //      Highest two levels always aburner away.
5053                 else {
5054                         return static_rand_timed(objp-Objects, Num_ai_classes - aip->ai_class);
5055                 }
5056         }
5057 }
5058
5059 //      Maybe engage afterburner after being hit by an object.
5060 void maybe_afterburner_after_ship_hit(object *objp, ai_info *aip, object *en_objp)
5061 {
5062         //      Only do if facing a little away.
5063         if (en_objp != NULL) {
5064                 vector  v2e;
5065
5066                 vm_vec_normalized_dir(&v2e, &en_objp->pos, &objp->pos);
5067                 if (vm_vec_dot(&v2e, &objp->orient.v.fvec) > -0.5f)
5068                         return;
5069         }
5070
5071         if (!( objp->phys_info.flags & PF_AFTERBURNER_ON )) {
5072                 if (ai_maybe_fire_afterburner(objp, aip)) {
5073                         afterburners_start(objp);
5074                         aip->afterburner_stop_time = Missiontime + F1_0/2;
5075                 }
5076         }
5077 }
5078
5079 //      Return true if object *objp is an instructor.
5080 //      Is an instructor if name begins INSTRUCTOR_SHIP_NAME else not.
5081 int is_instructor(object *objp)
5082 {
5083         return !SDL_strncasecmp(Ships[objp->instance].ship_name, INSTRUCTOR_SHIP_NAME, strlen(INSTRUCTOR_SHIP_NAME));
5084 }
5085
5086 //      Evade the weapon aip->danger_weapon_objnum
5087 //      If it's not valid, do a quick out.
5088 //      Evade by accelerating hard.
5089 //      If necessary, turn hard left or hard right.
5090 void evade_weapon()
5091 {
5092         object  *weapon_objp = NULL;
5093         object  *unlocked_weapon_objp = NULL, *locked_weapon_objp = NULL;
5094         vector  weapon_pos, player_pos, goal_point;
5095         vector  vec_from_enemy;
5096         float           dot_from_enemy, dot_to_enemy;
5097         float           dist;
5098         ship            *shipp = &Ships[Pl_objp->instance];
5099         ai_info *aip = &Ai_info[shipp->ai_index];
5100
5101         if (is_instructor(Pl_objp))
5102                 return;
5103
5104         //      Make sure we're actually being attacked.
5105         //      Favor locked objects.
5106         if (aip->nearest_locked_object != -1) {
5107                 if (Objects[aip->nearest_locked_object].type == OBJ_WEAPON)
5108                         locked_weapon_objp = &Objects[aip->nearest_locked_object];
5109         }
5110         
5111         if (aip->danger_weapon_objnum != -1) {
5112                 if (Objects[aip->danger_weapon_objnum].signature == aip->danger_weapon_signature) {
5113                         unlocked_weapon_objp = &Objects[aip->danger_weapon_objnum];
5114                 } else {
5115                         aip->danger_weapon_objnum = -1;         //      Signatures don't match, so no longer endangered.
5116                 }
5117         }
5118
5119         if (locked_weapon_objp != NULL) {
5120                 if (unlocked_weapon_objp != NULL) {
5121                         if (vm_vec_dist_quick(&locked_weapon_objp->pos, &Pl_objp->pos) < 1.5f * vm_vec_dist_quick(&unlocked_weapon_objp->pos, &Pl_objp->pos))
5122                                 weapon_objp = locked_weapon_objp;
5123                         else
5124                                 weapon_objp = unlocked_weapon_objp;
5125                 } else
5126                         weapon_objp = locked_weapon_objp;
5127         } else if (unlocked_weapon_objp != NULL)
5128                 weapon_objp = unlocked_weapon_objp;
5129         else {
5130                 if (aip->mode == AIM_EVADE_WEAPON)
5131                         maybe_resume_previous_mode(Pl_objp, aip);
5132                 return;
5133         }
5134
5135         SDL_assert(weapon_objp != NULL);
5136
5137         if (weapon_objp->type != OBJ_WEAPON) {
5138                 if (aip->mode == AIM_EVADE_WEAPON)
5139                         maybe_resume_previous_mode(Pl_objp, aip);
5140                 return;
5141         }
5142         
5143         weapon_pos = weapon_objp->pos;
5144         player_pos = Pl_objp->pos;
5145
5146         //      Make speed based on skill level, varying at highest skill level, which is harder to hit.
5147         accelerate_ship(aip, 1.0f);
5148
5149         dist = vm_vec_normalized_dir(&vec_from_enemy, &player_pos, &weapon_pos);
5150
5151         dot_to_enemy = -vm_vec_dot(&Pl_objp->orient.v.fvec, &vec_from_enemy);
5152         dot_from_enemy = vm_vec_dot(&weapon_objp->orient.v.fvec, &vec_from_enemy);
5153         //nprintf(("AI", "dot from enemy = %7.3f\n", dot_from_enemy));
5154
5155         //      If shot is incoming...
5156         if (dot_from_enemy < 0.3f) {
5157                 if (weapon_objp == unlocked_weapon_objp)
5158                         aip->danger_weapon_objnum = -1;
5159                 return;
5160         } else if (dot_from_enemy > 0.7f) {
5161                 if (dist < 200.0f) {
5162                         if (!( Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
5163                                 if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
5164                                         //nprintf(("AI", "Frame %i, turning on afterburner.\n", AI_FrameCount));
5165                                         afterburners_start(Pl_objp);
5166                                         aip->afterburner_stop_time = Missiontime + F1_0/2;
5167                                 }
5168                         }
5169                 }
5170
5171                 //      If we're sort of pointing towards it...
5172                 if ((dot_to_enemy < -0.5f) || (dot_to_enemy > 0.5f)) {
5173                         float   rdot;
5174
5175                         //      Turn hard left or right, depending on which gets out of way quicker.
5176                         rdot = vm_vec_dot(&Pl_objp->orient.v.rvec, &vec_from_enemy);
5177
5178                         if ((rdot < -0.5f) || (rdot > 0.5f))
5179                                 vm_vec_scale_add(&goal_point, &Pl_objp->pos, &Pl_objp->orient.v.rvec, -200.0f);
5180                         else
5181                                 vm_vec_scale_add(&goal_point, &Pl_objp->pos, &Pl_objp->orient.v.rvec, 200.0f);
5182
5183                         turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
5184                 }
5185         }
5186
5187 }
5188
5189 //      Use sliding and backwards moving to face enemy.
5190 //      (Coded 2/20/98.  Works fine, but it's hard to see how to integrate it into the AI system.
5191 //       Typically ships are moving so fast that a little sliding isn't enough to gain an advantage.
5192 //       It's currently used to avoid collisions and could be used to evade weapon fire, but the latter
5193 //       would be frustrating, I think.
5194 //       This function is currently not called.)
5195 void slide_face_ship()
5196 {
5197         ship_info       *sip;
5198
5199         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
5200
5201         //      If can't slide, return.
5202         if ((sip->max_vel.xyz.x == 0.0f) && (sip->max_vel.xyz.y == 0.0f))
5203                 return;
5204
5205         vector  goal_pos;
5206         float           dot_from_enemy;
5207         vector  vec_from_enemy, vec_to_goal;
5208         float           dist;
5209         float           up, right;
5210         ai_info         *aip;
5211
5212         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
5213
5214         dist = vm_vec_normalized_dir(&vec_from_enemy, &Pl_objp->pos, &En_objp->pos);
5215
5216         ai_turn_towards_vector(&En_objp->pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
5217
5218         dot_from_enemy = vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.fvec);
5219
5220         if (vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.rvec) > 0.0f)
5221                 right = 1.0f;
5222         else
5223                 right = -1.0f;
5224
5225         if (vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.uvec) > 0.0f)
5226                 up = 1.0f;
5227         else
5228                 up = -1.0f;
5229
5230         vm_vec_scale_add(&goal_pos, &En_objp->pos, &En_objp->orient.v.rvec, right * 200.0f);
5231         vm_vec_scale_add(&goal_pos, &En_objp->pos, &En_objp->orient.v.uvec, up * 200.0f);
5232
5233         vm_vec_normalized_dir(&vec_to_goal, &goal_pos, &Pl_objp->pos);
5234
5235         if (vm_vec_dot(&vec_to_goal, &Pl_objp->orient.v.rvec) > 0.0f)
5236                 AI_ci.sideways = 1.0f;
5237         else
5238                 AI_ci.sideways = -1.0f;
5239
5240         if (vm_vec_dot(&vec_to_goal, &Pl_objp->orient.v.uvec) > 0.0f)
5241                 AI_ci.vertical = 1.0f;
5242         else
5243                 AI_ci.vertical = -1.0f;
5244
5245         if (dist < 200.0f) {
5246                 if (dot_from_enemy < 0.7f)
5247                         accelerate_ship(aip, -1.0f);
5248                 else
5249                         accelerate_ship(aip, dot_from_enemy + 0.5f);
5250         } else {
5251                 if (dot_from_enemy < 0.7f) {
5252                         accelerate_ship(aip, 0.2f);
5253                 } else {
5254                         accelerate_ship(aip, 1.0f);
5255                 }
5256         }
5257 }
5258
5259 //      General code for handling one ship evading another.
5260 //      Problem: This code is also used for avoiding an impending collision.
5261 //      In such a case, it is not good to go to max speed, which is often good
5262 //      for a certain kind of evasion.
5263 void evade_ship()
5264 {
5265         vector  player_pos, enemy_pos, goal_point;
5266         vector  vec_from_enemy;
5267         float           dot_from_enemy;
5268         float           dist;
5269         ship            *shipp = &Ships[Pl_objp->instance];
5270         ship_info       *sip = &Ship_info[shipp->ship_info_index];
5271         ai_info *aip = &Ai_info[shipp->ai_index];
5272         float           bank_override = 0.0f;
5273
5274         ai_set_positions(Pl_objp, En_objp, aip, &player_pos, &enemy_pos);
5275
5276         //      Make speed based on skill level, varying at highest skill level, which is harder to hit.
5277         if (Game_skill_level == NUM_SKILL_LEVELS-1) {
5278                 int     rand_int;
5279                 float   accel_val;
5280
5281                 rand_int = static_rand(Pl_objp-Objects);
5282                 accel_val = (float) (((Missiontime^rand_int) >> 14) & 0x0f)/32.0f + 0.5f;
5283                 accelerate_ship(aip, accel_val);
5284                 //nprintf(("AI", "Accel value = %7.3f\n", accel_val));
5285         } else
5286                 accelerate_ship(aip, (float) (Game_skill_level+2) / (NUM_SKILL_LEVELS+1));
5287
5288         if ((Missiontime - aip->submode_start_time > F1_0/2) && (sip->afterburner_fuel_capacity > 0.0f)) {
5289                 float percent_left = 100.0f * shipp->afterburner_fuel / sip->afterburner_fuel_capacity;
5290                 if (percent_left > 30.0f + ((Pl_objp-Objects) & 0x0f)) {
5291                         afterburners_start(Pl_objp);
5292                         aip->afterburner_stop_time = Missiontime + F1_0 + static_rand(Pl_objp-Objects)/4;
5293                 }
5294         }
5295
5296         vm_vec_sub(&vec_from_enemy, &player_pos, &enemy_pos);
5297
5298         dist = vm_vec_normalize(&vec_from_enemy);
5299         dot_from_enemy = vm_vec_dot(&En_objp->orient.v.fvec, &vec_from_enemy);
5300
5301         if (dist > 250.0f) {
5302                 vector  gp1, gp2;
5303                 //      If far away from enemy, circle, going to nearer of point far off left or right wing
5304                 vm_vec_scale_add(&gp1, &enemy_pos, &En_objp->orient.v.rvec, 250.0f);
5305                 vm_vec_scale_add(&gp2, &enemy_pos, &En_objp->orient.v.rvec, -250.0f);
5306                 if (vm_vec_dist_quick(&gp1, &Pl_objp->pos) < vm_vec_dist_quick(&gp2, &Pl_objp->pos))
5307                         goal_point = gp1;
5308                 else
5309                         goal_point = gp2;
5310         } else if (dot_from_enemy < 0.1f) {
5311                 //      If already close to behind, goal is to get completely behind.
5312                 vm_vec_scale_add(&goal_point, &enemy_pos, &En_objp->orient.v.fvec, -1000.0f);
5313         } else if (dot_from_enemy > 0.9f) {
5314                 //      If enemy pointing almost right at self, and self pointing close to enemy, turn away from
5315                 vector  vec_to_enemy;
5316                 float           dot_to_enemy;
5317
5318                 vm_vec_sub(&vec_to_enemy, &enemy_pos, &player_pos);
5319
5320                 vm_vec_normalize(&vec_to_enemy);
5321                 dot_to_enemy = vm_vec_dot(&Pl_objp->orient.v.fvec, &vec_to_enemy);
5322                 if (dot_to_enemy > 0.75f) {
5323                         //      Used to go to En_objp's right vector, but due to banking while turning, that
5324                         //      caused flying in an odd spiral.
5325                         vm_vec_scale_add(&goal_point, &enemy_pos, &Pl_objp->orient.v.rvec, 1000.0f);
5326                         if (dist < 100.0f)
5327                                 bank_override = Pl_objp->phys_info.speed; 
5328                 } else {
5329                         bank_override = Pl_objp->phys_info.speed;                       //      In enemy's sights, not pointing at him, twirl away.
5330                         // nprintf(("Mike", " Do sumpin' else."));
5331                         goto evade_ship_l1;
5332                 }
5333         } else {
5334 evade_ship_l1: ;
5335                 if (aip->ai_evasion > myrand()*100.0f/32767.0f) {
5336                         int     temp;
5337                         float   scale;
5338                         float   psrandval;      //      some value close to zero to choose whether to turn right or left.
5339
5340                         psrandval = (float) (((Missiontime >> 14) & 0x0f) - 8); //      Value between -8 and 7
5341                         psrandval = psrandval/16.0f;                                                    //      Value between -1/2 and 1/2 (approx)
5342
5343                         //      If not close to behind, turn towards his right or left vector, whichever won't cross his path.
5344                         if (vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.rvec) > psrandval) {
5345                                 scale = 1000.0f;
5346                         } else {
5347                                 scale = -1000.0f;
5348                         }
5349
5350                         vm_vec_scale_add(&goal_point, &enemy_pos, &En_objp->orient.v.rvec, scale);
5351
5352                         temp = ((Missiontime >> 16) & 0x07);
5353                         temp = ((temp * (temp+1)) % 16)/2 - 4;
5354                         if ((psrandval == 0) && (temp == 0))
5355                                 temp = 3;
5356
5357                         scale = 200.0f * temp;
5358
5359                         vm_vec_scale_add2(&goal_point, &En_objp->orient.v.uvec, scale);
5360                 } else {
5361                         //      No evasion this frame, but continue with previous turn.
5362                         //      Reason: If you don't, you lose rotational momentum.  Turning every other frame,
5363                         //      and not in between results in a very slow turn because of loss of momentum.
5364                         if ((aip->prev_goal_point.xyz.x != 0.0f) || (aip->prev_goal_point.xyz.y != 0.0f) || (aip->prev_goal_point.xyz.z != 0.0f))
5365                                 goal_point = aip->prev_goal_point;
5366                         else
5367                                 vm_vec_scale_add(&goal_point, &enemy_pos, &En_objp->orient.v.rvec, 100.0f);
5368                 }
5369         }
5370
5371         // nprintf(("Mike", "Goal point = %7.1f %7.1f %7.1f\n", goal_point.xyz.x, goal_point.xyz.y, goal_point.xyz.z));
5372         turn_towards_point(Pl_objp, &goal_point, NULL, bank_override);
5373
5374         aip->prev_goal_point = goal_point;
5375 }
5376
5377 //      --------------------------------------------------------------------------
5378 //      Fly in a manner making it difficult for opponent to attack.
5379 void ai_evade()
5380 {
5381         evade_ship();
5382 }
5383
5384 /*
5385 // -------------------------------------------------------------------
5386 //      Refine predicted enemy position because enemy will move while we move
5387 //      towards predicted enemy position.
5388 //      last_delta_vec is stuffed with size of polishing in last step.  This small amount
5389 //      can be used to perturb the predicted position to make firing not be exact.
5390 //      This function will almost always undershoot actual position, assuming both ships
5391 //      are moving at constant speed.  But with even one polishing step, the error should
5392 //      be under 1%. The number of polishing steps is specified in the parameter num_polish_steps.
5393 void polish_predicted_enemy_pos(vector *predicted_enemy_pos, object *pobjp, object *eobjp, float dist_to_enemy, vector *last_delta_vec, int num_polish_steps) // Not used:, float time_to_enemy)
5394 {
5395         int     iteration;
5396         vector  player_pos = pobjp->pos;
5397         vector  enemy_pos = *predicted_enemy_pos;
5398         physics_info    *en_physp = &eobjp->phys_info;
5399         float           time_to_enemy;
5400         vector  last_predicted_enemy_pos = *predicted_enemy_pos;
5401         
5402         vm_vec_zero(last_delta_vec);
5403
5404         for (iteration=0; iteration < num_polish_steps; iteration++) {
5405                 dist_to_enemy = vm_vec_dist_quick(predicted_enemy_pos, &player_pos);
5406                 time_to_enemy = compute_time_to_enemy(dist_to_enemy, pobjp, eobjp);
5407                 vm_vec_scale_add(predicted_enemy_pos, &eobjp->pos, &eobjp->phys_info.vel, time_to_enemy);
5408                 vm_vec_sub(last_delta_vec, predicted_enemy_pos, &last_predicted_enemy_pos);
5409                 last_predicted_enemy_pos= *predicted_enemy_pos;
5410         }
5411 }
5412 */
5413
5414 /*
5415 Relevant variables are:
5416         best_dot_to_enemy               best dot product to enemy in last BEST_DOT_TIME seconds
5417         best_dot_to_time                time at which best dot occurred
5418         best_dot_from_enemy     best dot product for enemy to player in last BEST_DOT_TIME seconds
5419         best_dot_from_time      time at which best dot occurred
5420         submode_start_time      time at which we entered the current submode
5421         previous_submode                previous submode, get it?
5422 Legal submodes are:
5423         CONTINUOUS_TURN vector_id {0..3 = right, -right, up, -up}
5424         ATTACK
5425         EVADE_SQUIGGLE
5426         EVADE_BRAKE
5427 */
5428
5429 float   G_collision_time;
5430 vector  G_predicted_pos, G_fire_pos;
5431
5432 /*
5433 void show_firing_diag()
5434 {
5435         float           dot;
5436         vector  v2t;
5437         vector  pos1, pos2;
5438         float           dist;
5439
5440         if (G_collision_time == 0.0f)
5441                 return;
5442
5443         mprintf(("Fired from %5.1f, %5.1f %5.1f at time = %5.1f, predict collision in %5.2f seconds at %5.1f %5.1f %5.1f\n",
5444                 Pl_objp->pos.xyz.x, Pl_objp->pos.xyz.y, Pl_objp->pos.xyz.z, (float) Missiontime/1000.0f, G_collision_time, G_predicted_pos.xyz.x, G_predicted_pos.xyz.y, G_predicted_pos.xyz.z));
5445         vm_vec_normalized_dir(&v2t, &G_predicted_pos, &G_fire_pos);
5446         dot = vm_vec_dot(&v2t, &Pl_objp->orient.v.fvec);
5447         mprintf(("Dot of v.fvec and vector to predicted position = %10.7f (%7.3f degrees)\n", dot, acos(dot)*180.0f/3.141592654f));
5448
5449         vm_vec_scale_add(&pos1, &En_objp->pos, &En_objp->phys_info.vel, G_collision_time);
5450         vm_vec_scale_add(&pos2, &G_fire_pos, &Pl_objp->orient.v.fvec, G_collision_time*300.0f);
5451         dist = vm_vec_dist(&pos1, &pos2);
5452
5453         mprintf(("Enemy, laser pos, distance: [%5.1f %5.1f %5.1f]  [%5.1f %5.1f %5.1f]  %6.2f\n", pos1.xyz.x, pos1.xyz.y, pos1.xyz.z, pos2.xyz.x, pos2.xyz.y, pos2.xyz.z, dist));
5454 }
5455 */
5456
5457 //      If:
5458 //              flags & WIF_PUNCTURE
5459 //      Then Select a Puncture weapon.
5460 //      Else
5461 //              Select Any ol' weapon.
5462 //      Returns primary_bank index.
5463 int ai_select_primary_weapon(object *objp, object *other_objp, int flags)
5464 {
5465         ship    *shipp = &Ships[objp->instance];
5466         ship_weapon *swp = &shipp->weapons;
5467
5468         //SDL_assert( other_objp != NULL );
5469         SDL_assert( shipp->ship_info_index >= 0 && shipp->ship_info_index < MAX_SHIP_TYPES);
5470
5471         if (flags & WIF_PUNCTURE) {
5472                 if (swp->current_primary_bank >= 0) {
5473                         int     bank_index;
5474
5475                         bank_index = swp->current_primary_bank;
5476
5477                         if (Weapon_info[swp->primary_bank_weapons[bank_index]].wi_flags & WIF_PUNCTURE) {
5478                                 //nprintf(("AI", "%i: Ship %s selecting weapon %s\n", Framecount, Ships[objp->instance].ship_name, Weapon_info[swp->primary_bank_weapons[bank_index]].name));
5479                                 return swp->current_primary_bank;
5480                         }
5481                 }
5482                 for (int i=0; i<swp->num_primary_banks; i++) {
5483                         int     weapon_info_index;
5484
5485                         weapon_info_index = swp->primary_bank_weapons[i];
5486
5487                         if (weapon_info_index > -1){
5488                                 if (Weapon_info[weapon_info_index].wi_flags & WIF_PUNCTURE) {
5489                                         swp->current_primary_bank = i;
5490                                         //nprintf(("AI", "%i: Ship %s selecting weapon %s\n", Framecount, Ships[objp->instance].ship_name, Weapon_info[swp->primary_bank_weapons[i]].name));
5491                                         return i;
5492                                 }
5493                         }
5494                 }
5495                 
5496                 // AL 26-3-98: If we couldn't find a puncture weapon, pick first available weapon if one isn't active
5497                 if ( swp->current_primary_bank < 0 ) {
5498                         if ( swp->num_primary_banks > 0 ) {
5499                                 swp->current_primary_bank = 0;
5500                         }
5501                 }
5502
5503         } else {                //      Don't need to be using a puncture weapon.
5504                 if (swp->current_primary_bank >= 0) {
5505                         if (!(Weapon_info[swp->primary_bank_weapons[swp->current_primary_bank]].wi_flags & WIF_PUNCTURE)){
5506                                 return swp->current_primary_bank;
5507                         }
5508                 }
5509                 for (int i=0; i<swp->num_primary_banks; i++) {
5510                         if (swp->primary_bank_weapons[i] > -1) {
5511                                 if (!(Weapon_info[swp->primary_bank_weapons[i]].wi_flags & WIF_PUNCTURE)) {
5512                                         swp->current_primary_bank = i;
5513                                         nprintf(("AI", "%i: Ship %s selecting weapon %s\n", Framecount, Ships[objp->instance].ship_name, Weapon_info[swp->primary_bank_weapons[i]].name));
5514                                         return i;
5515                                 }
5516                         }
5517                 }
5518                 //      Wasn't able to find a non-puncture weapon.  Stick with what we have.
5519         }
5520
5521         SDL_assert( swp->current_primary_bank != -1 );          // get Alan or Allender
5522
5523         return swp->current_primary_bank;
5524 }
5525
5526 //      --------------------------------------------------------------------------
5527 //      Maybe link primary weapons.
5528 void set_primary_weapon_linkage(object *objp)
5529 {
5530         ship            *shipp;
5531         ai_info *aip;
5532
5533         shipp = &Ships[objp->instance];
5534         aip     = &Ai_info[shipp->ai_index];
5535
5536         shipp->flags &= ~SF_PRIMARY_LINKED;
5537
5538         if (Num_weapons > (int) (MAX_WEAPONS * 0.75f)) {
5539                 if (shipp->flags & SF_PRIMARY_LINKED) {
5540                         nprintf(("AI", "Frame %i, ship %s: Unlinking primaries.\n", Framecount, shipp->ship_name));
5541                 }
5542                 shipp->flags &= ~SF_PRIMARY_LINKED;
5543                 return;         //      If low on slots, don't link.
5544         }
5545
5546         shipp->flags &= ~SF_PRIMARY_LINKED;
5547
5548         // AL: ensure target is a ship!
5549         if ( Objects[aip->target_objnum].type == OBJ_SHIP ) {
5550                 // If trying to destroy a big ship (i.e., not disable/disarm), always unleash all weapons
5551                 if ( ship_get_SIF(&Ships[Objects[aip->target_objnum].instance]) & SIF_BIG_SHIP) {
5552                         if ( aip->targeted_subsys == NULL ) {
5553                                 shipp->flags |= SF_PRIMARY_LINKED;
5554                                 shipp->flags |= SF_SECONDARY_DUAL_FIRE;
5555                                 return;
5556                         }
5557                 }
5558         }
5559
5560         // AL 2-11-98: If ship has a disarm or disable goal, don't link unless both weapons are
5561         //                                      puncture weapons
5562         if ( (aip->active_goal != AI_GOAL_NONE) && (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC) ) {
5563                 if ( aip->goals[aip->active_goal].ai_mode & (AI_GOAL_DISABLE_SHIP|AI_GOAL_DISARM_SHIP) ) {
5564                         ship_weapon     *swp;
5565                         swp = &shipp->weapons;
5566                         // only continue if both primaries are puncture weapons
5567                         if ( swp->num_primary_banks == 2 ) {
5568                                 if ( !(Weapon_info[swp->primary_bank_weapons[0]].wi_flags & WIF_PUNCTURE) ) 
5569                                         return;
5570                                 if ( !(Weapon_info[swp->primary_bank_weapons[1]].wi_flags & WIF_PUNCTURE) ) 
5571                                         return;
5572                         }
5573                 }
5574         }
5575
5576         //      Don't want all ships always linking weapons at start, so asynchronize.
5577         if (Missiontime < i2f(30))
5578                 return;
5579         else if (Missiontime < i2f(120)) {
5580                 int r = static_rand((Missiontime >> 17) ^ OBJ_INDEX(objp));
5581                 if ( (r&3) != 0)
5582                         return;
5583         }
5584
5585         if (shipp->weapon_energy > Link_energy_levels_always[Game_skill_level]) {
5586                 shipp->flags |= SF_PRIMARY_LINKED;
5587         } else if (shipp->weapon_energy > Link_energy_levels_maybe[Game_skill_level]) {
5588                 if (objp->hull_strength < Ship_info[shipp->ship_info_index].initial_hull_strength/3.0f)
5589                         shipp->flags |= SF_PRIMARY_LINKED;
5590         }
5591 }
5592
5593 //      --------------------------------------------------------------------------
5594 //      Fire the current primary weapon.
5595 //      *objp is the object to fire from.
5596 void ai_fire_primary_weapon(object *objp)
5597 {
5598         ship                    *shipp = &Ships[objp->instance];
5599         ship_weapon     *swp = &shipp->weapons;
5600         ai_info         *aip;
5601         object          *enemy_objp;
5602
5603         SDL_assert( shipp->ship_info_index >= 0 && shipp->ship_info_index < MAX_SHIP_TYPES);
5604
5605         aip = &Ai_info[shipp->ai_index];
5606
5607         //      If low on slots, fire a little less often.
5608         if (Num_weapons > (int) (0.9f * MAX_WEAPONS)) {
5609                 if (frand() > 0.5f) {
5610                         nprintf(("AI", "Frame %i, %s not fire.\n", Framecount, shipp->ship_name));
5611                         return;
5612                 }
5613         }
5614
5615         if (!Ai_firing_enabled){
5616                 return;
5617         }
5618
5619         if (aip->target_objnum != -1){
5620                 enemy_objp = &Objects[aip->target_objnum];
5621         } else {
5622                 enemy_objp = NULL;
5623         }
5624
5625         if ( (swp->current_primary_bank < 0) || (swp->current_primary_bank >= swp->num_primary_banks) || timestamp_elapsed(aip->primary_select_timestamp)) {
5626                 int     flags = 0;
5627                 // AL 2-11-98: If attacking any subsystem (not just engines), use disrupter weapon
5628 //              if ((aip->targeted_subsys != NULL) && (aip->targeted_subsys->system_info->type == SUBSYSTEM_ENGINE)) {
5629                 if ( aip->targeted_subsys != NULL ) {
5630                         flags = WIF_PUNCTURE;
5631                 }
5632                 ai_select_primary_weapon(objp, enemy_objp, flags);
5633                 ship_primary_changed(shipp);    // AL: maybe send multiplayer information when AI ship changes primaries
5634                 aip->primary_select_timestamp = timestamp(5 * 1000);    //      Maybe change primary weapon five seconds from now.
5635         }
5636
5637         //      If pointing nearly at predicted collision point of target, bash orientation to be perfectly pointing.
5638         float   dot;
5639         vector  v2t;
5640
5641 //      if (!IS_VEC_NULL(&G_predicted_pos)) {
5642         if (!( vm_vec_mag_quick(&G_predicted_pos) < AICODE_SMALL_MAGNITUDE )) {
5643                 if ( !vm_vec_cmp(&G_predicted_pos, &G_fire_pos) ) {
5644                         nprintf(("Warning", "Avoid NULL vector assert.. why are G_predicted_pos and G_fire_pos the same?\n"));
5645                 } else {
5646                         vm_vec_normalized_dir(&v2t, &G_predicted_pos, &G_fire_pos);
5647                         dot = vm_vec_dot(&v2t, &objp->orient.v.fvec);
5648                         if (dot > .998629534f){ //      if within 3.0 degrees of desired heading, bash
5649                                 vm_vector_2_matrix(&objp->orient, &v2t, &objp->orient.v.uvec, NULL);
5650                         }
5651                 }
5652         }
5653
5654         //      Make sure not firing at a protected ship unless firing at a live subsystem.
5655         //      Note: This happens every time the ship tries to fire, perhaps every frame.
5656         //      Should be wrapped in a timestamp, same one that enables it to fire, but that is complicated
5657         //      by multiple banks it can fire from.
5658         if (aip->target_objnum != -1) {
5659                 object  *tobjp = &Objects[aip->target_objnum];
5660                 if (tobjp->flags & OF_PROTECTED) {
5661                         if (aip->targeted_subsys != NULL) {
5662                                 int     type;
5663
5664                                 type = aip->targeted_subsys->system_info->type;
5665                                 if (ship_get_subsystem_strength(&Ships[tobjp->instance], type) == 0.0f) {
5666                                         aip->target_objnum = -1;
5667                                         return;
5668                                 }
5669                         } else {
5670                                 aip->target_objnum = -1;
5671                                 return;
5672                         }
5673                 }
5674         }
5675
5676         //      If enemy is protected, not firing a puncture weapon and enemy's hull is low, don't fire.
5677         if ((enemy_objp != NULL) && (enemy_objp->flags & OF_PROTECTED)) {
5678                 // AL: 3-6-98: Check if current_primary_bank is valid
5679                 if ((enemy_objp->hull_strength < 750.0f) && 
5680                         ((aip->targeted_subsys == NULL) || (enemy_objp->hull_strength < aip->targeted_subsys->current_hits + 50.0f)) &&
5681                         (swp->current_primary_bank >= 0) ) {
5682                         if (!(Weapon_info[swp->primary_bank_weapons[swp->current_primary_bank]].wi_flags & WIF_PUNCTURE)) {
5683                                 //nprintf(("AI", "Ship %s not firing at protected ship %s because not using disruptor.\n", Ships[objp->instance].ship_name, Ships[enemy_objp->instance].ship_name));
5684                                 swp->next_primary_fire_stamp[swp->current_primary_bank] = timestamp(1000);
5685                                 return;
5686                         }
5687
5688                         /*
5689                         int     num_attacking;
5690                         num_attacking = num_enemies_attacking(enemy_objp-Objects);
5691                         if (enemy_objp->hull_strength / num_attacking < 200.0f) {
5692                                 if (frand() < 0.75f) {
5693                                         nprintf(("AI", "Ship %s not firing at protected ship %s because too many attacking.\n", Ships[objp->instance].ship_name, Ships[enemy_objp->instance].ship_name));
5694                                         swp->next_primary_fire_stamp[swp->current_primary_bank] = timestamp(500);
5695                                         return;
5696                                 }
5697                         }
5698                         */
5699                 }
5700         }
5701
5702         set_primary_weapon_linkage(objp);
5703         
5704         // I think this will properly solve the problem
5705         // fire non-streaming weapons
5706         ship_fire_primary(objp, 0);
5707         
5708         // fire streaming weapons
5709         shipp->flags |= SF_TRIGGER_DOWN;
5710         ship_fire_primary(objp, 1);
5711         shipp->flags &= ~SF_TRIGGER_DOWN;
5712 }
5713
5714 //      --------------------------------------------------------------------------
5715 //      Return number of nearby enemy fighters.
5716 //      threshold is the distance within which a ship is considered near.
5717 //
5718 // input:       enemy_team_mask =>      teams that are considered as an enemy
5719 //                              pos                                     =>      world position to measure ship distances from
5720 //                              threshold                       =>      max distance from pos to be considered "near"
5721 //
5722 // exit:                number of ships within threshold units of pos
5723 int num_nearby_fighters(int enemy_team_mask, vector *pos, float threshold)
5724 {
5725         ship_obj        *so;
5726         object  *ship_objp;
5727         int             count = 0;
5728
5729         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
5730
5731                 ship_objp = &Objects[so->objnum];
5732
5733                 if (Ships[ship_objp->instance].team & enemy_team_mask) {
5734                         if (Ship_info[Ships[ship_objp->instance].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER)) {
5735                                 if (vm_vec_dist_quick(pos, &ship_objp->pos) < threshold)
5736                                         count++;
5737                         }
5738                 }
5739         }
5740
5741         return count;
5742 }
5743
5744 //      --------------------------------------------------------------------------
5745 //      Select secondary weapon to fire.
5746 //      Currently, 1/16/98:
5747 //              If 0 secondary weapons available, return -1
5748 //              If 1 available, use it.
5749 //              If 2 or more, if the current weapon is one of them, stick with it, otherwise choose a random one.
5750 //      priority1 and priority2 are Weapon_info[] bitmasks such as WIF_HOMING_ASPECT.  If any weapon has any bit in priority1
5751 //      set, that weapon will be selected.  If not, apply to priority2.  If neither, return -1, meaning no weapon selected.
5752 //      Note, priorityX have default values of -1, meaning if not set, they will match any weapon.
5753 //      Return value:
5754 //              bank index
5755 //      Should do this:
5756 //              Favor aspect seekers when attacking small ships faraway.
5757 //              Favor rapid fire dumbfire when attacking a large ship.
5758 //              Ignore heat seekers because we're not sure how they'll work.
5759 void ai_select_secondary_weapon(object *objp, ship_weapon *swp, int priority1 = -1, int priority2 = -1)
5760 {
5761         int     num_weapon_types;
5762         int     weapon_id_list[MAX_WEAPON_TYPES], weapon_bank_list[MAX_WEAPON_TYPES];
5763         int     i;
5764         int     ignore_mask;
5765         int     initial_bank;
5766
5767         initial_bank = swp->current_secondary_bank;
5768
5769         //      Ignore bombs unless one of the priorities asks for them to be selected.
5770         if (WIF_HUGE & (priority1 | priority2))
5771                 ignore_mask = 0;
5772         else
5773                 ignore_mask = WIF_HUGE;
5774
5775         if (!(WIF_BOMBER_PLUS & (priority1 | priority2)))
5776                 ignore_mask |= WIF_BOMBER_PLUS;
5777
5778 #ifndef NDEBUG
5779         for (i=0; i<MAX_WEAPON_TYPES; i++) {
5780                 weapon_id_list[i] = -1;
5781                 weapon_bank_list[i] = -1;
5782         }
5783 #endif
5784
5785         //      Stuff weapon_bank_list with bank index of available weapons.
5786         num_weapon_types = get_available_secondary_weapons(objp, weapon_id_list, weapon_bank_list);
5787
5788         int     priority2_index = -1;
5789
5790         for (i=0; i<num_weapon_types; i++) {
5791                 int     wi_flags;
5792
5793                 wi_flags = Weapon_info[swp->secondary_bank_weapons[weapon_bank_list[i]]].wi_flags;
5794                 if (!(wi_flags & ignore_mask)) {                                        //      Maybe bombs are illegal.
5795                         if (wi_flags & priority1) {
5796                                 swp->current_secondary_bank = weapon_bank_list[i];                              //      Found first priority, return it.
5797                                 break;
5798                         } else if (wi_flags & priority2)
5799                                 priority2_index = weapon_bank_list[i];  //      Found second priority, but might still find first priority.
5800                 }
5801         }
5802
5803         //      If didn't find anything above, then pick any secondary weapon.
5804         if (i == num_weapon_types) {
5805                 swp->current_secondary_bank = priority2_index;  //      Assume we won't find anything.
5806                 if (priority2_index == -1) {
5807                         for (i=0; i<num_weapon_types; i++) {
5808                                 int     wi_flags;
5809
5810                                 wi_flags = Weapon_info[swp->secondary_bank_weapons[weapon_bank_list[i]]].wi_flags;
5811                                 if (!(wi_flags & ignore_mask)) {                                        //      Maybe bombs are illegal.
5812                                         if (swp->secondary_bank_ammo[i] > 0) {
5813                                                 swp->current_secondary_bank = i;
5814                                                 break;
5815                                         }
5816                                 }
5817                         }
5818                 }
5819         }
5820
5821         //      If switched banks, force reacquisition of aspect lock.
5822         if (swp->current_secondary_bank != initial_bank) {
5823                 ai_info *aip = &Ai_info[Ships[objp->instance].ai_index];
5824                 
5825                 aip->aspect_locked_time = 0.0f;
5826                 aip->current_target_is_locked = 0;
5827         }
5828
5829
5830         ship_secondary_changed(&Ships[objp->instance]); // AL: let multiplayer know if secondary bank has changed
5831         // nprintf(("AI", "Ship %s selected weapon %s\n", Ships[objp->instance].ship_name, Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]].name));
5832 }
5833
5834 //      Return number of objects homing on object *target_objp
5835 int compute_num_homing_objects(object *target_objp)
5836 {
5837         object  *objp;
5838         int             count = 0;
5839
5840         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
5841                 if (objp->type == OBJ_WEAPON) {
5842                         if (Weapon_info[Weapons[objp->instance].weapon_info_index].wi_flags & WIF_HOMING) {
5843                                 if (Weapons[objp->instance].homing_object == target_objp) {
5844                                         count++;
5845                                 }
5846                         }
5847                 }
5848         }
5849
5850         return count;
5851 }
5852
5853 //      Object *firing_objp just fired weapon weapon_index (index in Weapon_info).
5854 //      If it's a shockwave weapon, tell your team about it!
5855 void ai_maybe_announce_shockwave_weapon(object *firing_objp, int weapon_index)
5856 {
5857         if ((firing_objp->type == OBJ_SHIP) && (Weapon_info[weapon_index].shockwave_speed > 0.0f)) {
5858                 ship_obj        *so;
5859                 int             firing_ship_team;
5860
5861                 firing_ship_team = Ships[firing_objp->instance].team;
5862
5863                 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
5864                         object  *A = &Objects[so->objnum];
5865                         SDL_assert(A->type == OBJ_SHIP);
5866
5867                         if (Ships[A->instance].team == firing_ship_team) {
5868                                 ai_info *aip = &Ai_info[Ships[A->instance].ai_index];
5869                                 // AL 1-5-98: only avoid shockwave if not docked or repairing
5870                                 if ( !(aip->ai_flags & (AIF_DOCKED|AIF_BEING_REPAIRED)) ) {
5871                                         aip->ai_flags |= AIF_AVOID_SHOCKWAVE_WEAPON;
5872                                 }
5873                         }
5874                 }
5875         }
5876 }
5877
5878 //      Return total payload of all incoming missiles.
5879 float compute_incoming_payload(object *target_objp)
5880 {
5881         missile_obj     *mo;
5882         float                   payload = 0.0f;
5883
5884         for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
5885                 object  *objp;
5886
5887                 objp = &Objects[mo->objnum];
5888                 SDL_assert(objp->type == OBJ_WEAPON);
5889                 if (Weapons[objp->instance].homing_object == target_objp) {
5890                         payload += Weapon_info[Weapons[objp->instance].weapon_info_index].damage;
5891                 }
5892         }
5893
5894         return payload;
5895 }
5896
5897 //      --------------------------------------------------------------------------
5898 //      Return true if OK for *aip to fire its current weapon at its current target.
5899 //      Only reason this function returns false is:
5900 //              weapon is a homer
5901 //              targeted at player
5902 //                      OR:     player has too many homers targeted at him
5903 //                                      Missiontime in that dead zone in which can't fire at this player
5904 //      Note: If player is attacking a ship, that ship is allowed to fire at player.  Otherwise, we get in a situation in which
5905 //      player is attacking a large ship, but that large ship is not defending itself with missiles.
5906 int check_ok_to_fire(int objnum, int target_objnum, weapon_info *wip)
5907 {
5908         int     num_homers = 0;
5909         object  *tobjp = &Objects[target_objnum];
5910
5911         if (target_objnum > -1) {
5912                 // AL 3-4-98: Ensure objp target is a ship first 
5913                 if ( tobjp->type == OBJ_SHIP ) {
5914
5915                         // should not get this far. check if ship is protected from beam and weapon is type beam
5916                         if ( (wip->wi_flags & WIF_BEAM) && (tobjp->flags & OF_BEAM_PROTECTED) ) {
5917                                 Int3();
5918                                 return 0;
5919                         }
5920                         if (Ship_info[Ships[tobjp->instance].ship_info_index].flags & SIF_SMALL_SHIP) {
5921                                 num_homers = compute_num_homing_objects(&Objects[target_objnum]);
5922                         }
5923                 }
5924
5925                 //      If player, maybe fire based on Skill_level and number of incoming weapons.
5926                 //      If non-player, maybe fire based on payload of incoming weapons.
5927                 if (wip->wi_flags & WIF_HOMING) {
5928                         if ((target_objnum > -1) && (tobjp->flags & OF_PLAYER_SHIP)) {
5929                                 if (Ai_info[Ships[tobjp->instance].ai_index].target_objnum != objnum) {
5930                                         //      Don't allow AI ships to fire at player for fixed periods of time based on skill level.
5931                                         //      With 5 skill levels, at Very Easy, they fire in 1/7 of every 10 second interval.
5932                                         //      At Easy, 2/7...at Expert, 5/7
5933                                         int t = ((Missiontime /(65536*10)) ^ target_objnum ^ 0x01) % (NUM_SKILL_LEVELS+2);
5934                                         if (t > Game_skill_level) {
5935                                                 //nprintf(("AI", "Not OK to fire homer at time thing %i\n", t));
5936                                                 return 0;
5937                                         }
5938                                 }
5939                                 //nprintf(("AI", " IS OK to fire homer at time thing %i ***\n", t));
5940                                 int     swarmers = 0;
5941                                 if (wip->wi_flags & WIF_SWARM)
5942                                         swarmers = 2;   //      Note, always want to be able to fire swarmers if no currently incident homers.
5943                                 if (Max_allowed_player_homers[Game_skill_level] < num_homers + swarmers) {
5944                                         return 0;
5945                                 }
5946                         } else if (num_homers > 3) {
5947                                 float   incoming_payload;
5948
5949                                 incoming_payload = compute_incoming_payload(&Objects[target_objnum]);
5950
5951                                 if (incoming_payload > tobjp->hull_strength) {
5952                                         return 0;
5953                                 }
5954                         }
5955                 }
5956         }
5957
5958         return 1;
5959 }
5960
5961 //      --------------------------------------------------------------------------
5962 //      Fire a secondary weapon.
5963 //      Maybe choose to fire a different one.
5964 //      priority1 and priority2 are optional parameters with defaults = -1
5965 int ai_fire_secondary_weapon(object *objp, int priority1, int priority2)
5966 {
5967         ship_weapon *swp;
5968         ship    *shipp;
5969         int             current_bank;
5970         int             rval = 0;
5971
5972 #ifndef NDEBUG
5973         if (!Ai_firing_enabled)
5974                 return rval;
5975 #endif
5976
5977         SDL_assert( objp != NULL );
5978         SDL_assert(objp->type == OBJ_SHIP);
5979         shipp = &Ships[objp->instance];
5980         swp = &shipp->weapons;
5981
5982         //      Select secondary weapon.
5983         current_bank = swp->current_secondary_bank; //ai_select_secondary_weapon(objp, swp, priority1, priority2);
5984
5985         //nprintf(("AI", "Frame %i: Current bank = %i, ammo remaining = %i\n", Framecount, current_bank, swp->secondary_bank_ammo[current_bank]));
5986         if (current_bank == -1) {
5987                 return rval;
5988         }
5989
5990         SDL_assert(current_bank < shipp->weapons.num_secondary_banks);
5991
5992         weapon_info     *wip = &Weapon_info[shipp->weapons.secondary_bank_weapons[current_bank]];
5993
5994         if ((wip->wi_flags & WIF_HOMING_ASPECT) && (!Ai_info[shipp->ai_index].current_target_is_locked)) {
5995                 //nprintf(("AI", "Not firing secondary weapon because not aspect locked.\n"));
5996                 swp->next_secondary_fire_stamp[current_bank] = timestamp(250);
5997         } else if ((wip->wi_flags & WIF_BOMB) || (vm_vec_dist_quick(&objp->pos, &En_objp->pos) > 50.0f)) {
5998                 //      This might look dumb, firing a bomb even if closer than 50 meters, but the reason is, if you're carrying
5999                 //      bombs, delivering them is probably more important than surviving.
6000                 ai_info *aip;
6001
6002                 aip = &Ai_info[shipp->ai_index];
6003                 
6004                 //      Note, maybe don't fire if firing at player and any homers yet fired.
6005                 //      Decreasing chance to fire the more homers are incoming on player.
6006                 if (check_ok_to_fire(OBJ_INDEX(objp), aip->target_objnum, wip)) {
6007                         if (ship_fire_secondary(objp)) {
6008                                 rval = 1;
6009                                 swp->next_secondary_fire_stamp[current_bank] = timestamp(500);
6010                                 //nprintf(("AI", "Frane %i: Ship %s fired secondary %s\n", Framecount, Ships[objp->instance].ship_name, Weapon_info[swp->secondary_bank_weapons[current_bank]].name));
6011                         }
6012
6013                 } else {
6014                         swp->next_secondary_fire_stamp[current_bank] = timestamp(500);
6015                 }
6016         }
6017
6018         return rval;
6019 }
6020
6021 //      Return true if it looks like obj1, if continuing to move along current vector, will
6022 //      collide with obj2.
6023 int might_collide_with_ship(object *obj1, object *obj2, float dot_to_enemy, float dist_to_enemy, float duration)
6024 {
6025         if (obj1->phys_info.speed * duration + 2*(obj1->radius + obj2->radius) > dist_to_enemy)
6026                 if (dot_to_enemy > 0.8f - 2*(obj1->radius + obj2->radius)/dist_to_enemy)
6027                         return objects_will_collide(obj1, obj2, duration, 2.0f);
6028
6029 //              BABY - 
6030 //              CONDITION 1, dist_to_enemy < o1_rad + o2_rad + (obj1.speed + obj2.speed) * time + 50
6031         
6032         return 0;
6033
6034 }
6035
6036 //      --------------------------------------------------------------------------
6037 //      Return true if ship *objp firing a laser believes it will hit a teammate.
6038 int might_hit_teammate(object *firing_objp)
6039 {
6040         int             team;
6041         object  *objp;
6042         ship_obj        *so;
6043
6044         team = Ships[firing_objp->instance].team;
6045
6046         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
6047                 objp = &Objects[so->objnum];
6048                 if (Ships[objp->instance].team == team) {
6049                         float           dist, dot;
6050                         vector  vec_to_objp;
6051
6052                         vm_vec_sub(&vec_to_objp, &firing_objp->pos, &objp->pos);
6053                         dist = vm_vec_mag_quick(&vec_to_objp);
6054                         dot = vm_vec_dot(&firing_objp->orient.v.fvec, &vec_to_objp)/dist;
6055                         if (might_collide_with_ship(firing_objp, objp, dot, dist, 2.0f))
6056                                 return 1;
6057                 }
6058         }
6059
6060         return 0;
6061
6062 }
6063
6064 //int   Team_not_fire_count=0, Team_hit_count = 0;
6065
6066 void render_all_ship_bay_paths(object *objp)
6067 {
6068         int             i,j,color;
6069         ship            *sp = &Ships[objp->instance];
6070         polymodel       *pm;
6071         model_path      *mp;
6072
6073         pm = model_get(sp->modelnum);
6074         vector  global_path_point;
6075         vertex  v, prev_vertex;
6076
6077         if ( pm->ship_bay == NULL )
6078                 return;
6079
6080         for ( i = 0; i < pm->ship_bay->num_paths; i++ ) {
6081                 mp = &pm->paths[pm->ship_bay->paths[i]];
6082
6083                 for ( j = 0; j < mp->nverts; j++ ) {
6084                         vm_vec_unrotate(&global_path_point, &mp->verts[j].pos, &objp->orient);
6085                         vm_vec_add2(&global_path_point, &objp->pos);
6086                         g3_rotate_vertex(&v, &global_path_point);
6087                         color = 255 - j*50;
6088                         if ( color < 50 ) 
6089                                 color = 100;
6090                         gr_set_color(0, color, 0);
6091
6092                         if ( j == mp->nverts-1 ) {
6093                                 gr_set_color(255, 0, 0);
6094                         }
6095
6096                         g3_draw_sphere( &v, 1.5f);
6097
6098                         if ( j > 0 )
6099                                 g3_draw_line(&v, &prev_vertex);
6100
6101                         prev_vertex = v;
6102         
6103                 }
6104         }
6105 }
6106
6107 // debug function to show all path points associated with an object
6108 void render_all_subsys_paths(object *objp)
6109 {
6110         int             i,j,color;
6111         ship            *sp = &Ships[objp->instance];
6112         polymodel       *pm;
6113         model_path      *mp;
6114
6115         pm = model_get(sp->modelnum);
6116         vector  global_path_point;
6117         vertex  v, prev_vertex;
6118
6119         if ( pm->ship_bay == NULL )
6120                 return;
6121
6122         for ( i = 0; i < pm->n_paths; i++ ) {
6123                 mp = &pm->paths[i];
6124                 for ( j = 0; j < mp->nverts; j++ ) {
6125                         vm_vec_unrotate(&global_path_point, &mp->verts[j].pos, &objp->orient);
6126                         vm_vec_add2(&global_path_point, &objp->pos);
6127                         g3_rotate_vertex(&v, &global_path_point);
6128                         color = 255 - j*50;
6129                         if ( color < 50 ) 
6130                                 color = 100;
6131                         gr_set_color(0, color, 0);
6132
6133                         if ( j == mp->nverts-1 ) {
6134                                 gr_set_color(255, 0, 0);
6135                         }
6136
6137                         g3_draw_sphere( &v, 1.5f);
6138
6139                         if ( j > 0 )
6140                                 g3_draw_line(&v, &prev_vertex);
6141
6142                         prev_vertex = v;
6143                 }
6144         }
6145 }
6146
6147 void render_path_points(object *objp)
6148 {
6149         ship            *shipp = &Ships[objp->instance];
6150         ai_info *aip = &Ai_info[shipp->ai_index];
6151         object  *dobjp;
6152         polymodel       *pm;
6153
6154         render_all_subsys_paths(objp);
6155         render_all_ship_bay_paths(objp);
6156
6157         if (aip->goal_objnum < 0)
6158                 return;
6159
6160         dobjp = &Objects[aip->goal_objnum];
6161         pm = model_get(Ships[dobjp->instance].modelnum);
6162         vector  dock_point, global_dock_point;
6163         vertex  v;
6164
6165         ship_model_start(&Objects[aip->goal_objnum]);
6166         if (pm->n_docks) {
6167                 dock_point = pm->docking_bays[0].pnt[0];
6168                 model_find_world_point(&global_dock_point, &dock_point, Ships[dobjp->instance].modelnum, 0, &dobjp->orient, &dobjp->pos );
6169                 g3_rotate_vertex(&v, &global_dock_point);
6170                 gr_set_color(255, 255, 255);
6171                 g3_draw_sphere( &v, 1.5f);
6172         }
6173
6174         if (aip->path_start != -1) {
6175                 vertex          prev_vertex;
6176                 pnode                   *pp = &Path_points[aip->path_start];
6177                 int                     num_points = aip->path_length;
6178                 int                     i;
6179
6180                 for (i=0; i<num_points; i++) {
6181                         vertex  v0;
6182
6183                         g3_rotate_vertex( &v0, &pp->pos );
6184
6185                         gr_set_color(0, 128, 96);
6186                         if (i != 0)
6187                                 g3_draw_line(&v0, &prev_vertex);
6188
6189                         if (pp-Path_points == aip->path_cur)
6190                                 gr_set_color(255,255,0);
6191                         
6192                         g3_draw_sphere( &v0, 4.5f);
6193
6194                         //      Connect all the turrets that can fire upon this point to this point.
6195 /*                      if (0) { //pp->path_index != -1) {
6196                                 model_path      *pmp;
6197                                 mp_vert         *pmpv;
6198
6199                                 get_base_path_info(pp->path_index, aip->goal_objnum, &pmp, &pmpv);
6200
6201                                 if (pmpv->nturrets) {
6202                                         for (int j = 0; j<pmpv->nturrets; j++) {
6203                                                 vertex  v1;
6204                                                 vector  turret_pos;
6205                                                 ship_subsys     *ssp;
6206
6207                                                 ssp = ship_get_indexed_subsys(&Ships[Objects[aip->goal_objnum].instance], pmpv->turret_ids[j]);
6208
6209 model_find_world_point(&turret_pos, &ssp->system_info->pnt, Ships[dobjp->instance].modelnum, 0, &dobjp->orient, &dobjp->pos );
6210         
6211                                                 g3_rotate_vertex(&v1, &turret_pos);
6212                                                 gr_set_color(255, 255, 0);
6213                                                 g3_draw_line(&v0, &v1);
6214                                                 g3_draw_sphere( &v1, 1.5f);
6215                                         }
6216                                 }
6217                         } */
6218
6219                         prev_vertex = v0;
6220
6221                         pp++;
6222                 }
6223         }
6224
6225         ship_model_stop(&Objects[aip->goal_objnum]);
6226 }
6227
6228 // Return the distance that the current AI weapon will travel
6229 float ai_get_weapon_dist(ship_weapon *swp)
6230 {
6231         int     bank_num, weapon_num;
6232
6233         bank_num = swp->current_primary_bank;
6234         weapon_num = swp->primary_bank_weapons[bank_num];
6235
6236         //      If weapon_num is illegal, return a reasonable value.  A valid weapon
6237         //      will get selected when this ship tries to fire.
6238         if (weapon_num == -1) {
6239                 // Int3();
6240                 return 1000.0f;
6241         }
6242
6243         return Weapon_info[weapon_num].max_speed * Weapon_info[weapon_num].lifetime;
6244 }
6245
6246 float ai_get_weapon_speed(ship_weapon *swp)
6247 {
6248         int     bank_num, weapon_num;
6249
6250         bank_num = swp->current_primary_bank;
6251         if (bank_num < 0)
6252                 return 100.0f;
6253
6254         weapon_num = swp->primary_bank_weapons[bank_num];
6255
6256         if (weapon_num == -1) {
6257                 //Int3();
6258                 return 100.0f;
6259         }
6260
6261         return Weapon_info[weapon_num].max_speed;
6262 }
6263
6264 //      Compute the predicted position of a ship to be fired upon from a turret.
6265 //      This is based on position of firing gun, enemy object, weapon speed and skill level constraints.
6266 //      Return value in *predicted_enemy_pos.
6267 //      Also, stuff globals G_predicted_pos, G_collision_time and G_fire_pos.
6268 //      *pobjp          object firing the weapon
6269 //      *eobjp          object being fired upon
6270 void set_predicted_enemy_pos_turret(vector *predicted_enemy_pos, vector *gun_pos, object *pobjp, vector *enemy_pos, vector *enemy_vel, float weapon_speed, float time_enemy_in_range)
6271 {
6272         ship    *shipp = &Ships[pobjp->instance];
6273         float   range_time;
6274
6275         //weapon_speed = ai_get_weapon_speed(&shipp->weapons);
6276
6277         if (weapon_speed < 1.0f)
6278                 weapon_speed = 1.0f;
6279
6280         range_time = 2.0f;
6281
6282         //      Make it take longer for enemies to get player's allies in range based on skill level.
6283         if (Ships[pobjp->instance].team != Ships[Player_obj->instance].team)
6284                 range_time += In_range_time[Game_skill_level];
6285
6286         //nprintf(("AI", "time enemy in range = %7.3f\n", aip->time_enemy_in_range));
6287
6288         if (time_enemy_in_range < range_time) {
6289                 float   dist;
6290
6291                 dist = vm_vec_dist_quick(&pobjp->pos, enemy_pos);
6292                 vm_vec_scale_add(predicted_enemy_pos, enemy_pos, enemy_vel, time_enemy_in_range * dist/weapon_speed);
6293         } else {
6294                 float   collision_time, scale;
6295                 vector  rand_vec;
6296                 ai_info *aip = &Ai_info[shipp->ai_index];
6297
6298                 collision_time = compute_collision_time(enemy_pos, enemy_vel, gun_pos, weapon_speed);
6299
6300                 if (collision_time == 0.0f){
6301                         collision_time = 100.0f;
6302                 }
6303
6304                 vm_vec_scale_add(predicted_enemy_pos, enemy_pos, enemy_vel, collision_time);
6305                 if (time_enemy_in_range > 2*range_time){
6306                         scale = (1.0f - aip->ai_accuracy) * 4.0f;
6307                 } else {
6308                         scale = (1.0f - aip->ai_accuracy) * 4.0f * (1.0f + 4.0f * (1.0f - time_enemy_in_range/(2*range_time)));
6309                 }               
6310
6311                 static_randvec(((pobjp-Objects) ^ (Missiontime >> 16)) & 7, &rand_vec);
6312
6313                 vm_vec_scale_add2(predicted_enemy_pos, &rand_vec, scale);
6314                 G_collision_time = collision_time;
6315                 G_fire_pos = *gun_pos;
6316         }
6317
6318         G_predicted_pos = *predicted_enemy_pos;
6319 }
6320
6321 //      Compute the predicted position of a ship to be fired upon.
6322 //      This is based on current position of firing object, enemy object, relative position of gun on firing object,
6323 //      weapon speed and skill level constraints.
6324 //      Return value in *predicted_enemy_pos.
6325 //      Also, stuff globals G_predicted_pos, G_collision_time and G_fire_pos.
6326 void set_predicted_enemy_pos(vector *predicted_enemy_pos, object *pobjp, object *eobjp, ai_info *aip)
6327 {
6328         float   weapon_speed, range_time;
6329         ship    *shipp = &Ships[pobjp->instance];
6330
6331         weapon_speed = ai_get_weapon_speed(&shipp->weapons);
6332         weapon_speed = SDL_max(weapon_speed, 1.0f);             // set not less than 1
6333
6334         range_time = 2.0f;
6335
6336         //      Make it take longer for enemies to get player's allies in range based on skill level.
6337         // but don't bias team v. team missions
6338         if ( !((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_TEAM)) ) {
6339                 if (Ships[pobjp->instance].team != Ships[Player_obj->instance].team) {
6340                         range_time += In_range_time[Game_skill_level];
6341                 }
6342         }
6343         //nprintf(("AI", "time enemy in range = %7.3f\n", aip->time_enemy_in_range));
6344
6345         if (aip->time_enemy_in_range < range_time) {
6346                 float   dist;
6347
6348                 dist = vm_vec_dist_quick(&pobjp->pos, &eobjp->pos);
6349                 vm_vec_scale_add(predicted_enemy_pos, &eobjp->pos, &eobjp->phys_info.vel, aip->time_enemy_in_range * dist/weapon_speed);
6350         } else {
6351                 float   collision_time;
6352                 vector  gun_pos, pnt;
6353                 polymodel *po = model_get( Ship_info[shipp->ship_info_index].modelnum );
6354
6355                 //      Compute position of gun in absolute space and use that as fire position.
6356                 if(po->gun_banks != NULL){
6357                         pnt = po->gun_banks[0].pnt[0];
6358                 } else {
6359                         pnt = Objects[shipp->objnum].pos;
6360                 }
6361                 vm_vec_unrotate(&gun_pos, &pnt, &pobjp->orient);
6362                 vm_vec_add2(&gun_pos, &pobjp->pos);
6363
6364                 collision_time = compute_collision_time(&eobjp->pos, &eobjp->phys_info.vel, &gun_pos, weapon_speed);
6365
6366                 if (collision_time == 0.0f) {
6367                         collision_time = 100.0f;
6368                 }
6369
6370                 vm_vec_scale_add(predicted_enemy_pos, &eobjp->pos, &eobjp->phys_info.vel, collision_time);
6371
6372                 // set globals
6373                 G_collision_time = collision_time;
6374                 G_fire_pos = gun_pos;
6375         }
6376
6377         // Now add error terms (1) regular aim (2) EMP (3) stealth
6378         float scale = 0.0f;
6379         vector rand_vec;
6380
6381         // regular skill level error in aim
6382         if (aip->time_enemy_in_range > 2*range_time) {
6383                 scale = (1.0f - aip->ai_accuracy) * 4.0f;
6384         } else {
6385                 scale = (1.0f - aip->ai_accuracy) * 4.0f * (1.0f + 4.0f * (1.0f - aip->time_enemy_in_range/(2*range_time)));
6386         }
6387
6388         // if this ship is under the effect of an EMP blast, throw his aim off a bit
6389         if (shipp->emp_intensity > 0.0f) {
6390                 // never go lower than 1/2 of the EMP effect max, otherwise things aren't noticeable
6391                 scale += (MAX_EMP_INACCURACY * (shipp->emp_intensity < 0.5f ? 0.5f : shipp->emp_intensity));
6392                 mprintf(("AI miss scale factor (EMP) %f\n",scale));
6393         }
6394
6395         // if stealthy ship, throw his aim off, more when farther away and when dot is small
6396         if ( aip->ai_flags & AIF_STEALTH_PURSIUT ) {
6397                 float dist = vm_vec_dist_quick(&pobjp->pos, &eobjp->pos);
6398                 vector temp;
6399                 vm_vec_sub(&temp, &eobjp->pos, &pobjp->pos);
6400                 vm_vec_normalize_quick(&temp);
6401                 float dot = vm_vec_dotprod(&temp, &pobjp->orient.v.fvec);
6402                 float st_err = 3.0f * (1.4f - dot) * (1.0f + dist / (get_skill_stealth_dist_scaler() * STEALTH_MAX_VIEW_DIST)) * (1 - aip->ai_accuracy);
6403                 scale += st_err;
6404                 // mprintf(("error term: %.1f, total %.1f, dot %.3f\n", st_err, scale, dot));
6405         }
6406
6407         // get a random vector that changes slowly over time (1x / sec)
6408         static_randvec(((pobjp-Objects) ^ (Missiontime >> 16)) & 7, &rand_vec);
6409
6410         vm_vec_scale_add2(predicted_enemy_pos, &rand_vec, scale);
6411
6412         // set global
6413         G_predicted_pos = *predicted_enemy_pos;
6414 }
6415
6416 //      Handler of submode for Chase.  Go into a continuous turn for awhile.
6417 void ai_chase_ct()
6418 {
6419         vector          tvec;
6420         ship_info       *sip;
6421         ai_info         *aip;
6422
6423         SDL_assert(Ships[Pl_objp->instance].ship_info_index >= 0);
6424         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6425         SDL_assert(Ships[Pl_objp->instance].ai_index >= 0);
6426         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
6427
6428         //      Make a continuous turn towards any combination of possibly negated
6429         // up and right vectors.
6430         tvec = Pl_objp->pos;
6431
6432         if (aip->submode_parm0 & 0x01)
6433                 vm_vec_add2(&tvec, &Pl_objp->orient.v.rvec);
6434         if (aip->submode_parm0 & 0x02)
6435                 vm_vec_sub2(&tvec, &Pl_objp->orient.v.rvec);
6436         if (aip->submode_parm0 & 0x04)
6437                 vm_vec_add2(&tvec, &Pl_objp->orient.v.uvec);
6438         if (aip->submode_parm0 & 0x08)
6439                 vm_vec_sub2(&tvec, &Pl_objp->orient.v.uvec);
6440
6441         //      Detect degenerate cases that cause tvec to be same as player pos.
6442         if (vm_vec_dist_quick(&tvec, &Pl_objp->pos) < 0.1f) {
6443                 aip->submode_parm0 &= 0x05;
6444                 if (aip->submode_parm0 == 0)
6445                         aip->submode_parm0 = 1;
6446                 vm_vec_add2(&tvec, &Pl_objp->orient.v.rvec);
6447         }
6448
6449         ai_turn_towards_vector(&tvec, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6450         accelerate_ship(aip, 1.0f);
6451 }
6452
6453 //      ATTACK submode handler for chase mode.
6454 void ai_chase_eb(ai_info *aip, ship_info *sip, vector *predicted_enemy_pos, float dist_to_enemy)
6455 {
6456         vector  _pep;
6457         float           dot_to_enemy, dot_from_enemy;
6458
6459         compute_dots(Pl_objp, En_objp, &dot_to_enemy, &dot_from_enemy);
6460
6461         //      If we're trying to slow down to get behind, then point to turn towards is different.
6462         _pep = *predicted_enemy_pos;
6463         if ((dot_to_enemy > dot_from_enemy + 0.1f) || (dot_to_enemy > 0.9f))
6464                 vm_vec_scale_add(&_pep, &Pl_objp->pos, &En_objp->orient.v.fvec, 100.0f);
6465
6466         ai_turn_towards_vector(&_pep, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6467
6468         accelerate_ship(aip, 0.0f);
6469 }
6470
6471 //      Return time until weapon_objp might hit ship_objp.
6472 //      Assumes ship_objp is not moving.
6473 //      Returns negative time if not going to hit.
6474 //      This is a very approximate function, but is pretty fast.
6475 float ai_endangered_time(object *ship_objp, object *weapon_objp)
6476 {
6477         float           to_dot, from_dot, dist;
6478
6479         dist = compute_dots(ship_objp, weapon_objp, &to_dot, &from_dot);
6480
6481         //      Note, this is bogus.  It assumes only the weapon is moving.
6482         //      Only proceed if weapon sort of pointing at object and object pointing towards or away from weapon
6483         //      (Ie, if object moving at right angle to weapon, just continue for now...)
6484         if (weapon_objp->phys_info.speed < 1.0f)
6485                 return dist + 1.0f;
6486         else if ((from_dot > 0.1f) && (dist/(from_dot*from_dot) < 48*ship_objp->radius)) //: don't require them to see it, they have instruments!: && (fl_abs(to_dot) > 0.5f))
6487                 return dist / weapon_objp->phys_info.speed;
6488         else
6489                 return -1.0f;
6490 }
6491
6492 //      Return time until danger weapon could hit this ai object.
6493 //      Return negative time if not endangered.
6494 float ai_endangered_by_weapon(ai_info *aip)
6495 {
6496         object  *weapon_objp;
6497
6498         if (aip->danger_weapon_objnum == -1) {
6499                 return -1.0f;
6500         }
6501
6502         weapon_objp = &Objects[aip->danger_weapon_objnum];
6503
6504         if (weapon_objp->signature != aip->danger_weapon_signature) {
6505                 aip->danger_weapon_objnum = -1;
6506                 return -1.0f;
6507         }
6508
6509         return ai_endangered_time(&Objects[Ships[aip->shipnum].objnum], weapon_objp);
6510 }
6511
6512 //      Return true if this ship is near full strength.
6513 int ai_near_full_strength(object *objp, ship_info *sip)
6514 {
6515         return (objp->hull_strength/sip->initial_hull_strength > 0.9f) || (get_shield_strength(objp)/sip->shields > 0.8f);
6516 }
6517                                 
6518 //      Set acceleration while in attack mode.
6519 void attack_set_accel(ai_info *aip, float dist_to_enemy, float dot_to_enemy, float dot_from_enemy)
6520 {
6521         float   speed_ratio;
6522
6523         if (En_objp->phys_info.speed > 1.0f)
6524                 speed_ratio = Pl_objp->phys_info.speed/En_objp->phys_info.speed;
6525         else
6526                 speed_ratio = 5.0f;
6527
6528         //      Sometimes, told to attack slowly.  Allows to get in more hits.
6529         if (aip->ai_flags & AIF_ATTACK_SLOWLY) {
6530                 if ((dist_to_enemy > 200.0f) && (dist_to_enemy < 800.0f)) {
6531                         if ((dot_from_enemy < 0.9f) || ai_near_full_strength(Pl_objp, &Ship_info[Ships[Pl_objp->instance].ship_info_index])) {
6532                                 //nprintf(("AI", " slowly "));
6533                                 accelerate_ship(aip, SDL_max(1.0f - (dist_to_enemy-200.0f)/600.0f, 0.1f));
6534                                 return;
6535                         }
6536                 } else
6537                         aip->ai_flags &= ~AIF_ATTACK_SLOWLY;
6538         }
6539
6540         if (dist_to_enemy > 200.0f + vm_vec_mag_quick(&En_objp->phys_info.vel) * dot_from_enemy + Pl_objp->phys_info.speed * speed_ratio) {
6541                 //nprintf(("AI", "1"));
6542                 if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
6543                         if (dist_to_enemy > 800.0f) {
6544                                 if (!( Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
6545                                         float percent_left;
6546                                         ship    *shipp;
6547                                         ship_info *sip;
6548
6549                                         shipp = &Ships[Pl_objp->instance];
6550                                         sip = &Ship_info[shipp->ship_info_index];
6551
6552                                         if (sip->afterburner_fuel_capacity > 0.0f) {
6553                                                 percent_left = 100.0f * shipp->afterburner_fuel / sip->afterburner_fuel_capacity;
6554                                                 if (percent_left > 30.0f + ((Pl_objp-Objects) & 0x0f)) {
6555                                                         afterburners_start(Pl_objp);
6556                                                         aip->afterburner_stop_time = Missiontime + F1_0 + static_rand(Pl_objp-Objects)/4;
6557                                                 }
6558                                         }
6559                                 }
6560                         }
6561                 }
6562
6563                 accelerate_ship(aip, 1.0f);
6564         } else if ((Missiontime - aip->last_hit_time > F1_0*7)
6565                 && (En_objp->phys_info.speed < 10.0f) 
6566                 && (dist_to_enemy > 25.0f) 
6567                 && (dot_to_enemy > 0.8f)
6568                 && (dot_from_enemy < 0.8f)) {
6569                 accelerate_ship(aip, 0.0f);             //      No one attacking us, so don't need to move.
6570         } else if ((dot_from_enemy < 0.25f) && (dot_to_enemy > 0.5f)) {
6571                 set_accel_for_target_speed(Pl_objp, En_objp->phys_info.speed);
6572         } else if (Pl_objp->phys_info.speed < 15.0f) {
6573                 accelerate_ship(aip, 1.0f);
6574         } else if (Pl_objp->phys_info.speed > En_objp->phys_info.speed - 1.0f) {
6575                 if (dot_from_enemy > 0.75f)
6576                         accelerate_ship(aip, 1.0f);
6577                 else
6578                         set_accel_for_target_speed(Pl_objp, En_objp->phys_info.speed*0.75f + 3.0f);
6579         } else {
6580                 change_acceleration(aip, 0.5f);
6581         }
6582 }
6583
6584 //      Pl_objp (aip) tries to get behind En_objp.
6585 //      New on 2/21/98: If this ship can move backwards and slide, maybe do that to get behind.
6586 void get_behind_ship(ai_info *aip, ship_info *sip, float dist_to_enemy)
6587 {
6588         vector  new_pos;
6589         float           dot;
6590         vector  vec_from_enemy;
6591
6592         vm_vec_normalized_dir(&vec_from_enemy, &Pl_objp->pos, &En_objp->pos);
6593
6594         vm_vec_scale_add(&new_pos, &En_objp->pos, &En_objp->orient.v.fvec, -100.0f);            //      Pick point 100 units behind.
6595         ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6596
6597         dot = vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.fvec);
6598
6599         if (dot > 0.25f) {
6600                 accelerate_ship(aip, 1.0f);
6601         } else {
6602                 accelerate_ship(aip, (dot + 1.0f)/2.0f);
6603         }
6604 }
6605
6606 int avoid_player(object *objp, vector *goal_pos)
6607 {
6608         maybe_avoid_player(Pl_objp, goal_pos);
6609         ai_info *aip = &Ai_info[Ships[objp->instance].ai_index];
6610
6611         if (aip->ai_flags & AIF_AVOIDING_SMALL_SHIP) {
6612                 ship_info *sip = &Ship_info[Ships[objp->instance].ship_info_index];
6613
6614                 if (aip->ai_flags & AIF_AVOIDING_SMALL_SHIP) {
6615                         ai_turn_towards_vector(&aip->avoid_goal_point, objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6616                         accelerate_ship(aip, 0.5f);
6617                         return 1;
6618                 }
6619         }
6620
6621         return 0;
6622 }
6623
6624 //      Determine if a cylinder of width radius from p0 to p1 will collide with big_objp.
6625 //      If so, stuff *collision_point.
6626 int will_collide_pp(vector *p0, vector *p1, float radius, object *big_objp, vector *collision_point)
6627 {
6628         mc_info mc;
6629
6630         mc.model_num = Ships[big_objp->instance].modelnum;              // Fill in the model to check
6631         mc.orient = &big_objp->orient;                  // The object's orient
6632         mc.pos = &big_objp->pos;                                        // The object's position
6633         mc.p0 = p0;                                                                             // Point 1 of ray to check
6634         mc.p1 = p1;
6635         mc.flags = MC_CHECK_MODEL | MC_CHECK_SPHERELINE | MC_SUBMODEL;                                  // flags
6636
6637         mc.radius = radius;
6638
6639         // Only check the 2nd lowest hull object
6640         polymodel *pm = model_get(Ships[big_objp->instance].modelnum);
6641         mc.submodel_num = pm->detail[0]; //pm->submodel->num_details-2];
6642         model_collide(&mc);
6643
6644         if (mc.num_hits)
6645                 *collision_point = mc.hit_point_world;
6646
6647         return mc.num_hits;
6648 }
6649
6650 //      Return true/false if *objp will collide with *big_objp
6651 //      Stuff distance in *distance to collision point if *objp will collide with *big_objp within delta_time seconds.
6652 //      Global collision point stuffed in *collision_point
6653 int will_collide_with_big_ship(object *objp, vector *goal_point, object *big_objp, vector *collision_point, float delta_time)
6654 {
6655         float           radius;
6656         vector  end_pos;
6657
6658         radius = big_objp->radius + delta_time * objp->phys_info.speed;
6659
6660         if (vm_vec_dist_quick(&big_objp->pos, &objp->pos) > radius) {
6661                 return 0;
6662         }
6663
6664         if (goal_point == NULL) {
6665                 vm_vec_scale_add(&end_pos, &objp->pos, &objp->phys_info.vel, delta_time);                                       // Point 2 of ray to check
6666         } else {
6667                 end_pos = *goal_point;
6668         }
6669
6670         return will_collide_pp(&objp->pos, &end_pos, objp->radius, big_objp, collision_point);
6671 }
6672
6673 //      Return true if *objp is expected to collide with a large ship.
6674 //      Stuff global collision point in *collision_point.
6675 //      If *goal_point is not NULL, use that as the point towards which *objp will be flying.  Don't use *objp velocity
6676 //      *ignore_objp will typically be the target this ship is pursuing, either to attack or guard.  We don't want to avoid it.
6677 int will_collide_with_big_ship_all(object *objp, object *ignore_objp, vector *goal_point, vector *collision_point, float *distance, float delta_time)
6678 {
6679         ship_obj        *so;
6680         object  *big_objp;
6681         int             collision_obj_index = -1;
6682         float           min_dist = 999999.9f;
6683
6684         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
6685                 big_objp = &Objects[so->objnum];
6686
6687                 if (big_objp == ignore_objp)
6688                         continue;
6689
6690                 if (Ship_info[Ships[big_objp->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
6691                         vector  cur_collision_point;
6692                         float           cur_dist;
6693
6694                         if (will_collide_with_big_ship(objp, goal_point, big_objp, &cur_collision_point, delta_time)) {
6695
6696                                 cur_dist = vm_vec_dist(&cur_collision_point, &objp->pos);
6697
6698                                 if (cur_dist < min_dist) {
6699                                         min_dist = cur_dist;
6700                                         *collision_point = cur_collision_point;
6701                                         collision_obj_index = OBJ_INDEX(big_objp);
6702                                 }
6703                         }
6704                 }
6705         }
6706
6707         *distance = min_dist;
6708         return collision_obj_index;
6709
6710 }
6711
6712 typedef struct {
6713         float           dist;
6714         int             collide;
6715         vector  pos;
6716 } sgoal;
6717
6718 //int will_collide_pp(vector *p0, vector *p1, float radius, object *big_objp, vector *collision_point)
6719 //      Pick a point for *objp to fly towards to avoid a collision with *big_objp at *collision_point
6720 //      Return result in *avoid_pos
6721 void mabs_pick_goal_point(object *objp, object *big_objp, vector *collision_point, vector *avoid_pos)
6722 {
6723         matrix  mat1;
6724         sgoal           goals[4];
6725         vector  v2b;
6726
6727         vm_vec_normalized_dir(&v2b, collision_point, &objp->pos);
6728         vm_vector_2_matrix(&mat1, &v2b, NULL, NULL);
6729
6730         int     found = 0;
6731
6732         //      Try various scales, in 0.5f, 0.75f, 1.0f, 1.25f.
6733         //      First try 0.5f to see if we can find a point that near the center of the target ship, which presumably
6734         //      means less of a turn.
6735         //      Try going as far as 1.25f * radius.
6736         float   s;
6737         for (s=0.5f; s<1.3f; s += 0.25f) {
6738                 int     i;
6739                 for (i=0; i<4; i++) {
6740                         vector p = big_objp->pos;
6741                         float ku = big_objp->radius*s + objp->radius * (OBJ_INDEX(objp) % 4)/4;         //      This objp->radius stuff to prevent ships from glomming together at one point
6742                         float kr = big_objp->radius*s + objp->radius * ((OBJ_INDEX(objp) % 4) ^ 2)/4;
6743                         if (i&1)
6744                                 ku = -ku;
6745                         if (i&2)
6746                                 kr = -kr;
6747                         vm_vec_scale_add2(&p, &mat1.v.uvec, ku);
6748                         vm_vec_scale_add2(&p, &mat1.v.rvec, kr);
6749                         goals[i].pos = p;
6750                         goals[i].dist = vm_vec_dist_quick(&objp->pos, &p);
6751                         goals[i].collide = will_collide_pp(&objp->pos, &p, objp->radius, big_objp, collision_point);
6752                         if (!goals[i].collide)
6753                                 found = 1;
6754                 }
6755
6756                 //      If we found a point that doesn't collide, find the nearest one and make that the *avoid_pos.
6757                 if (found) {
6758                         float   min_dist = 9999999.9f;
6759                         int     min_index = -1;
6760
6761                         for (i=0; i<4; i++) {
6762                                 if (!goals[i].collide && (goals[i].dist < min_dist)) {
6763                                         min_dist = goals[i].dist;
6764                                         min_index = i;
6765                                 }
6766                         }
6767
6768                         SDL_assert(i != -1);
6769                         if (i != -1) {
6770                                 *avoid_pos = goals[min_index].pos;
6771                                 return;
6772                         }
6773                 }
6774         }
6775
6776         //      Drat.  We tried and tried and could not find a point that did not cause a collision.
6777         //      Get this dump pilot far away from the problem ship.
6778         vector  away_vec;
6779         vm_vec_normalized_dir(&away_vec, &objp->pos, collision_point);
6780         vm_vec_scale_add(avoid_pos, &objp->pos, &away_vec, big_objp->radius*1.5f);
6781
6782 }
6783
6784 //      Return true if a large ship is being ignored.
6785 int maybe_avoid_big_ship(object *objp, object *ignore_objp, ai_info *aip, vector *goal_point, float delta_time)
6786 {
6787         if (timestamp_elapsed(aip->avoid_check_timestamp)) {
6788                 float           distance;
6789                 vector  collision_point;
6790                 int             ship_num;
6791                 if ((ship_num = will_collide_with_big_ship_all(Pl_objp, ignore_objp, goal_point, &collision_point, &distance, delta_time)) != -1) {
6792                         aip->ai_flags |= AIF_AVOIDING_BIG_SHIP;
6793                         mabs_pick_goal_point(objp, &Objects[ship_num], &collision_point, &aip->avoid_goal_point);
6794                         float dist = vm_vec_dist_quick(&aip->avoid_goal_point, &objp->pos);
6795                         aip->avoid_check_timestamp = timestamp(2000 + SDL_min(1000, (int) (dist * 2.0f)));      //      Delay until check again is based on distance to avoid point.
6796                         aip->avoid_ship_num = ship_num;
6797                 } else {
6798                         aip->ai_flags &= ~AIF_AVOIDING_BIG_SHIP;
6799                         aip->ai_flags &= ~AIF_AVOIDING_SMALL_SHIP;
6800                         aip->avoid_ship_num = -1;
6801                         aip->avoid_check_timestamp = timestamp(1500);
6802                 }
6803         }
6804         
6805         if (aip->ai_flags & AIF_AVOIDING_BIG_SHIP) {
6806                 ship_info *sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6807
6808                 vector  v2g;
6809
6810                 ai_turn_towards_vector(&aip->avoid_goal_point, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6811                 vm_vec_normalized_dir(&v2g, &aip->avoid_goal_point, &Pl_objp->pos);
6812                 float dot = vm_vec_dot(&objp->orient.v.fvec, &v2g);
6813                 float d2 = (1.0f + dot) * (1.0f + dot);
6814                 accelerate_ship(aip, d2/4.0f);
6815                 return 1;
6816         }
6817
6818         return 0;
6819 }
6820
6821 //      Set desired right vector for ships flying towards another ship.
6822 //      Since this is governed only by vector to target, it causes ships to align bank and look less chaotic.
6823 void compute_desired_rvec(vector *rvec, vector *goal_pos, vector *cur_pos)
6824 {
6825         vector  v2e;
6826
6827         vm_vec_normalized_dir(&v2e, goal_pos, cur_pos);
6828         rvec->xyz.x = v2e.xyz.z;
6829         rvec->xyz.y = 0.0f;
6830         rvec->xyz.z = -v2e.xyz.x;
6831         if (vm_vec_mag_squared(rvec) < 0.001f)
6832                 rvec->xyz.y = 1.0f;
6833 }
6834
6835 // Handler for stealth find submode of Chase.
6836 void ai_stealth_find()
6837 {
6838         ai_info         *aip;
6839         ship_info       *sip;
6840
6841         vector new_pos, vec_to_enemy;
6842         float dist_to_enemy, dot_to_enemy, dot_from_enemy;
6843
6844         SDL_assert(Ships[Pl_objp->instance].ship_info_index >= 0);
6845         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6846         SDL_assert(Ships[Pl_objp->instance].ai_index >= 0);
6847         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
6848
6849         // get time since last seen
6850         int delta_time = (timestamp() - aip->stealth_last_visible_stamp);
6851
6852         // if delta_time is really big, i'm real confused, start sweep
6853         if (delta_time > 10000) {
6854                 aip->submode_parm0 = SM_SF_BAIL;
6855         }
6856
6857         // guestimate new position
6858         vm_vec_scale_add(&new_pos, &aip->stealth_last_pos, &aip->stealth_velocity, (delta_time * 0.001f));
6859
6860         // if I think he's behind me, go to the goal point
6861         if ( aip->submode_parm0 == SM_SF_BEHIND ) {
6862                 new_pos = aip->goal_point;
6863         }
6864
6865         // check for collision with big ships
6866         if (maybe_avoid_big_ship(Pl_objp, En_objp, aip, &new_pos, 10.0f)) {
6867                 // reset ai submode to chase
6868                 return;
6869         }
6870
6871         // if dist is near max and dot is close to 1, accel, afterburn
6872         vm_vec_sub(&vec_to_enemy, &new_pos, &Pl_objp->pos);
6873         dist_to_enemy = vm_vec_normalize_quick(&vec_to_enemy);
6874         dot_to_enemy = vm_vec_dotprod(&vec_to_enemy, &Pl_objp->orient.v.fvec);
6875
6876         // if i think i should see him ahead and i don't, set goal pos and turn around, but only if I haven't seen him for a while
6877         if ( (delta_time > 800) && (aip->submode_parm0 == SM_SF_AHEAD) && (dot_to_enemy > .94) && (dist_to_enemy < get_skill_stealth_dist_scaler()*STEALTH_MAX_VIEW_DIST + 50) ) {
6878                 // do turn around)
6879                 vm_vec_scale_add(&aip->goal_point, &Pl_objp->pos, &Pl_objp->orient.v.fvec, -300.0f);
6880                 aip->submode_parm0 = SM_SF_BEHIND;
6881                 vm_vec_sub(&vec_to_enemy, &new_pos, &Pl_objp->pos);
6882                 dist_to_enemy = vm_vec_normalize_quick(&vec_to_enemy);
6883                 dot_to_enemy = vm_vec_dotprod(&vec_to_enemy, &Pl_objp->orient.v.fvec);
6884         }
6885
6886         if ( (dist_to_enemy > get_skill_stealth_dist_scaler()*STEALTH_MAX_VIEW_DIST) && (dot_to_enemy > 0.94f) ) {              // 20 degree half angle
6887                 // accelerate ship
6888                 accelerate_ship(aip, 1.0f);
6889
6890                 // engage afterburner
6891                 if (!( Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
6892                         if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
6893                                 afterburners_start(Pl_objp);
6894                                 aip->afterburner_stop_time = Missiontime + 3*F1_0/2;
6895                         }
6896                 }
6897
6898                 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6899                 return;
6900         }
6901
6902         //      If enemy more than 500 meters away, all ships flying there will tend to match bank.
6903         //      They do this by using their vector to their target to compute their right vector and causing ai_turn_towards_vector
6904         //      to interpolate a matrix rather than just a vector.
6905         if (dist_to_enemy > 500.0f) {
6906                 vector  rvec;
6907                 compute_desired_rvec(&rvec, &new_pos, &Pl_objp->pos);
6908                 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0, &rvec);
6909         } else {
6910                 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6911         }
6912
6913         dot_from_enemy = -vm_vec_dotprod(&vec_to_enemy, &En_objp->orient.v.fvec);
6914
6915         attack_set_accel(aip, dist_to_enemy, dot_to_enemy, dot_from_enemy);
6916 }
6917
6918 // -----------------------------------------------------------------------------
6919 // try to find stealth ship by sweeping an area
6920 void ai_stealth_sweep()
6921 {
6922         ai_info         *aip;
6923         ship_info       *sip;
6924
6925         SDL_assert(Ships[Pl_objp->instance].ship_info_index >= 0);
6926         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6927         SDL_assert(Ships[Pl_objp->instance].ai_index >= 0);
6928         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
6929
6930         vector goal_pt;
6931         vector forward, right, up;
6932         int lost_time;
6933
6934         // time since stealth last seen
6935         lost_time = (timestamp() - aip->stealth_last_visible_stamp);
6936
6937         // determine which pt to fly to in sweep by keeping track of parm0
6938         if (aip->submode_parm0 == SM_SS_SET_GOAL) {
6939
6940                 // don't make goal pt more than 2k from current pos
6941                 vm_vec_scale_add(&goal_pt, &aip->stealth_last_pos, &aip->stealth_velocity, (0.001f * lost_time));
6942
6943                 // make box size based on speed of stealth and expected time to intercept (keep box in range 200-500)
6944                 float box_size = vm_vec_mag_quick(&aip->stealth_velocity) * (0.001f * lost_time);
6945                 box_size = SDL_min(200.0f, box_size);
6946                 box_size = SDL_max(500.0f, box_size);
6947                 aip->stealth_sweep_box_size = box_size;
6948
6949                 aip->goal_point = goal_pt;
6950                 aip->submode_parm0 = SM_SS_BOX0;
6951         }
6952
6953         // GET UP, RIGHT, FORWARD FOR BOX based on stealth ship's velocity
6954         // if velocity changes in stealth mode, then ship is *seen*, and falls out of sweep mode
6955         // if stealth has no velocity make a velocity
6956         if ( vm_vec_mag_quick(&aip->stealth_velocity) < 1 ) {
6957                 vm_vec_rand_vec_quick(&aip->stealth_velocity);
6958         }
6959
6960         // get "right" vector for box
6961         vm_vec_crossprod(&right, &aip->stealth_velocity, &vmd_y_vector);
6962
6963         if ( vm_vec_mag_quick(&right) < 0.01 ) {
6964                 vm_vec_crossprod(&right, &aip->stealth_velocity, &vmd_z_vector);
6965         }
6966
6967         vm_vec_normalize_quick(&right);
6968
6969         // get forward for box
6970         vm_vec_copy_normalize_quick(&forward, &aip->stealth_velocity);
6971
6972         // get "up" for box
6973         vm_vec_crossprod(&up, &forward, &right);
6974         
6975         // lost far away ahead (do box)
6976         switch(aip->submode_parm0) {
6977         case SM_SS_BOX0:
6978                 goal_pt = aip->goal_point;
6979                 break;
6980
6981         // pt1 -U +R
6982         case SM_SS_LR:
6983                 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, -aip->stealth_sweep_box_size);
6984                 vm_vec_scale_add2(&goal_pt, &right, aip->stealth_sweep_box_size);
6985                 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
6986                 break;
6987
6988         // pt2 +U -R
6989         case SM_SS_UL:
6990                 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, aip->stealth_sweep_box_size);
6991                 vm_vec_scale_add2(&goal_pt, &right, -aip->stealth_sweep_box_size);
6992                 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
6993                 break;
6994
6995         // pt3 back
6996         case SM_SS_BOX1:
6997                 goal_pt = aip->goal_point;
6998                 break;
6999
7000         // pt4 +U +R
7001         case SM_SS_UR:
7002                 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, aip->stealth_sweep_box_size);
7003                 vm_vec_scale_add2(&goal_pt, &right, aip->stealth_sweep_box_size);
7004                 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
7005                 break;
7006
7007         // pt5 -U -R
7008         case SM_SS_LL:
7009                 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, -aip->stealth_sweep_box_size);
7010                 vm_vec_scale_add2(&goal_pt, &right, -aip->stealth_sweep_box_size);
7011                 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
7012                 break;
7013
7014         // pt6 back
7015         case SM_SS_BOX2:
7016                 goal_pt = aip->goal_point;
7017                 break;
7018
7019         default:
7020                 Int3();
7021
7022         }
7023
7024         // when close to goal_pt, update next goal pt
7025         float dist_to_goal = vm_vec_dist(&goal_pt, &Pl_objp->pos);
7026         if (dist_to_goal < 15) {
7027                 aip->submode_parm0++;
7028         }
7029
7030         // check for collision with big ship
7031         if (maybe_avoid_big_ship(Pl_objp, En_objp, aip, &goal_pt, 10.0f)) {
7032                 // skip to the next pt on box
7033                 aip->submode_parm0++;
7034                 return;
7035         }
7036
7037         ai_turn_towards_vector(&goal_pt, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
7038
7039         float dot = 1.0f;
7040         if (dist_to_goal < 100) {
7041                 vector vec_to_goal;
7042                 vm_vec_normalized_dir(&vec_to_goal, &goal_pt, &Pl_objp->pos);
7043                 dot = vm_vec_dotprod(&vec_to_goal, &Pl_objp->orient.v.fvec);
7044         }
7045
7046         accelerate_ship(aip, 0.8f*dot);
7047 }
7048
7049 //      ATTACK submode handler for chase mode.
7050 void ai_chase_attack(ai_info *aip, ship_info *sip, vector *predicted_enemy_pos, float dist_to_enemy)
7051 {
7052         int             start_bank;
7053         float           dot_to_enemy, dot_from_enemy; //, time_to_hit;
7054         float           bank_override = 0.0f;
7055
7056         if (avoid_player(Pl_objp, predicted_enemy_pos))
7057                 return;
7058
7059         compute_dots(Pl_objp, En_objp, &dot_to_enemy, &dot_from_enemy);
7060
7061         polymodel *po = model_get( sip->modelnum );
7062
7063         vector  *rel_pos;
7064         float           scale;
7065         vector  randvec;
7066         vector  new_pos;
7067
7068         start_bank = Ships[aip->shipnum].weapons.current_primary_bank;
7069         if (po->n_guns && start_bank != -1 ) {
7070                 rel_pos = &po->gun_banks[start_bank].pnt[0];
7071         } else
7072                 rel_pos = NULL;
7073
7074         //      If ship moving slowly relative to its size, then don't attack its center point.
7075         //      How far from center we attack is based on speed, size and distance to enemy
7076         if (En_objp->radius > En_objp->phys_info.speed) {
7077                 static_randvec(Pl_objp-Objects, &randvec);
7078                 scale = dist_to_enemy/(dist_to_enemy + En_objp->radius) * En_objp->radius;
7079                 scale *= 0.5f * En_objp->radius/(En_objp->phys_info.speed + En_objp->radius);   // scale downward by 1/2 to 1/4
7080                 vm_vec_scale_add(&new_pos, predicted_enemy_pos, &randvec, scale);
7081         } else
7082                 new_pos = *predicted_enemy_pos;
7083
7084         if (dist_to_enemy < 250.0f) {
7085                 if (dot_from_enemy > 0.7f) {
7086                         bank_override = Pl_objp->phys_info.speed;
7087                 }
7088         }
7089
7090         //      If enemy more than 500 meters away, all ships flying there will tend to match bank.
7091         //      They do this by using their vector to their target to compute their right vector and causing ai_turn_towards_vector
7092         //      to interpolate a matrix rather than just a vector.
7093         if (dist_to_enemy > 500.0f) {
7094                 vector  rvec;
7095                 compute_desired_rvec(&rvec, predicted_enemy_pos, &Pl_objp->pos);
7096                 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, rel_pos, bank_override, 0, &rvec);
7097         } else {
7098                 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, rel_pos, bank_override, 0);
7099         }
7100
7101         attack_set_accel(aip, dist_to_enemy, dot_to_enemy, dot_from_enemy);
7102 }
7103
7104 //      EVADE_SQUIGGLE submode handler for chase mode.
7105 //      Changed by MK on 5/5/97.
7106 //      Used to evade towards a point off the right or up vector.
7107 //      Now, evade straight away to try to get far away.
7108 //      The squiggling should protect against laser fire.
7109 void ai_chase_es(ai_info *aip, ship_info *sip)
7110 {
7111         vector  tvec;
7112         fix             timeslice;
7113         fix             scale;
7114         float           bank_override = 0.0f;
7115
7116         tvec = Pl_objp->pos;
7117
7118         timeslice = (Missiontime >> 16) & 0x0f;
7119         scale = ((Missiontime >> 16) & 0x0f) << 14;
7120
7121         if (timeslice & 0x01)
7122                 vm_vec_scale_add2(&tvec, &Pl_objp->orient.v.rvec, f2fl(scale ^ 0x10000));
7123         if (timeslice & 0x02)
7124                 vm_vec_scale_sub2(&tvec, &Pl_objp->orient.v.rvec, f2fl(scale));
7125         if (timeslice & 0x04)
7126                 vm_vec_scale_add2(&tvec, &Pl_objp->orient.v.uvec, f2fl(scale ^ 0x10000));
7127         if (timeslice & 0x08)
7128                 vm_vec_scale_sub2(&tvec, &Pl_objp->orient.v.uvec, f2fl(scale));
7129
7130         while (vm_vec_dist_quick(&tvec, &Pl_objp->pos) < 0.1f) {
7131                 tvec.xyz.x += frand();
7132                 tvec.xyz.y += frand();
7133         }
7134
7135         bank_override = Pl_objp->phys_info.speed;
7136
7137         ai_turn_towards_vector(&tvec, Pl_objp, flFrametime/2, sip->srotation_time, NULL, NULL, bank_override, 0);
7138         accelerate_ship(aip, 1.0f);
7139 }
7140
7141 //      Trying to get away from opponent.
7142 void ai_chase_ga(ai_info *aip, ship_info *sip)
7143 {
7144         //      If not near end of this submode, evade squiggly.  If near end, just fly straight for a bit
7145         vector  tvec;
7146         float           bank_override;
7147         vector  vec_from_enemy;
7148
7149         if (En_objp != NULL) {
7150                 vm_vec_normalized_dir(&vec_from_enemy, &Pl_objp->pos, &En_objp->pos);
7151         } else
7152                 vec_from_enemy = Pl_objp->orient.v.fvec;
7153
7154         static_randvec(Missiontime >> 15, &tvec);
7155         vm_vec_scale(&tvec, 100.0f);
7156         vm_vec_scale_add2(&tvec, &vec_from_enemy, 300.0f);
7157         vm_vec_add2(&tvec, &Pl_objp->pos);
7158
7159         bank_override = Pl_objp->phys_info.speed;
7160
7161         ai_turn_towards_vector(&tvec, Pl_objp, flFrametime/2, sip->srotation_time, NULL, NULL, bank_override, 0);
7162
7163         accelerate_ship(aip, 2.0f);
7164
7165         if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
7166                 if (!(Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
7167                         float percent_left = 100.0f * Ships[Pl_objp->instance].afterburner_fuel / sip->afterburner_fuel_capacity;
7168                         if (percent_left > 30.0f + ((Pl_objp-Objects) & 0x0f)) {
7169                                 afterburners_start(Pl_objp);
7170                                 aip->afterburner_stop_time = Missiontime + 3*F1_0/2;
7171                         }
7172                         afterburners_start(Pl_objp);
7173                         aip->afterburner_stop_time = Missiontime + 3*F1_0/2;
7174                 }
7175         }
7176
7177 }
7178
7179 //      Make object *objp attack subsystem with ID = subnum.
7180 //      Return true if found a subsystem to attack, else return false.
7181 //      Note, can fail if subsystem exists, but has no hits.
7182 int ai_set_attack_subsystem(object *objp, int subnum)
7183 {
7184         ship                    *shipp, *attacker_shipp;
7185         ai_info         *aip;
7186         ship_subsys     *ssp;
7187         object          *attacked_objp;
7188
7189         SDL_assert(objp->type == OBJ_SHIP);
7190         SDL_assert(objp->instance >= 0);
7191
7192         attacker_shipp = &Ships[objp->instance];
7193         SDL_assert(attacker_shipp->ai_index >= 0);
7194
7195         aip = &Ai_info[attacker_shipp->ai_index];
7196
7197         // MWA -- 2/27/98.  Due to AL's changes, target_objnum is now not always valid (at least sometimes
7198         // in terms of goals).  So, bail if we don't have a valid target.
7199         if ( aip->target_objnum == -1 )
7200                 return 0;
7201
7202         attacked_objp = &Objects[aip->target_objnum];
7203         shipp = &Ships[attacked_objp->instance];                //  need to get our target's ship pointer!!!
7204
7205         ssp = ship_get_indexed_subsys(shipp, subnum, &objp->pos);
7206         if (ssp == NULL)
7207                 return 0;
7208
7209         set_targeted_subsys(aip, ssp, aip->target_objnum);
7210         
7211         if (aip->ignore_objnum == aip->target_objnum)
7212                 aip->ignore_objnum = UNUSED_OBJNUM;
7213
7214         // -- Done at caller in ai_process_mission_orders -- attacked_objp->flags |= OF_PROTECTED;
7215
7216         ai_set_goal_maybe_abort_dock(objp, aip);
7217         aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);
7218
7219         return 1;
7220 }
7221
7222 void ai_set_guard_vec(object *objp, object *guard_objp)
7223 {
7224         ai_info *aip;
7225         float   radius;
7226
7227         aip = &Ai_info[Ships[objp->instance].ai_index];
7228
7229         //      Handle case of bogus call in which ship is told to guard self.
7230         SDL_assert(objp != guard_objp);
7231         if (objp == guard_objp) {
7232                 vm_vec_rand_vec_quick(&aip->guard_vec);
7233                 vm_vec_scale(&aip->guard_vec, 100.0f);
7234                 return;
7235         }
7236
7237         // check if guard_objp is BIG
7238         radius = 5.0f * (objp->radius + guard_objp->radius) + 50.0f;
7239         if (radius > 300.0f) {
7240                 radius = guard_objp->radius * 1.25f;
7241         }
7242
7243         vm_vec_sub(&aip->guard_vec, &objp->pos, &guard_objp->pos);
7244
7245         if (vm_vec_mag(&aip->guard_vec) > 3.0f*radius) {
7246                 //      Far away, don't just use vector to object, causes clustering of guard ships.
7247                 vector  tvec, rvec;
7248                 float   mag;
7249                 mag = vm_vec_copy_normalize(&tvec, &aip->guard_vec);
7250                 vm_vec_rand_vec_quick(&rvec);                   
7251                 vm_vec_scale_add2(&tvec, &rvec, 0.5f);
7252                 vm_vec_copy_scale(&aip->guard_vec, &tvec, mag);
7253         }
7254
7255         vm_vec_normalize_quick(&aip->guard_vec);
7256         vm_vec_scale(&aip->guard_vec, radius);
7257 }
7258
7259 //      Make object *objp guard object *other_objp.
7260 //      To be called from the goals code.
7261 void ai_set_guard_wing(object *objp, int wingnum)
7262 {
7263         ship            *shipp;
7264         ai_info *aip;
7265         int             leader_objnum, leader_shipnum;
7266
7267         SDL_assert(wingnum >= 0);
7268
7269         SDL_assert(objp->type == OBJ_SHIP);
7270         SDL_assert(objp->instance >= 0);
7271
7272         // shouldn't set the ai mode for the player
7273         if ( objp == Player_obj ) {
7274                 return;
7275         }
7276
7277         shipp = &Ships[objp->instance];
7278
7279         SDL_assert(shipp->ai_index >= 0);
7280
7281         aip = &Ai_info[shipp->ai_index];
7282         force_avoid_player_check(objp, aip);
7283
7284         ai_set_goal_maybe_abort_dock(objp, aip);
7285         aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);
7286
7287         //      This function is called whenever a guarded ship is destroyed, so this code
7288         //      prevents a ship from trying to guard a non-existent wing.
7289         if (Wings[wingnum].current_count < 1) {
7290                 aip->guard_objnum = -1;
7291                 aip->guard_wingnum = -1;
7292                 aip->mode = AIM_NONE;
7293         } else {
7294                 leader_shipnum = Wings[wingnum].ship_index[0];
7295                 leader_objnum = Ships[leader_shipnum].objnum;
7296
7297                 SDL_assert((leader_objnum >= 0) && (leader_objnum < MAX_OBJECTS));
7298                 //SDL_assert(leader_objnum != objp-Objects);    //      Don't allow ships to guard themselves.
7299                 if (leader_objnum == OBJ_INDEX(objp)) {
7300                         //Int3();       //      Seems illegal, but let's clean up.  Get MikeK.
7301                         return;
7302                 }
7303
7304                 aip->guard_wingnum = wingnum;
7305                 aip->guard_objnum = leader_objnum;
7306                 aip->guard_signature = Objects[leader_objnum].signature;
7307                 aip->mode = AIM_GUARD;
7308                 aip->submode = AIS_GUARD_STATIC;
7309
7310                 ai_set_guard_vec(objp, &Objects[leader_objnum]);
7311         }
7312 }
7313
7314 //      Make object *objp guard object *other_objp.
7315 //      To be called from the goals code.
7316 void ai_set_evade_object(object *objp, object *other_objp)
7317 {
7318         ship            *shipp;
7319         ai_info *aip;
7320         int             other_objnum;
7321
7322         SDL_assert(objp->type == OBJ_SHIP);
7323         SDL_assert(objp->instance >= 0);
7324
7325         shipp = &Ships[objp->instance];
7326
7327         SDL_assert(shipp->ai_index >= 0);
7328
7329         aip = &Ai_info[shipp->ai_index];
7330
7331         other_objnum = OBJ_INDEX(other_objp);
7332         SDL_assert(other_objnum >= 0);
7333
7334         SDL_assert(other_objnum != Ships[aip->shipnum].objnum); //      make sure not targeting self
7335         aip->target_objnum = other_objnum;
7336
7337         aip->mode = AIM_EVADE;
7338 }
7339
7340 //      Make objp guard other_objp
7341 //      If other_objp is a member of a wing, objp will guard that whole wing
7342 //      UNLESS objp is also a member of the wing!
7343 void ai_set_guard_object(object *objp, object *other_objp)
7344 {
7345         ship            *shipp;
7346         ai_info *aip;
7347         int             other_objnum;
7348
7349         SDL_assert(objp->type == OBJ_SHIP);
7350         SDL_assert(objp->instance >= 0);
7351         SDL_assert(objp != other_objp);
7352
7353         shipp = &Ships[objp->instance];
7354
7355         SDL_assert(shipp->ai_index >= 0);
7356
7357         aip = &Ai_info[shipp->ai_index];
7358         aip->avoid_check_timestamp = timestamp(1);
7359
7360         //      If ship to guard is in a wing, guard that whole wing.
7361         ai_info *other_aip = &Ai_info[Ships[other_objp->instance].ai_index];
7362         if ((other_aip->wing != -1) && (other_aip->wing != aip->wing)) {
7363                 ai_set_guard_wing(objp, Ai_info[Ships[other_objp->instance].ai_index].wing);
7364         } else {
7365
7366                 other_objnum = other_objp-Objects;
7367
7368                 aip->guard_objnum = other_objnum;
7369                 aip->guard_signature = other_objp->signature;
7370                 aip->guard_wingnum = -1;
7371
7372                 aip->mode = AIM_GUARD;
7373                 aip->submode = AIS_GUARD_STATIC;
7374
7375                 SDL_assert(other_objnum >= 0);  //      Hmm, bogus object and we need its position for guard_vec.
7376
7377                 // vm_vec_sub(&aip->guard_vec, &objp->pos, &Objects[other_objnum].pos);
7378                 ai_set_guard_vec(objp, &Objects[other_objnum]);
7379
7380                 ai_set_goal_maybe_abort_dock(objp, aip);
7381                 aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);
7382         }
7383 }
7384
7385 //      Update the aspect_locked_time field based on whether enemy is in view cone.
7386 //      Also set/clear AIF_SEEK_LOCK.
7387 void update_aspect_lock_information(ai_info *aip, vector *vec_to_enemy, float dist_to_enemy, float enemy_radius)
7388 {
7389         float   dot_to_enemy;
7390         int     num_weapon_types;
7391         int     weapon_id_list[MAX_WEAPON_TYPES], weapon_bank_list[MAX_WEAPON_TYPES];
7392         ship    *shipp;
7393         ship_weapon     *swp;
7394         weapon_info     *wip;
7395
7396         shipp = &Ships[aip->shipnum];
7397         swp = &shipp->weapons;
7398
7399         // AL 3-7-98: This probably should never happen, but check to ensure that current_secondary_bank is valid
7400         if ( (swp->current_secondary_bank < 0) || (swp->current_secondary_bank > swp->num_secondary_banks) ) {
7401                 return;
7402         }
7403
7404         num_weapon_types = get_available_secondary_weapons(Pl_objp, weapon_id_list, weapon_bank_list);
7405
7406         wip = &Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]];
7407
7408         if (num_weapon_types && (wip->wi_flags & WIF_HOMING_ASPECT)) {
7409                 if (dist_to_enemy > 300.0f - SDL_min(enemy_radius, 100.0f))
7410                         aip->ai_flags |= AIF_SEEK_LOCK;
7411                 else
7412                         aip->ai_flags &= ~AIF_SEEK_LOCK;
7413
7414                 //      Update locking information for aspect seeking missiles.
7415                 aip->current_target_is_locked = 0;
7416                 dot_to_enemy = vm_vec_dot(vec_to_enemy, &Pl_objp->orient.v.fvec);
7417
7418                 float   needed_dot = 0.9f - 0.5f * enemy_radius/(dist_to_enemy + enemy_radius); //      Replaced MIN_TRACKABLE_DOT with 0.9f
7419                 if (dot_to_enemy > needed_dot) {
7420                         aip->aspect_locked_time += flFrametime;
7421                         // nprintf(("AI", "+ Lock time = %7.3f\n", aip->aspect_locked_time));
7422                         if (aip->aspect_locked_time >= wip->min_lock_time) {
7423                                 aip->aspect_locked_time = wip->min_lock_time;
7424                                 aip->current_target_is_locked = 1;
7425                         }
7426                 } else {
7427                         aip->aspect_locked_time -= flFrametime*2;
7428                         // nprintf(("AI", "- Lock time = %7.3f\n", aip->aspect_locked_time));
7429                         if (aip->aspect_locked_time < 0.0f)
7430                                 aip->aspect_locked_time = 0.0f;
7431                 }
7432                 //nprintf(("AI", "dot = %7.3f, time = %7.3f\n", dot_to_enemy, aip->aspect_locked_time));
7433         
7434         } else {
7435                 aip->current_target_is_locked = 0;
7436                 aip->aspect_locked_time = 0.0f; // Used to be this, why?: wip->min_lock_time;
7437                 aip->ai_flags &= ~AIF_SEEK_LOCK;
7438         }
7439
7440 }
7441
7442 //      We're in chase mode and we've recently collided with our target.
7443 //      Fly away from it!
7444 void ai_chase_fly_away(object *objp, ai_info *aip)
7445 {
7446         int     abort_flag = 0;
7447
7448         if (aip->ai_flags & AIF_TARGET_COLLISION) {
7449                 aip->ai_flags &= ~AIF_TARGET_COLLISION; //      Don't process this hit again next frame.
7450                 aip->submode = SM_FLY_AWAY;                                     //      Focus on avoiding target
7451                 aip->submode_start_time = Missiontime;
7452         }
7453
7454         if ((aip->target_objnum == -1) || (Objects[aip->target_objnum].signature != aip->target_signature)) {
7455                 abort_flag = 1;
7456         }
7457
7458         if (abort_flag || (Missiontime > aip->submode_start_time + F1_0)) {
7459                 aip->last_attack_time = Missiontime;
7460                 aip->submode = SM_ATTACK;
7461                 aip->submode_start_time = Missiontime;
7462         } else {
7463                 vector  v2e;
7464                 float           dot;
7465
7466                 vm_vec_normalized_dir(&v2e, &Objects[aip->target_objnum].pos, &objp->pos);
7467
7468                 dot = vm_vec_dot(&objp->orient.v.fvec, &v2e);
7469                 if (dot < 0.0f)
7470                         accelerate_ship(aip, 1.0f);
7471                 else
7472                         accelerate_ship(aip, 1.0f - dot);
7473                 turn_away_from_point(objp, &Objects[aip->target_objnum].pos, 0.0f);
7474         }
7475 }
7476
7477 //      Return bank index of favored secondary weapon.
7478 //      Return -1 if nothing favored.
7479 //      "favored" means SEXPs have specified the weapon as being good to fire at en_objp.
7480 int has_preferred_secondary(object *objp, object *en_objp, ship_weapon *swp)
7481 {
7482 // int is_preferred_weapon(int weapon_num, object *firer_objp, object *target_objp)
7483         int     i;
7484
7485         for (i=0; i<swp->num_secondary_banks; i++) {
7486                 if (swp->secondary_bank_capacity[i] > 0) {
7487                         if (swp->secondary_bank_ammo[i] > 0) {
7488                                 if (is_preferred_weapon(swp->secondary_bank_weapons[i], objp, en_objp) != -1){
7489                                         return i;
7490                                 }
7491                         }
7492                 }
7493         }
7494
7495         return -1;
7496 }
7497
7498 //      Choose which secondary weapon to fire.
7499 //      Note, this is not like ai_select_secondary_weapon().  "choose" means make a choice.
7500 //      "select" means execute an order.  Get it?
7501 //      This function calls ai_select_secondary_weapon() with the characteristics it should search for.
7502 void ai_choose_secondary_weapon(object *objp, ai_info *aip, object *en_objp)
7503 {
7504         float                   subsystem_strength = 0.0f;
7505         int                     is_big_ship, priority1, priority2;
7506         ship_weapon     *swp;
7507         ship_info       *esip;
7508
7509         if ( en_objp->type == OBJ_SHIP ) {
7510                 esip = &Ship_info[Ships[en_objp->instance].ship_info_index];
7511         } else {
7512                 esip = NULL;
7513         }
7514
7515         swp = &Ships[objp->instance].weapons;
7516
7517         // AL 3-5-98: do a quick out if the ship has no secondaries
7518         if ( swp->num_secondary_banks <= 0 ) {
7519                 swp->current_secondary_bank = -1;
7520                 return;
7521         }
7522
7523         int preferred_secondary = has_preferred_secondary(objp, en_objp, swp);
7524
7525         if (preferred_secondary != -1) {
7526                 if (swp->current_secondary_bank != preferred_secondary) {
7527                         aip->current_target_is_locked = 0;
7528                         aip->aspect_locked_time = 0.0f;
7529                         swp->current_secondary_bank = preferred_secondary;
7530                 }
7531                 //nprintf(("AI", "Favored secondary = %s\n", Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]].name));
7532                 aip->ai_flags |= AIF_UNLOAD_SECONDARIES;
7533         } else {
7534                 aip->ai_flags &= ~AIF_UNLOAD_SECONDARIES;
7535                 if (aip->targeted_subsys) {
7536                         subsystem_strength = aip->targeted_subsys->current_hits;
7537                 }
7538
7539                 if ( esip ) {
7540                         is_big_ship = esip->flags & (SIF_HUGE_SHIP | SIF_BIG_SHIP);
7541                 } else {
7542                         is_big_ship=0;
7543                 }
7544
7545                 if (is_big_ship) {
7546                         priority1 = WIF_HUGE;
7547                         priority2 = WIF_HOMING;
7548                 } else if ( (esip != NULL) && (esip->flags & SIF_BOMBER) ) {
7549                         priority1 = WIF_BOMBER_PLUS;
7550                         priority2 = WIF_HOMING;
7551                 } else if (subsystem_strength > 100.0f) {
7552                         priority1 = WIF_PUNCTURE;
7553                         priority2 = WIF_HOMING;
7554                 } else {
7555                         priority1 = WIF_HOMING;
7556                         priority2 = 0;
7557                 }
7558                 
7559                 ai_select_secondary_weapon(objp, swp, priority1, priority2);
7560         }
7561
7562         // nprintf(("AI", "Frame %i: Chose secondary %s\n", Framecount, Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]].name));
7563 }
7564
7565 //      Return time, in seconds, at which this ship can next fire its current secondary weapon.
7566 float set_secondary_fire_delay(ai_info *aip, ship *shipp, weapon_info *swip)
7567 {
7568         float t = swip->fire_wait;              //      Base delay for this weapon.
7569         if (shipp->team == Player_ship->team) {
7570                 //      On player's team, _lower_ skill level = faster firing
7571                 t = t * (Game_skill_level+2) / (NUM_SKILL_LEVELS);
7572         } else {                //      Not on player's team, higher skill level = faster firing
7573                 t = t * (NUM_SKILL_LEVELS - Game_skill_level+2) / (NUM_SKILL_LEVELS);
7574         }
7575
7576         t += (Num_ai_classes - aip->ai_class + 1) * 0.5f;
7577         t *= frand_range(0.8f, 1.2f);
7578
7579         //      For the missiles that fire fairly quickly, occasionally add an additional substantial delay.
7580         if (t < 5.0f)
7581                 if (frand() < 0.5f)
7582                         t = t * 2.0f + 2.0f;
7583
7584         return t;
7585 }
7586
7587
7588 void ai_chase_big_approach_set_goal(vector *goal_pos, object *attack_objp, object *target_objp, float *accel)
7589 {
7590         float dist_to_goal;
7591
7592         // head straight toward him and maybe circle later
7593         vm_vec_avg(goal_pos, &attack_objp->pos, &target_objp->pos);
7594
7595         // get distance to goal
7596         dist_to_goal = vm_vec_dist(goal_pos, &attack_objp->pos);
7597         
7598         // set accel
7599         if (dist_to_goal > 400.0f) {
7600                 *accel = 1.0f;
7601         } else {
7602                 *accel = dist_to_goal/400.0f;
7603         }
7604 }
7605
7606 void ai_chase_big_circle_set_goal(vector *goal_pos, object *attack_objp, object *target_objp, float *accel)
7607 {
7608         get_tangent_point(goal_pos, attack_objp, &target_objp->pos, attack_objp->radius + target_objp->radius + 100.0f);
7609
7610         *accel = 1.0f;
7611 }
7612
7613 // get the current and desired horizontal separations between target
7614 void ai_chase_big_get_separations(object *attack_objp, object *target_objp, vector *horz_vec_to_target, float *desired_separation, float *cur_separation)
7615 {
7616         float temp, r_target, r_attacker;
7617         float perp_dist;
7618         vector vec_to_target;
7619         polymodel *pm;
7620
7621         // get parameters of ships (as cylinders - radius and height)
7622         // get radius of attacker (for rotations about forward)
7623         pm = model_get(Ships[attack_objp->instance].modelnum);
7624         temp = SDL_max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7625         r_attacker = SDL_max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7626         r_attacker = SDL_max(temp, r_attacker);
7627
7628         // get radius of target (for rotations about forward)
7629         pm = model_get(Ships[attack_objp->instance].modelnum);
7630         temp = SDL_max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7631         r_target = SDL_max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7632         r_target = SDL_max(temp, r_target);
7633
7634         // find separation between cylinders [if parallel]
7635         vm_vec_sub(&vec_to_target, &attack_objp->pos, &target_objp->pos);
7636
7637         // find the distance between centers along forward direction of ships
7638         perp_dist = vm_vec_dotprod(&vec_to_target, &target_objp->orient.v.fvec);
7639
7640         // subtract off perp component to get "horizontal" separation vector between cylinders [ASSUMING parallel]
7641         vm_vec_scale_add(horz_vec_to_target, &vec_to_target, &target_objp->orient.v.fvec, -perp_dist);
7642         *cur_separation = vm_vec_mag_quick(horz_vec_to_target);
7643
7644         // choose "optimal" separation of 1000 + r_target + r_attacker
7645         *desired_separation = 1000 + r_target + r_attacker;
7646 }
7647
7648 void ai_chase_big_parallel_set_goal(vector *goal_pos, object *attack_objp, object *target_objp, float *accel)
7649 {
7650         int opposing;
7651         float separation, optimal_separation;
7652         vector  horz_vec_to_target;
7653
7654         /*
7655         float temp, r_target, r_attacker;
7656         polymodel *pm;
7657
7658         // get parameters of ships (as cylinders - radius and height)
7659         // get radius of attacker (for rotations about forward)
7660         pm = model_get(Ships[attack_objp->instance].modelnum);
7661         temp = SDL_max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7662         r_attacker = SDL_max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7663         r_attacker = SDL_max(temp, r_attacker);
7664
7665         // get radius of target (for rotations about forward)
7666         pm = model_get(Ships[attack_objp->instance].modelnum);
7667         temp = SDL_max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7668         r_target = SDL_max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7669         r_target = SDL_max(temp, r_target);
7670         */
7671
7672         // are we opposing (only when other ship is not moving)
7673         opposing = ( vm_vec_dotprod(&attack_objp->orient.v.fvec, &target_objp->orient.v.fvec) < 0 );
7674
7675         ai_chase_big_get_separations(attack_objp, target_objp, &horz_vec_to_target, &optimal_separation, &separation);
7676
7677         // choose dist (2000) so that we don't bash
7678         float dist = 2000;
7679         if (opposing) {
7680                 dist = - dist;
7681         }
7682
7683         // set the goal pos as dist forward from target along target forward
7684         vm_vec_scale_add(goal_pos, &target_objp->pos, &target_objp->orient.v.fvec, dist);
7685         // then add horizontal separation
7686         vm_vec_scale_add2(goal_pos, &horz_vec_to_target, optimal_separation/separation);
7687
7688         // find the distance between centers along forward direction of ships
7689         vector vec_to_target;
7690         vm_vec_sub(&vec_to_target, &target_objp->pos, &attack_objp->pos);
7691         float perp_dist = vm_vec_dotprod(&vec_to_target, &target_objp->orient.v.fvec);
7692
7693         float match_accel = target_objp->phys_info.vel.xyz.z / Ship_info[Ships[attack_objp->instance].ship_info_index].max_vel.xyz.z;
7694         float length_scale = attack_objp->radius;
7695
7696         // if we're heading toward enemy ship, we want to keep going if we're ahead
7697         if (opposing) {
7698                 perp_dist = -perp_dist;
7699         }
7700
7701         if (perp_dist > 0) {
7702                 // falling behind, so speed up
7703                 *accel = match_accel + (1.0f - match_accel) / length_scale * (perp_dist);
7704         } else {
7705                 // up in front, so slow down
7706                 *accel = match_accel  - match_accel / length_scale * -perp_dist;
7707                 *accel = SDL_max(0.0f, *accel);
7708         }
7709
7710 }
7711
7712
7713 //      Return *goal_pos for one cruiser to attack another (big ship).
7714 //      Choose point fairly nearby that is not occupied by another cruiser.
7715 void ai_cruiser_chase_set_goal_pos(vector *goal_pos, object *pl_objp, object *en_objp)
7716 {
7717         ai_info *aip;
7718
7719         aip = &Ai_info[Ships[pl_objp->instance].ai_index];
7720         float accel;
7721
7722         switch (aip->submode) {
7723         case SM_BIG_APPROACH:
7724                 // do approach stuff;
7725                 ai_chase_big_approach_set_goal(goal_pos, pl_objp, en_objp, &accel);
7726                 break;
7727
7728         case SM_BIG_CIRCLE:
7729                 // do circle stuff
7730                 ai_chase_big_circle_set_goal(goal_pos, pl_objp, en_objp, &accel);
7731                 break;
7732
7733         case SM_BIG_PARALLEL:
7734                 // do parallel stuff
7735                 ai_chase_big_parallel_set_goal(goal_pos, pl_objp, en_objp, &accel);
7736                 break;
7737         }
7738 }
7739
7740 int maybe_hack_cruiser_chase_abort()
7741 {
7742         ship                    *shipp = &Ships[Pl_objp->instance];     
7743         ship                    *eshipp = &Ships[En_objp->instance];
7744         ai_info         *aip = &Ai_info[shipp->ai_index];
7745
7746         // mission sm3-08, sathanos chasing collosus
7747         if ( SDL_strcasecmp(Mission_filename, "sm3-08.fs2") == 0 ) {
7748                 if (( SDL_strcasecmp(eshipp->ship_name, "colossus") == 0 ) || ( SDL_strcasecmp(shipp->ship_name, "colossus") == 0 )) {
7749                         // Changed so all big ships attacking the Colossus will not do the chase code.
7750                         // Did this so Beast wouldn't swerve away from Colossus. -- MK, 9/14/99
7751                         //if ( SDL_strcasecmp(shipp->ship_name, "Sathanas") == 0 ) {
7752                                 // do cool hack stuff here
7753                                 ai_clear_ship_goals( aip );
7754                                 aip->mode = AIM_NONE;
7755                                 return 1;
7756                         //}
7757                 }
7758         }
7759
7760         return 0;
7761 }
7762
7763 //      Make a big ship pursue another big ship.
7764 //      (Note, called "ai_cruiser_chase" because we already have ai_chase_big() which means fighter chases big ship.
7765 void ai_cruiser_chase()
7766 {
7767         ship_info       *sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
7768         ship                    *shipp = &Ships[Pl_objp->instance];     
7769         ai_info         *aip = &Ai_info[shipp->ai_index];
7770
7771         if (!(sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
7772                 Int3(); //      Hmm, not a very big ship, how did we get in this function?
7773                 aip->mode = AIM_NONE;
7774                 return;
7775         }
7776
7777         if (En_objp->type != OBJ_SHIP) {
7778                 Int3();
7779                 return;
7780         }
7781
7782         if (En_objp->instance < 0) {
7783                 Int3();
7784                 return;
7785         }
7786
7787         ship                    *eshipp;
7788         ship_info       *esip;
7789
7790         eshipp = &Ships[En_objp->instance];
7791         esip = &Ship_info[eshipp->ship_info_index];
7792
7793         if (!(esip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
7794                 // Int3();      //      Hmm, we're big and we're pursuing something other than a big ship?
7795                 aip->mode = AIM_NONE;
7796                 return;
7797         }
7798
7799         vector  goal_pos;
7800         float turn_time = Ship_info[Ships[Pl_objp->instance].ship_info_index].srotation_time;
7801
7802         // kamikaze - ram and explode
7803         if (aip->ai_flags & AIF_KAMIKAZE) {
7804                 ai_turn_towards_vector(&En_objp->pos, Pl_objp, flFrametime, turn_time, NULL, NULL, 0.0f, 0);
7805                 accelerate_ship(aip, 1.0f);
7806         } 
7807         
7808         // really track down and chase
7809         else {
7810                 // check valid submode
7811                 SDL_assert( (aip->submode == SM_ATTACK) || (aip->submode == SM_BIG_APPROACH) || (aip->submode == SM_BIG_CIRCLE) || (aip->submode == SM_BIG_PARALLEL) );
7812
7813                 // just entering, approach enemy ship
7814                 if (aip->submode == SM_ATTACK) {
7815                         aip->submode = SM_BIG_APPROACH;
7816                 }
7817
7818                 // desired accel
7819                 float accel = 0.0f;
7820                 vector *rvecp = NULL;
7821
7822                 switch (aip->submode) {
7823                 case SM_BIG_APPROACH:
7824                         // do approach stuff;
7825                         ai_chase_big_approach_set_goal(&goal_pos, Pl_objp, En_objp, &accel);
7826                         // maybe set rvec
7827                         break;
7828
7829                 case SM_BIG_CIRCLE:
7830                         // do circle stuff
7831                         ai_chase_big_circle_set_goal(&goal_pos, Pl_objp, En_objp, &accel);
7832                         // maybe set rvec
7833                         break;
7834
7835                 case SM_BIG_PARALLEL:
7836                         // do parallel stuff
7837                         ai_chase_big_parallel_set_goal(&goal_pos, Pl_objp, En_objp, &accel);
7838                         //maybe set rvec
7839                         break;
7840                 }
7841
7842
7843                 // now move as desired
7844                 ai_turn_towards_vector(&goal_pos, Pl_objp, flFrametime, turn_time, NULL, NULL, 0.0f, 0, rvecp);
7845                 accelerate_ship(aip, accel);
7846
7847
7848                 // maybe switch to new mode
7849                 vector vec_to_enemy;
7850                 float dist_to_enemy;
7851                 int moving = (En_objp->phys_info.vel.xyz.z > 0.5f);
7852                 vm_vec_sub(&vec_to_enemy, &En_objp->pos, &Pl_objp->pos);
7853                 dist_to_enemy = vm_vec_mag_quick(&vec_to_enemy);
7854
7855                 switch (aip->submode) {
7856                 case SM_BIG_APPROACH:
7857                         if ( dist_to_enemy < (Pl_objp->radius + En_objp->radius)*1.25f + 200.0f ) {
7858                                 // moving
7859                                 if (moving) {
7860                                         // if within 90 degrees of en forward, go into parallel, otherwise circle
7861                                         if ( vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) > 0 ) {
7862                                                 aip->submode = SM_BIG_PARALLEL;
7863                                         }
7864                                 }
7865
7866                                 // otherwise cirle
7867                                 if ( !maybe_hack_cruiser_chase_abort() ) {
7868                                         aip->submode = SM_BIG_CIRCLE;
7869                                 }
7870                         }
7871                         break;
7872
7873                 case SM_BIG_CIRCLE:
7874                         // moving
7875                         if (moving) {
7876                                 vector temp;
7877                                 float desired_sep, cur_sep;
7878                                 // we're behind the enemy ship
7879                                 if (vm_vec_dotprod(&vec_to_enemy, &En_objp->orient.v.fvec) > 0) {
7880                                         // and we're turning toward the enemy
7881                                         if (vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) > 0) {
7882                                                 // get separation
7883                                                 ai_chase_big_get_separations(Pl_objp, En_objp, &temp, &desired_sep, &cur_sep);
7884                                                 // and the separation is > 0.9 desired
7885                                                 if (cur_sep > 0.9 * desired_sep) {
7886                                                         aip->submode = SM_BIG_PARALLEL;
7887                                                 }
7888                                         }
7889                                 }
7890                         } else {
7891                                 // still
7892                                 vector temp;
7893                                 float desired_sep, cur_sep;
7894                                 // we're behind the enemy ship
7895                                 if (vm_vec_dotprod(&vec_to_enemy, &En_objp->orient.v.fvec) > 0) {
7896                                         // and we're turning toward the enemy
7897                                         if (vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) > 0) {
7898                                                 // get separation
7899                                                 ai_chase_big_get_separations(Pl_objp, En_objp, &temp, &desired_sep, &cur_sep);
7900                                                 //and the separation is [0.9 to 1.1] desired
7901                                                 if ( (cur_sep > 0.9f * desired_sep) ) {
7902                                                         aip->submode = SM_BIG_PARALLEL;
7903                                                 }
7904                                         }
7905                                 }
7906                                 // in front of ship
7907                                 else {
7908                                         // and we're turning toward the enemy
7909                                         if (vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) < 0) {
7910                                                 // get separation
7911                                                 ai_chase_big_get_separations(Pl_objp, En_objp, &temp, &desired_sep, &cur_sep);
7912                                                 //and the separation is [0.9 to 1.1] desired
7913                                                 if ( (cur_sep > 0.9f * desired_sep) ) {
7914                                                         aip->submode = SM_BIG_PARALLEL;
7915                                                 }
7916                                         }
7917                                 }
7918                         }
7919                         break;
7920
7921                 case SM_BIG_PARALLEL:
7922                         // we're opposing
7923                         if ( vm_vec_dotprod(&Pl_objp->orient.v.fvec, &En_objp->orient.v.fvec) < 0 ) {
7924                                 // and the other ship is moving
7925                                 if (moving) {
7926                                         // and we no longer overlap
7927                                         if ( dist_to_enemy > (0.75 * (En_objp->radius + Pl_objp->radius)) ) {
7928                                                 aip->submode = SM_BIG_APPROACH;
7929                                         }
7930                                 }
7931                         }
7932                         break;
7933                 }
7934         }
7935 }
7936
7937 // --------------------------------------------------------------------------
7938 // Make object Pl_objp chase object En_objp
7939 void ai_chase()
7940 {
7941         float                   dist_to_enemy;
7942         float                   dot_to_enemy, dot_from_enemy, real_dot_to_enemy;
7943         vector          player_pos, enemy_pos, predicted_enemy_pos, real_vec_to_enemy, predicted_vec_to_enemy;
7944         ship_info       *sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
7945         ship                    *shipp = &Ships[Pl_objp->instance];
7946         ship_weapon     *swp = &shipp->weapons;
7947         ai_info         *aip = &Ai_info[shipp->ai_index];
7948         int                     enemy_sip_flags;
7949
7950         if (aip->mode != AIM_CHASE) {
7951                 Int3();
7952         }
7953
7954         if (sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
7955                 ai_cruiser_chase();
7956                 return;
7957         }
7958
7959         if (!(sip->flags & (SIF_FIGHTER | SIF_BOMBER | SIF_ESCAPEPOD))) {
7960                 Warning(LOCATION, "Ship %s is not 'small', but is in chase mode.\nSwitching to AI=none.\n", shipp->ship_name);
7961                 aip->mode = AIM_NONE;
7962                 return;
7963         }
7964
7965         //nprintf(("AI", "%7s ", Submode_text[aip->submode]));
7966
7967         if ( En_objp->type == OBJ_SHIP ) {
7968                 enemy_sip_flags = Ship_info[Ships[En_objp->instance].ship_info_index].flags;
7969         } else {
7970                 enemy_sip_flags = 0;
7971         }
7972
7973         if ( enemy_sip_flags > 0 ) {
7974                 if (enemy_sip_flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
7975                         ai_big_chase();
7976                         return;
7977                 }
7978         }
7979
7980         //      If collided with target_objnum last frame, avoid that ship.
7981         //      This should prevent the embarrassing behavior of ships getting stuck on each other
7982         //      as if they were magnetically attracted. -- MK, 11/13/97.
7983         if ((aip->ai_flags & AIF_TARGET_COLLISION) || (aip->submode == SM_FLY_AWAY)) {
7984                 ai_chase_fly_away(Pl_objp, aip);
7985                 return;
7986         }
7987
7988         ai_set_positions(Pl_objp, En_objp, aip, &player_pos, &enemy_pos);
7989         dist_to_enemy = vm_vec_dist_quick(&player_pos, &enemy_pos);
7990         vm_vec_sub(&real_vec_to_enemy, &enemy_pos, &player_pos);
7991
7992         vm_vec_normalize(&real_vec_to_enemy);
7993
7994         real_dot_to_enemy = vm_vec_dot(&real_vec_to_enemy, &Pl_objp->orient.v.fvec);
7995
7996         int is_stealthy_ship = 0;
7997         if ( (enemy_sip_flags > 0) && (enemy_sip_flags & SIF_STEALTH) ) {
7998                 if ( ai_is_stealth_visible(Pl_objp, En_objp) != STEALTH_FULLY_TARGETABLE ) {
7999                         is_stealthy_ship = 1;
8000                 }
8001         }
8002
8003         // Can only acquire lock on a target that isn't hidden from sensors
8004         if ( !(Ships[En_objp->instance].flags & SF_HIDDEN_FROM_SENSORS) && !is_stealthy_ship ) {
8005                 update_aspect_lock_information(aip, &real_vec_to_enemy, dist_to_enemy, En_objp->radius);
8006         } else {
8007                 aip->current_target_is_locked = 0;
8008                 aip->ai_flags &= ~AIF_SEEK_LOCK;
8009         }
8010
8011         //      If seeking lock, try to point directly at ship, else predict position so lasers can hit it.
8012         //      If just acquired target, or target is not in reasonable cone, don't refine believed enemy position.
8013         if ((real_dot_to_enemy < 0.25f) || (aip->target_time < 1.0f) || (aip->ai_flags & AIF_SEEK_LOCK)) {
8014                 predicted_enemy_pos = enemy_pos;
8015         } else {
8016                 //      Set predicted_enemy_pos.
8017                 //      See if attacking a subsystem.
8018                 if (aip->targeted_subsys != NULL) {
8019                         SDL_assert(En_objp->type == OBJ_SHIP);
8020                         ship_info       *esip = &Ship_info[Ships[En_objp->instance].ship_info_index];
8021                         if (get_shield_strength(En_objp)/esip->shields < HULL_DAMAGE_THRESHOLD_PERCENT) {
8022                                 //int   rval;
8023
8024                                 if (aip->targeted_subsys != NULL) {
8025                                         get_subsystem_pos(&enemy_pos, En_objp, aip->targeted_subsys);
8026                                         predicted_enemy_pos = enemy_pos;
8027                                         predicted_vec_to_enemy = real_vec_to_enemy;
8028                                 } else {
8029                                         set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, En_objp, aip);
8030                                         set_target_objnum(aip, -1);
8031                                 }
8032                                 // nprintf(("AI", "Attacking subsystem: rval = %i, pos = %7.3f %7.3f %7.3f\n", rval, predicted_enemy_pos.xyz.x, predicted_enemy_pos.xyz.y, predicted_enemy_pos.xyz.z));
8033
8034                         } else {
8035                                 set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, En_objp, aip);
8036                                 // nprintf(("AI", "Attacking subsystem: pos = %7.3f %7.3f %7.3f\n", predicted_enemy_pos.xyz.x, predicted_enemy_pos.xyz.y, predicted_enemy_pos.xyz.z));
8037                         }
8038                 } else {
8039                         set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, En_objp, aip);
8040                 }
8041         }
8042
8043         vm_vec_sub(&predicted_vec_to_enemy, &predicted_enemy_pos, &player_pos);
8044
8045         vm_vec_normalize(&predicted_vec_to_enemy);
8046
8047         dot_to_enemy = vm_vec_dot(&Pl_objp->orient.v.fvec, &predicted_vec_to_enemy);
8048         dot_from_enemy= - vm_vec_dot(&En_objp->orient.v.fvec, &real_vec_to_enemy);
8049
8050         //
8051         //      Set turn and acceleration based on submode.
8052         //
8053         switch (aip->submode) {
8054         case SM_CONTINUOUS_TURN:
8055                 ai_chase_ct();
8056                 break;
8057
8058         case SM_STEALTH_FIND:
8059                 ai_stealth_find();
8060                 break;
8061
8062         case SM_STEALTH_SWEEP:
8063                 ai_stealth_sweep();
8064                 break;
8065
8066         case SM_ATTACK:
8067         case SM_SUPER_ATTACK:
8068         case SM_ATTACK_FOREVER:
8069                 if (vm_vec_dist_quick(&Pl_objp->pos, &predicted_enemy_pos) > 100.0f + En_objp->radius * 2.0f) {
8070                         if (maybe_avoid_big_ship(Pl_objp, En_objp, aip, &predicted_enemy_pos, 10.0f))
8071                                 return;
8072                 }
8073
8074                 ai_chase_attack(aip, sip, &predicted_enemy_pos, dist_to_enemy);
8075                 break;
8076
8077         case SM_EVADE_SQUIGGLE:
8078                 ai_chase_es(aip, sip);
8079                 break;
8080
8081         case SM_EVADE_BRAKE:
8082                 ai_chase_eb(aip, sip, &predicted_enemy_pos, dist_to_enemy);
8083                 break;
8084
8085         case SM_EVADE:
8086                 evade_ship();
8087                 break;
8088
8089         case SM_AVOID:
8090                 avoid_ship();
8091                 break;
8092
8093         case SM_GET_BEHIND:
8094                 get_behind_ship(aip, sip, dist_to_enemy);
8095                 break;
8096
8097         case SM_GET_AWAY:               //      Used to get away from opponent to prevent endless circling.
8098                 ai_chase_ga(aip, sip);
8099                 break;
8100
8101         case SM_EVADE_WEAPON:
8102                 evade_weapon();
8103                 break;
8104
8105         default:
8106                 // Int3();
8107                 aip->last_attack_time = Missiontime;
8108                 aip->submode = SM_ATTACK;
8109                 aip->submode_start_time = Missiontime;
8110         }
8111
8112         //
8113         //      Maybe choose a new submode.
8114         //
8115         if ( (aip->submode != SM_AVOID) && (aip->submode != SM_ATTACK_FOREVER) ) {
8116                 //      If a very long time since attacked, attack no matter what!
8117                 if ( (aip->submode != SM_SUPER_ATTACK) && (aip->submode != SM_GET_AWAY) && !(aip->ai_flags & AIF_STEALTH_PURSIUT) ) {
8118                         if (Missiontime - aip->last_attack_time > i2f(6)) {
8119                                 aip->submode = SM_SUPER_ATTACK;
8120                                 aip->submode_start_time = Missiontime;
8121                                 aip->last_attack_time = Missiontime;
8122                         }
8123                 }
8124
8125                 //      If a collision is expected, pull out!
8126                 //      If enemy is pointing away and moving a bit, don't worry about collision detection.
8127                 if ((dot_from_enemy > 0.5f) || (En_objp->phys_info.speed < 10.0f)) {
8128                         if (might_collide_with_ship(Pl_objp, En_objp, dot_to_enemy, dist_to_enemy, 4.0f)) {
8129                                 if ((Missiontime - aip->last_hit_time > F1_0*4) && (dist_to_enemy < Pl_objp->radius*2 + En_objp->radius*2)) {
8130                                         accelerate_ship(aip, -1.0f);
8131                                 } else {
8132                                         aip->submode = SM_AVOID;
8133                                         aip->submode_start_time = Missiontime;
8134                                 }
8135                         }
8136                 }
8137         }
8138
8139         switch (aip->submode) {
8140         case SM_CONTINUOUS_TURN:
8141                 if (Missiontime - aip->submode_start_time > i2f(3)) {
8142                         aip->last_attack_time = Missiontime;
8143                         aip->submode = SM_ATTACK;
8144                         aip->submode_start_time = Missiontime;
8145                 }
8146                 break;
8147
8148         case SM_ATTACK:
8149                 // if taraget is stealth and stealth not visible, then enter stealth find mode
8150                 if ( (aip->ai_flags & AIF_STEALTH_PURSIUT) && (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_INVISIBLE) ) {
8151                         aip->submode = SM_STEALTH_FIND;
8152                         aip->submode_start_time = Missiontime;
8153                         aip->submode_parm0 = SM_SF_AHEAD;
8154                 } else if (ai_near_full_strength(Pl_objp, sip) && (Missiontime - aip->last_hit_target_time > i2f(3)) && (dist_to_enemy < 500.0f) && (dot_to_enemy < 0.5f)) {
8155                         aip->submode = SM_SUPER_ATTACK;
8156                         aip->submode_start_time = Missiontime;
8157                         aip->last_attack_time = Missiontime;
8158                 } else if ((Missiontime - aip->last_hit_target_time > i2f(6)) &&
8159                         (dist_to_enemy < 500.0f) && (dot_to_enemy < 0.2f) &&
8160                         (frand() < (float) Game_skill_level/NUM_SKILL_LEVELS)) {
8161                         aip->submode = SM_GET_AWAY;
8162                         aip->submode_start_time = Missiontime;
8163                         aip->last_hit_target_time = Missiontime;
8164                 } else if ((enemy_sip_flags & SIF_SMALL_SHIP)
8165                         && (dot_to_enemy < dot_from_enemy)
8166                         && (En_objp->phys_info.speed > 15.0f) 
8167                         && (dist_to_enemy < 200.0f) 
8168                         && (dist_to_enemy > 50.0f)
8169                         && (dot_to_enemy < 0.1f)
8170                         && (Missiontime - aip->submode_start_time > i2f(2))) {
8171                         aip->submode = SM_EVADE_BRAKE;
8172                         aip->submode_start_time = Missiontime;
8173                 } else if ((dot_to_enemy > 0.2f) && (dot_from_enemy > -0.2f) && (dot_from_enemy < 0.1f)) {
8174                         aip->submode = SM_GET_BEHIND;
8175                         aip->submode_start_time = Missiontime;
8176                 } else if ((enemy_sip_flags & SIF_SMALL_SHIP) && (dist_to_enemy < 150.0f) && (dot_from_enemy > dot_to_enemy + 0.5f + aip->ai_courage*.002)) {
8177                         if ((Missiontime - aip->last_hit_target_time > i2f(5)) && (frand() < (float) (aip->ai_class + Game_skill_level)/(Num_ai_classes + NUM_SKILL_LEVELS))) {                         aip->submode = SM_GET_AWAY;
8178                                 aip->submode_start_time = Missiontime;
8179                                 aip->last_hit_target_time = Missiontime;
8180                         } else {
8181                                 aip->submode = SM_EVADE_SQUIGGLE;
8182                                 aip->submode_start_time = Missiontime;
8183                         }
8184                 } else if ((enemy_sip_flags & SIF_SMALL_SHIP) && (Missiontime - aip->submode_start_time > F1_0*2)) {
8185                         if ((dot_to_enemy < 0.8f) && (dot_from_enemy > dot_to_enemy)) {
8186                                 if (frand() > 0.5f) {
8187                                         aip->submode = SM_CONTINUOUS_TURN;
8188                                         aip->submode_parm0 = myrand() & 0x0f;
8189                                         aip->submode_start_time = Missiontime;
8190                                 } else {
8191                                         aip->submode = SM_EVADE;
8192                                         aip->submode_start_time = Missiontime;
8193                                 }
8194                         } else {
8195                                 aip->submode_start_time = Missiontime;
8196                         }
8197                 }
8198
8199                 aip->last_attack_time = Missiontime;
8200
8201                 break;
8202                 
8203         case SM_EVADE_SQUIGGLE:
8204                 if ((Missiontime - aip->submode_start_time > i2f(5)) || (dist_to_enemy > 300.0f)) {
8205                         if ((dist_to_enemy < 100.0f) && (dot_to_enemy < 0.0f) && (dot_from_enemy > 0.5f)) {
8206                                 aip->submode = SM_EVADE_BRAKE;
8207                                 aip->submode_start_time = Missiontime;
8208                         } else {
8209                                 aip->last_attack_time = Missiontime;
8210                                 aip->submode = SM_ATTACK;
8211                                 aip->submode_start_time = Missiontime;
8212                         }
8213                 }
8214                 break;
8215         
8216         case SM_EVADE_BRAKE:
8217                 if ((dist_to_enemy < 15.0f) || (En_objp->phys_info.speed < 10.0f)) {
8218                         aip->submode = SM_AVOID;
8219                         aip->submode_start_time = Missiontime;
8220                 } else if ((dot_to_enemy > 0.9f) || ((dot_from_enemy > 0.9f) && (Missiontime - aip->submode_start_time > i2f(1)))) {
8221                         aip->last_attack_time = Missiontime;
8222                         aip->submode = SM_ATTACK;
8223                         aip->submode_start_time = Missiontime;
8224                 } else if (Missiontime - aip->submode_start_time > i2f(4)) {
8225                         aip->last_attack_time = Missiontime;
8226                         aip->submode = SM_ATTACK;
8227                         aip->submode_start_time = Missiontime;
8228                 }
8229                 break;
8230
8231         case SM_EVADE:
8232                 //      Modified by MK on 5/5/97 to keep trying to regain attack mode.  It's what a human would do.
8233                 if ((dot_to_enemy < 0.2f) && (dot_from_enemy < 0.8f) && (dist_to_enemy < 100.0f) && (En_objp->phys_info.speed > 15.0f)) {
8234                         aip->last_attack_time = Missiontime;
8235                         aip->submode = SM_EVADE_BRAKE;
8236                         aip->submode_start_time = Missiontime;
8237                 } else if (((dot_to_enemy > dot_from_enemy - 0.1f)
8238                         && (Missiontime > aip->submode_start_time + i2f(1)))
8239                         || (dist_to_enemy > 150.0f + 2*(Pl_objp->radius + En_objp->radius))) {
8240                         aip->last_attack_time = Missiontime;
8241                         aip->submode = SM_ATTACK;
8242                         aip->submode_start_time = Missiontime;
8243                 } else if (Missiontime - aip->submode_start_time > i2f(2))
8244                         if (dot_from_enemy > 0.8f) {
8245                                 aip->submode = SM_EVADE_SQUIGGLE;
8246                                 aip->submode_start_time = Missiontime;
8247                         }
8248
8249                 break;
8250
8251         case SM_SUPER_ATTACK:
8252                 // if stealth and invisible, enter stealth find mode
8253                 if ( (aip->ai_flags & AIF_STEALTH_PURSIUT) && (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_INVISIBLE) ) {
8254                         aip->submode = SM_STEALTH_FIND;
8255                         aip->submode_start_time = Missiontime;
8256                         aip->submode_parm0 = SM_SF_AHEAD;
8257                 } else if ((dist_to_enemy < 100.0f) && (dot_to_enemy < 0.8f) && (enemy_sip_flags & SIF_SMALL_SHIP) && (Missiontime - aip->submode_start_time > i2f(5) )) {
8258                         aip->ai_flags &= ~AIF_ATTACK_SLOWLY;    //      Just in case, clear here.
8259
8260                         switch (myrand() % 5) {
8261                         case 0:
8262                                 aip->submode = SM_CONTINUOUS_TURN;
8263                                 aip->submode_start_time = Missiontime;
8264                                 break;
8265                         case 1:
8266                                 aip->submode_start_time = Missiontime;  //      Stay in super attack mode
8267                                 break;
8268                         case 2:
8269                         case 3:
8270                                 if (frand() < (float) 0.5f * (aip->ai_class + Game_skill_level)/(Num_ai_classes + NUM_SKILL_LEVELS)) {
8271                                         aip->submode = SM_GET_AWAY;
8272                                         aip->submode_start_time = Missiontime;
8273                                 } else {
8274                                         aip->submode = SM_EVADE;
8275                                         aip->submode_start_time = Missiontime;
8276                                 }
8277                                 break;
8278                         case 4:
8279                                 if (dot_from_enemy + (NUM_SKILL_LEVELS - Game_skill_level) * 0.1f > dot_to_enemy) {     //      Less likely to GET_AWAY at lower skill levels.
8280                                         aip->submode = SM_EVADE;
8281                                         aip->submode_start_time = Missiontime;
8282                                 } else {
8283                                         aip->submode = SM_GET_AWAY;
8284                                         aip->submode_start_time = Missiontime;
8285                                 }
8286                                 break;
8287                         default:
8288                                 Int3(); //      Impossible!
8289                         }
8290                 }
8291
8292                 aip->last_attack_time = Missiontime;
8293
8294                 break;
8295
8296         case SM_AVOID:
8297                 if ((dot_to_enemy > -0.2f) && (dist_to_enemy / (dot_to_enemy + 0.3f) < 100.0f)) {
8298                         aip->submode_start_time = Missiontime;
8299                 } else if (Missiontime - aip->submode_start_time > i2f(1)/2) {
8300                         if (might_collide_with_ship(Pl_objp, En_objp, dot_to_enemy, dist_to_enemy, 3.0f)) {
8301                                 aip->submode_start_time = Missiontime;
8302                         } else {
8303                                 aip->submode = SM_GET_BEHIND;
8304                                 aip->submode_start_time = Missiontime;
8305                         }
8306                 }
8307
8308                 break;
8309
8310         case SM_GET_BEHIND:
8311                 if ((dot_from_enemy < -0.7f) || (Missiontime - aip->submode_start_time > i2f(2))) {
8312                         aip->submode = SM_ATTACK;
8313                         aip->submode_start_time = Missiontime;
8314                         aip->last_attack_time = Missiontime;
8315                 }
8316                 break;
8317
8318         case SM_GET_AWAY:
8319                 if (Missiontime - aip->submode_start_time > i2f(2)) {
8320                         float   rand_dist;
8321
8322                         rand_dist = ((Missiontime >> 17) & 0x03) * 100.0f + 200.0f;     //      Some value in 200..500
8323                         if ((Missiontime - aip->submode_start_time > i2f(5)) || (dist_to_enemy > rand_dist) || (dot_from_enemy < 0.4f)) {
8324                                 aip->ai_flags |= AIF_ATTACK_SLOWLY;
8325                                 aip->submode = SM_ATTACK;
8326                                 aip->time_enemy_in_range = 2.0f;                //      Cheat.  Presumably if they were running away from you, they were monitoring you!
8327                                 aip->submode_start_time = Missiontime;
8328                                 aip->last_attack_time = Missiontime;
8329                         }
8330                 }
8331                 break;
8332
8333         case SM_EVADE_WEAPON:
8334                 if (aip->danger_weapon_objnum == -1) {
8335                         aip->submode = SM_ATTACK;
8336                         aip->submode_start_time = Missiontime;
8337                         aip->last_attack_time = Missiontime;
8338                 }
8339                 break;
8340
8341         // Either change to SM_ATTACK or AIM_FIND_STEALTH
8342         case SM_STEALTH_FIND:
8343                 // if time > 5 sec change mode to sweep
8344                 if ( !(aip->ai_flags & AIF_STEALTH_PURSIUT) || (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_VISIBLE) ) {
8345                         aip->submode = SM_ATTACK;
8346                         aip->submode_start_time = Missiontime;
8347                         aip->last_attack_time = Missiontime;
8348                         // sweep if I can't find in 5 sec or bail from find
8349                 } else if ( ((Missiontime - aip->submode_start_time) > i2f(5)) || (aip->submode_parm0 == SM_SF_BAIL) ) {
8350                         // begin sweep mode
8351                         aip->submode = SM_STEALTH_SWEEP;
8352                         aip->submode_start_time = Missiontime;
8353                         aip->last_attack_time = Missiontime;
8354                         aip->submode_parm0 = SM_SS_SET_GOAL;
8355                 }
8356                 break;
8357
8358         case SM_STEALTH_SWEEP:
8359                 if ( !(aip->ai_flags & AIF_STEALTH_PURSIUT) || (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_VISIBLE) ) {
8360                         aip->submode = SM_ATTACK;
8361                         aip->submode_start_time = Missiontime;
8362                         aip->last_attack_time = Missiontime;
8363                 } else if ( (timestamp() - aip->stealth_last_visible_stamp) < 5000 ) {
8364                         // go back to find mode
8365                         aip->submode = SM_STEALTH_FIND;
8366                         aip->submode_start_time = Missiontime;
8367                         aip->submode_parm0 = SM_SF_AHEAD;
8368                 } else if ( /*(Missiontime - aip->submode_start_time) > i2f(30) || */ aip->submode_parm0 == SM_SS_DONE ) {
8369                         // set target objnum = -1
8370                         set_target_objnum(aip, -1);
8371
8372                         // set submode to attack
8373                         aip->submode = SM_ATTACK;
8374                         aip->submode_start_time = Missiontime;
8375                         aip->last_attack_time = Missiontime;
8376                 }
8377                 break;
8378
8379         case SM_ATTACK_FOREVER: //      Engines blown, just attack.
8380                 break;
8381
8382         default:
8383                 //Int3();
8384                 aip->submode = SM_ATTACK;
8385                 aip->last_attack_time = Missiontime;
8386
8387                 aip->submode_start_time = Missiontime;
8388         }
8389
8390         //
8391         //      Maybe fire primary weapon and update time_enemy_in_range
8392         //
8393         //nprintf(("AI", "time_enemy_in_range = %7.3f, dot = %7.3f\n", aip->time_enemy_in_range, dot_to_enemy));
8394
8395         if (aip->mode != AIM_EVADE) {
8396                 if (dot_to_enemy > 0.95f - 0.5f * En_objp->radius/SDL_max(1.0f, En_objp->radius + dist_to_enemy)) {
8397                         aip->time_enemy_in_range += flFrametime;
8398                         
8399                         //      Chance of hitting ship is based on dot product of firing ship's forward vector with vector to ship
8400                         //      and also the size of the target relative to distance to target.
8401                         if (dot_to_enemy > SDL_max(0.5f, 0.90f + aip->ai_accuracy/10.0f - En_objp->radius/SDL_max(1.0f,dist_to_enemy))) {
8402
8403                                 ship *temp_shipp;
8404                                 ship_weapon *tswp;
8405
8406                                 temp_shipp = &Ships[Pl_objp->instance];
8407                                 tswp = &temp_shipp->weapons;
8408                                 if ( tswp->num_primary_banks > 0 ) {
8409                                         float   scale;
8410                                         SDL_assert(tswp->current_primary_bank < tswp->num_primary_banks);
8411                                         weapon_info     *pwip = &Weapon_info[tswp->primary_bank_weapons[tswp->current_primary_bank]];
8412
8413                                         //      Less likely to fire if far away and moving.
8414                                         scale = pwip->max_speed/(En_objp->phys_info.speed + pwip->max_speed);
8415                                         if (scale > 0.6f)
8416                                                 scale = (scale - 0.6f) * 1.5f;
8417                                         else
8418                                                 scale = 0.0f;
8419                                         if (dist_to_enemy < pwip->max_speed * (1.0f + scale)) {
8420                                                 ai_fire_primary_weapon(Pl_objp);
8421                                         }
8422
8423                                         //      Don't fire secondaries at a protected ship.
8424                                         if (!(En_objp->flags & OF_PROTECTED)) {
8425                                                 ai_choose_secondary_weapon(Pl_objp, aip, En_objp);
8426                                                 int current_bank = tswp->current_secondary_bank;
8427
8428                                                 if (current_bank > -1) {
8429                                                         weapon_info     *swip = &Weapon_info[tswp->secondary_bank_weapons[current_bank]];
8430
8431                                                         if (aip->ai_flags & AIF_UNLOAD_SECONDARIES) {
8432                                                                 if (timestamp_until(swp->next_secondary_fire_stamp[current_bank]) > swip->fire_wait*1000.0f) {
8433                                                                         swp->next_secondary_fire_stamp[current_bank] = timestamp((int) (swip->fire_wait*1000.0f));
8434                                                                 }
8435                                                         }
8436
8437                                                         if (timestamp_elapsed(swp->next_secondary_fire_stamp[current_bank])) {
8438                                                                 float firing_range;
8439                                                                         
8440                                                                 if (swip->wi_flags & WIF_BOMB)
8441                                                                         firing_range = swip->max_speed * swip->lifetime * 0.75f;
8442                                                                 else
8443                                                                         firing_range = swip->max_speed * swip->lifetime * (Game_skill_level + 1 + aip->ai_class/2)/NUM_SKILL_LEVELS;
8444
8445                                                                 // reduce firing range in nebula
8446                                                                 extern int Nebula_sec_range;
8447                                                                 if ((The_mission.flags & MISSION_FLAG_FULLNEB) && Nebula_sec_range) {
8448                                                                         firing_range *= 0.8f;
8449                                                                 }
8450
8451                                                                 //      If firing a spawn weapon, distance doesn't matter.
8452                                                                 int     spawn_fire = 0;
8453
8454                                                                 if (swip->wi_flags & WIF_SPAWN) {
8455                                                                         int     count;
8456
8457                                                                         count = num_nearby_fighters(get_enemy_team_mask(OBJ_INDEX(Pl_objp)), &Pl_objp->pos, 1000.0f);
8458
8459                                                                         if (count > 3)
8460                                                                                 spawn_fire = 1;
8461                                                                         else if (count >= 1) {
8462                                                                                 float hull_percent = Pl_objp->hull_strength/sip->initial_hull_strength;
8463
8464                                                                                 if (hull_percent < 0.01f)
8465                                                                                         hull_percent = 0.01f;
8466
8467                                                                                 if (frand() < 0.25f/(30.0f*hull_percent) * count)       //      With timestamp below, this means could fire in 30 seconds if one enemy.
8468                                                                                         spawn_fire = 1;
8469                                                                         }
8470                                                                 }
8471
8472                                                                 if (spawn_fire || (dist_to_enemy < firing_range)) {
8473                                                                         if (ai_fire_secondary_weapon(Pl_objp)) {
8474                                                                                 //      Only if weapon was fired do we specify time until next fire.  If not fired, done in ai_fire_secondary...
8475                                                                                 float t;
8476                                                                                         
8477                                                                                 if (aip->ai_flags & AIF_UNLOAD_SECONDARIES) {
8478                                                                                         t = swip->fire_wait;
8479                                                                                 } else {
8480                                                                                         t = set_secondary_fire_delay(aip, temp_shipp, swip);
8481                                                                                 }
8482                                                                                 //nprintf(("AI", "Next secondary to be fired in %7.3f seconds.\n", t));
8483                                                                                 swp->next_secondary_fire_stamp[current_bank] = timestamp((int) (t*1000.0f));
8484                                                                         }
8485                                                                 } else {
8486                                                                         swp->next_secondary_fire_stamp[current_bank] = timestamp(250);
8487                                                                 }
8488                                                         }
8489                                                 }
8490                                         }
8491                                 }
8492                         }
8493                 } else {
8494                         aip->time_enemy_in_range *= (1.0f - flFrametime);
8495                 }
8496         } else
8497                 aip->time_enemy_in_range *= (1.0f - flFrametime);
8498
8499 }
8500
8501 //      Make the object *objp move so that the point *dp on the object moves towards the point *vp
8502 //      Return distance.
8503 void dock_move_towards_point(object *objp, vector *dp, vector *vp, float speed_scale, float other_obj_speed = 0.0f)
8504 {
8505         physics_info    *pi = &objp->phys_info;
8506         float                           dist;                   //      dist to goal
8507         vector                  v2g;                    //      vector to goal
8508         vector                  abs_pnt;                //      location of dock point, ie objp->pos + db
8509
8510         if (dp == NULL)
8511                 abs_pnt = objp->pos;
8512         else
8513                 vm_vec_add(&abs_pnt, &objp->pos, dp);
8514
8515         dist = vm_vec_dist_quick(vp, &abs_pnt);
8516         if (dist > 0.0f) {
8517                 float   speed;
8518
8519                 dist = vm_vec_normalized_dir(&v2g, vp, &abs_pnt);
8520                 speed = fl_sqrt(dist) * speed_scale;
8521                 if (other_obj_speed < MAX_REPAIR_SPEED*0.75f)
8522                         speed += other_obj_speed;
8523                 else
8524                         speed += MAX_REPAIR_SPEED*0.75f;
8525
8526                 vm_vec_copy_scale(&pi->desired_vel, &v2g, speed);
8527         } else
8528                 vm_vec_zero(&pi->desired_vel);
8529 }
8530
8531 //      Set the orientation in the global reference frame for an object to attain
8532 //      to dock with another object.
8533 //      *dom            resultant global matrix
8534 //      *db_dest        pointer to destination docking bay information
8535 //      *db_src pointer to source docking bay information
8536 //      *dorient        pointer to global orientation of docking bay (ie, the dockee object's orient)
8537 //      *sorient        pointer to global orientation of docker
8538 void set_goal_dock_orient(matrix *dom, dock_bay *db_dest, dock_bay *db_src, matrix *dorient, matrix *sorient)
8539 {
8540         vector  fvec, uvec;
8541         matrix  m1, m2, m3;
8542
8543         //      Compute the global orientation of the docker's (dest) docking bay.
8544         fvec = db_dest->norm[0];
8545         vm_vec_negate(&fvec);
8546
8547         vm_vec_normalized_dir(&uvec, &db_dest->pnt[1], &db_dest->pnt[0]);
8548         vm_vector_2_matrix(&m1, &fvec, &uvec, NULL);
8549
8550         vm_matrix_x_matrix(&m3, dorient, &m1);
8551
8552         //      Compute the matrix given by the source docking bay.
8553         //      Pre-multiply the orientation of the source object (sorient) by the transpose
8554         //      of the docking bay's orientation, ie unrotate the source object's matrix.
8555         fvec = db_src->norm[0];
8556         vm_vec_normalized_dir(&uvec, &db_src->pnt[1], &db_src->pnt[0]);
8557         vm_vector_2_matrix(&m2, &fvec, &uvec, NULL);
8558         vm_transpose(&m2);
8559
8560         vm_matrix_x_matrix(dom, &m3, &m2);
8561 }
8562
8563 #define DOCK_BACKUP_RETURN_VAL  99999.9f
8564
8565 //      Make objp dock with dobjp
8566 //      Returns distance to goal, defined as distance between corresponding dock points, plus 10.0f * rotational velocity vector (DOA_DOCK only)
8567 //      DOA_APPROACH    means   approach point aip->path_cur
8568 //      DOA_DOCK                        means dock
8569 //      DOA_UNDOCK_1    means undock, moving to point nearest dock bay
8570 //      DOA_UNDOCK_2    means undock, moving to point nearest dock bay and facing away from ship
8571 //      DOA_DOCK_STAY   means rigidly maintain position in dock bay.
8572 float dock_orient_and_approach(object *objp, object *dobjp, int dock_mode)
8573 {
8574         ship_info       *sip0, *sip1;
8575         polymodel       *pm0, *pm1;
8576         ai_info         *aip;
8577         matrix          dom, nm;
8578         vector          goal_point, docker_point;
8579         float                   fdist = UNINITIALIZED_VALUE;
8580         int                     docker_index, dockee_index;             // index into docking_bays[] array for objects docking
8581                                                                                                                                 // docker is Pl_objp -- dockee is dobjp
8582         aip = &Ai_info[Ships[objp->instance].ai_index];
8583
8584         //      If dockee has moved much, then path will be recreated.
8585         //      Might need to change state if moved too far.
8586         if ((dock_mode != DOA_DOCK_STAY) && (dock_mode != DOA_DOCK)) {
8587                 if (maybe_recreate_path(objp, &Ai_info[Ships[objp->instance].ai_index], 0) > 5.0f) {
8588 /*                      if (dock_mode == DOA_APPROACH) {
8589                                 return DOCK_BACKUP_RETURN_VAL;
8590                         } else if (dock_mode == DOA_DOCK) {
8591                                 return DOCK_BACKUP_RETURN_VAL;          
8592                         }
8593 */              }
8594         }
8595
8596         objp->phys_info.forward_thrust = 0.0f;          //      Kill thrust so we don't have a sputtering thruster.
8597
8598         sip0 = &Ship_info[Ships[objp->instance].ship_info_index];
8599         sip1 = &Ship_info[Ships[dobjp->instance].ship_info_index];
8600         pm0 = model_get( sip0->modelnum );
8601         pm1 = model_get( sip1->modelnum );
8602
8603         docker_index = aip->dock_index;
8604         dockee_index = aip->dockee_index;
8605
8606         SDL_assert( docker_index >= 0 );
8607         SDL_assert( dockee_index >= 0 );
8608
8609         SDL_assert(pm0->docking_bays[docker_index].num_slots == 2);
8610         SDL_assert(pm1->docking_bays[dockee_index].num_slots == 2);
8611
8612         float speed_scale = 1.0f;
8613         if (sip0->flags & SIF_SUPPORT) {
8614                 speed_scale = 3.0f;
8615         }
8616
8617         switch (dock_mode) {
8618         case DOA_APPROACH:
8619                 {
8620                 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8621                         return 9999.9f;
8622                 }
8623                 
8624                 //      Compute the desired global orientation matrix for the docker's station.
8625                 //      That is, the normal vector of the docking station must be the same as the
8626                 //      forward vector and the vector between its two points must be the uvec.
8627                 set_goal_dock_orient(&dom, &pm1->docking_bays[dockee_index], &pm0->docking_bays[docker_index], &dobjp->orient, &objp->orient);
8628
8629                 //      Compute new orientation matrix and update rotational velocity.
8630                 vector  w_in, w_out, vel_limit, acc_limit;
8631                 float           tdist, mdist, ss1;
8632
8633                 w_in = objp->phys_info.rotvel;
8634                 vel_limit = objp->phys_info.max_rotvel;
8635                 vm_vec_copy_scale(&acc_limit, &vel_limit, 0.3f);
8636                 
8637                 if (sip0->flags & SIF_SUPPORT)
8638                         vm_vec_scale(&acc_limit, 2.0f);
8639
8640                 // 1 at end of line prevent overshoot
8641                 vm_matrix_interpolate(&dom, &objp->orient, &w_in, flFrametime, &nm, &w_out, &vel_limit, &acc_limit, 1);
8642                 objp->phys_info.rotvel = w_out;
8643                 objp->orient = nm;
8644
8645                 //      Translate towards goal and note distance to goal.
8646                 goal_point = Path_points[aip->path_cur].pos;
8647                 mdist = ai_matrix_dist(&objp->orient, &dom);
8648                 tdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8649
8650                 //      If translation is badly lagging rotation, speed up translation.
8651                 if (mdist > 0.1f) {
8652                         ss1 = tdist/(10.0f * mdist);
8653                         if (ss1 > 2.0f)
8654                                 ss1 = 2.0f;
8655                 } else
8656                         ss1 = 2.0f;
8657
8658                 // nprintf(("AI", "speed scale = %7.3f\n", ss1));
8659                 speed_scale *= 1.0f + ss1;
8660
8661                 dock_move_towards_point(objp, NULL, &goal_point, speed_scale, dobjp->phys_info.speed);
8662
8663                 fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8664
8665                 //      Note, we're interested in distance from goal, so if we're still turning, bash that into return value.
8666                 // nprintf(("AI", "matrix dist = %7.3f, threshold = %7.3f\n", mdist, 2*flFrametime));
8667                 fdist += 2.0f * mdist;
8668
8669                 break;
8670         }
8671         case DOA_DOCK:
8672                 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8673                         return 9999.9f;
8674                 }
8675         case DOA_DOCK_STAY:
8676                 //      Compute the desired global orientation matrix for the docker's station.
8677                 //      That is, the normal vector of the docking station must be the same as the
8678                 //      forward vector and the vector between its two points must be the uvec.
8679                 set_goal_dock_orient(&dom, &pm1->docking_bays[dockee_index], &pm0->docking_bays[docker_index], &dobjp->orient, &objp->orient);
8680
8681                 //      Compute distance between dock bay points.
8682                 vector  db0, db1, db2, db3;
8683
8684                 vm_vec_unrotate(&db0, &pm0->docking_bays[docker_index].pnt[0], &objp->orient);
8685                 vm_vec_add2(&db0, &objp->pos);
8686
8687                 vm_vec_unrotate(&db1, &pm0->docking_bays[docker_index].pnt[1], &objp->orient);
8688                 vm_vec_add2(&db1, &objp->pos);
8689
8690                 vm_vec_unrotate(&db2, &pm1->docking_bays[dockee_index].pnt[0], &dobjp->orient);
8691                 vm_vec_add2(&db2, &dobjp->pos);
8692
8693                 vm_vec_unrotate(&db3, &pm1->docking_bays[dockee_index].pnt[1], &dobjp->orient);
8694                 vm_vec_add2(&db3, &dobjp->pos);
8695
8696                 vm_vec_avg(&goal_point, &db2, &db3);
8697
8698                 vm_vec_avg(&docker_point, &db0, &db1);
8699                 vm_vec_sub2(&docker_point, &objp->pos);
8700
8701                 if (dock_mode == DOA_DOCK) {
8702                         vector  t1, t2;
8703                         vector  w_in, w_out, vel_limit, acc_limit;
8704
8705                         fdist = vm_vec_dist_quick(vm_vec_avg(&t1, &db0, &db1), vm_vec_avg(&t2, &db2, &db3));
8706
8707                         //      Compute new orientation matrix and update rotational velocity.
8708                         w_in = objp->phys_info.rotvel;
8709                         vel_limit = objp->phys_info.max_rotvel;
8710                         vm_vec_copy_scale(&acc_limit, &vel_limit, 0.3f);
8711
8712                         if (sip0->flags & SIF_SUPPORT)
8713                                 vm_vec_scale(&acc_limit, 2.0f);
8714
8715                         vm_matrix_interpolate(&dom, &objp->orient, &w_in, flFrametime, &nm, &w_out, &vel_limit, &acc_limit);
8716                         objp->phys_info.rotvel = w_out;
8717                         objp->orient = nm;
8718
8719                         //      Note, we're interested in distance from goal, so if we're still turning, bash that into return value.
8720                         fdist += 10.0f * vm_vec_mag_quick(&w_out);
8721
8722                         dock_move_towards_point(objp, &docker_point, &goal_point, speed_scale, dobjp->phys_info.speed);
8723                 } else {
8724                         SDL_assert(dock_mode == DOA_DOCK_STAY);
8725                         objp->orient = dom;
8726                         vector  temp;
8727                         vm_vec_sub(&temp, &goal_point, &docker_point);
8728                         vm_vec_sub(&objp->pos, &goal_point, &docker_point);
8729                 }
8730
8731                 break;
8732         case DOA_UNDOCK_1: {
8733                 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8734                         return 9999.9f;
8735                 }
8736
8737                 //      Undocking.
8738                 //      Move to point on dock path nearest to dock station.
8739                 SDL_assert(aip->path_length >= 2);
8740                 goal_point = Path_points[aip->path_start + aip->path_length-2].pos;
8741
8742                 vm_vec_zero(&docker_point);
8743                 fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8744
8745                 dock_move_towards_point(objp, &docker_point, &goal_point, speed_scale);
8746
8747                 break;
8748                           }
8749
8750         case DOA_UNDOCK_2: {
8751                 //      Undocking.
8752                 //      Move to point on dock path nearest to dock station and orient away from big ship.
8753                 int             desired_index;
8754
8755                 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8756                         return 9999.9f;
8757                 }
8758
8759                 SDL_assert(aip->path_length >= 2);
8760 //              if (aip->path_length >= 3)
8761 //                      desired_index = aip->path_length-3;
8762 //              else
8763                         desired_index = aip->path_length-2;
8764
8765                 goal_point = Path_points[aip->path_start + desired_index].pos;
8766
8767                 dock_move_towards_point(objp, NULL, &goal_point, speed_scale);
8768
8769                 fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8770                 break;
8771                           }
8772         case DOA_UNDOCK_3: {
8773                 float           dist, goal_dist;
8774                 vector  away_vec;
8775
8776                 goal_dist = objp->radius + dobjp->radius + 25.0f;
8777
8778                 dist = vm_vec_normalized_dir(&away_vec, &objp->pos, &dobjp->pos);
8779                 vm_vec_scale_add(&goal_point, &dobjp->pos, &away_vec, goal_dist);
8780                 if (vm_vec_dist_quick(&goal_point, &dobjp->pos) < vm_vec_dist_quick(&objp->pos, &dobjp->pos))
8781                         fdist = 0.0f;
8782                 else {
8783                         float   dot, accel;
8784                         float turn_time = Ship_info[Ships[objp->instance].ship_info_index].srotation_time;
8785                         ai_turn_towards_vector(&goal_point, objp, flFrametime, turn_time, NULL, NULL, 0.0f, 0);
8786
8787                         dot = vm_vec_dot(&objp->orient.v.fvec, &away_vec);
8788                         accel = 0.1f;
8789                         if (dot > accel)
8790                                 accel = dot;
8791                         if (dist > goal_dist/2)
8792                                 accel *= 1.2f - 0.5f*goal_dist/dist;
8793
8794                         accelerate_ship(aip, accel);
8795                         fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8796                 }
8797
8798                 break;
8799                                                          }
8800         }
8801
8802 #ifndef NDEBUG
8803         //      For debug purposes, compute global orientation of both dock vectors and show
8804         //      how close they are.
8805         vector  d0, d1;
8806
8807         vm_vec_unrotate(&d0, &pm0->docking_bays[docker_index].norm[0], &objp->orient);
8808         vm_vec_unrotate(&d1, &pm1->docking_bays[dockee_index].norm[0], &dobjp->orient);
8809
8810         //nprintf(("AI", "or/app: dist = %7.3f/%7.3f, dot = %7.3f, global dot = %7.3f\n", 
8811         //      vm_vec_dist_quick(&goal_point, &objp->pos), fdist,
8812         //      vm_vec_dot(&objp->orient.v.fvec, &dom.v.fvec), 
8813         //      vm_vec_dot(&d0, &d1)));
8814 #endif
8815
8816         // -- Note, A lot of callers don't care about fdist, so OK to return ERROR value: SDL_assert(fdist != UNINITIALIZED_VALUE);
8817         return fdist;
8818
8819 }
8820
8821 void debug_find_guard_object()
8822 {
8823         ship                    *shipp = &Ships[Pl_objp->instance];     
8824         object          *objp;
8825
8826         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
8827                 if ((Pl_objp != objp) && (objp->type == OBJ_SHIP)) {
8828                         if (objp->instance != -1) {
8829                                 if (Ships[objp->instance].team == shipp->team)  {
8830                                         // nprintf(("AI", "Setting guard object for %s to %s\n", shipp->ship_name, Ships[objp->instance].ship_name));
8831                                         ai_set_guard_object(Pl_objp, objp);
8832                                 }
8833                         }
8834                 }
8835         }
8836
8837 }
8838
8839 //      Given an object number, return the number of ships attacking it.
8840 int num_ships_attacking(int objnum)
8841 {
8842         object  *objp;
8843         ship_obj        *so;
8844         int             count = 0;
8845
8846         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
8847                 objp = &Objects[so->objnum];
8848                 if (objp->instance != -1) {
8849                         ai_info *aip;
8850                         aip = &Ai_info[Ships[objp->instance].ai_index];
8851
8852                         if ((aip->mode == AIM_CHASE) && (aip->target_objnum == objnum))
8853                                 if (Ships[objp->instance].team != Ships[Objects[objnum].instance].team)
8854                                         count++;
8855                 }
8856         }
8857
8858         return count;
8859 }
8860
8861 //      For all objects attacking object #objnum, remove the one that is farthest away.
8862 //      Do this by resuming previous behavior, if any.  If not, set target_objnum to -1.
8863 void remove_farthest_attacker(int objnum)
8864 {
8865         object  *objp, *objp2, *farthest_objp;
8866         ship_obj        *so;
8867         float           farthest_dist;
8868
8869         objp2 = &Objects[objnum];
8870
8871         farthest_dist = 9999999.9f;
8872         farthest_objp = NULL;
8873
8874         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
8875                 objp = &Objects[so->objnum];
8876                 if ( !(objp->flags & OF_PLAYER_SHIP)) {
8877                         if (objp->instance != -1) {
8878                                 ai_info *aip2;
8879
8880                                 aip2 = &Ai_info[Ships[objp->instance].ai_index];
8881
8882                                 if ((aip2->mode == AIM_CHASE) && (aip2->target_objnum == objnum)) {
8883                                         if (Ships[objp->instance].team != Ships[Objects[objnum].instance].team) {
8884                                                 float   dist;
8885
8886                                                 dist = vm_vec_dist_quick(&objp->pos, &objp2->pos);
8887                                                 if (dist < farthest_dist) {
8888                                                         farthest_dist = dist;
8889                                                         farthest_objp = objp;
8890                                                 }
8891                                         }
8892                                 }
8893                         }
8894                 }
8895         }
8896
8897         if (farthest_objp != NULL) {
8898                 ai_info *aip;
8899                 SDL_assert(farthest_objp->type == OBJ_SHIP);
8900                 SDL_assert((farthest_objp->instance > -1) && (farthest_objp->instance < MAX_SHIPS));
8901                 SDL_assert(Ships[farthest_objp->instance].ai_index > -1);
8902
8903                 aip = &Ai_info[Ships[farthest_objp->instance].ai_index];
8904
8905                 if (!maybe_resume_previous_mode(Pl_objp, aip)) {
8906                         //      If already ignoring something under player's orders, don't ignore current target.
8907                         if ((aip->ignore_objnum == UNUSED_OBJNUM) || (aip->ai_flags & AIF_TEMPORARY_IGNORE)) {
8908                                 aip->ignore_objnum = aip->target_objnum;
8909                                 aip->ignore_signature = Objects[aip->target_objnum].signature;
8910                                 aip->ai_flags |= AIF_TEMPORARY_IGNORE;
8911                                 aip->ignore_expire_timestamp = timestamp(((myrand() % 10) + 20) * 1000);        //      OK to attack again in 20 to 24 seconds.
8912                         }
8913                         aip->target_objnum = -1;
8914                         ai_do_default_behavior(farthest_objp);
8915                 }
8916         }
8917 }
8918
8919 // Maybe limit the number of attackers on attack_objnum.  For now, only limit attackers
8920 // in attacked_objnum is the player
8921 // input:       attacked_objnum =>              object index for ship we want to limit attacks on
8922 //
8923 //      exit:                   1       =>      num attackers exceeds maximum, abort
8924 //                                      0       =>      removed the farthest attacker
8925 //                                      -1      =>      nothing was done
8926 int ai_maybe_limit_attackers(int attacked_objnum)
8927 {
8928         int rval=-1;
8929
8930         // limit the number of ships attacking the _player_ only
8931 //      if ( attacked_objnum == OBJ_INDEX(Player_obj) ) {
8932         if ( Objects[attacked_objnum].flags & OF_PLAYER_SHIP) {
8933                 int num_attacking;
8934                 num_attacking = num_ships_attacking(attacked_objnum);
8935
8936                 if (num_attacking == Skill_level_max_attackers[Game_skill_level]) {
8937                         remove_farthest_attacker(attacked_objnum);
8938                         rval=0;
8939                 } else if (num_attacking > Skill_level_max_attackers[Game_skill_level]) {
8940                         rval=1;
8941                 }
8942                 //nprintf(("AI", "Num attacking player = %i\n", num_attacking));
8943         }
8944
8945         return rval;
8946 }
8947
8948 //      Object being guarded by object *guard_objp was hit by object *hitter_objp
8949 void guard_object_was_hit(object *guard_objp, object *hitter_objp)
8950 {
8951         int             hitter_objnum;
8952         ai_info *aip;
8953
8954         aip = &Ai_info[Ships[guard_objp->instance].ai_index];
8955
8956         if (guard_objp == hitter_objp) {
8957                 // Int3();      //      Bogus!  Who tried to get me to attack myself!  Trace out and fix!
8958                 return;
8959         }
8960
8961         if (guard_objp->type == OBJ_GHOST || hitter_objp->type == OBJ_GHOST)
8962                 return;
8963
8964         if (aip->ai_flags & AIF_NO_DYNAMIC)     //      Not allowed to pursue dynamic goals.  So, why are we guarding?
8965                 return;
8966
8967         SDL_assert( (hitter_objp->type == OBJ_SHIP) || (hitter_objp->type == OBJ_ASTEROID) || (hitter_objp->type == OBJ_WEAPON) );
8968
8969         hitter_objnum = OBJ_INDEX(hitter_objp);
8970
8971         if ( hitter_objp->type == OBJ_SHIP ) {
8972                 //      If the hitter object is the ignore object, don't attack it.
8973                 if (is_ignore_object(aip, hitter_objp-Objects))
8974                         return;
8975
8976                 //      If hitter is on same team as me, don't attack him.
8977                 if (Ships[guard_objp->instance].team == Ships[hitter_objp->instance].team)
8978                         return;
8979
8980                 // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
8981                 if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
8982                         return;
8983                 }
8984
8985                 // dont attack if you can't see him
8986                 if ( awacs_get_level(hitter_objp, &Ships[aip->shipnum], 1) < 1 ) {
8987                         // if he's a stealth and visible, but not targetable, ok to attack.
8988                         if ( is_object_stealth_ship(hitter_objp) ) {
8989                                 if ( ai_is_stealth_visible(guard_objp, hitter_objp) != STEALTH_VISIBLE ) {
8990                                         return;
8991                                 }
8992                         }
8993                 }
8994         }
8995
8996         if (aip->target_objnum == -1) {
8997                 aip->ok_to_target_timestamp = timestamp(0);
8998         }
8999
9000         if ((aip->submode == AIS_GUARD_PATROL) || (aip->submode == AIS_GUARD_STATIC)) {
9001
9002                 if ( hitter_objp->type == OBJ_SHIP ) {
9003                         if (!(Ship_info[Ships[guard_objp->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
9004                                 return;
9005                         }
9006
9007                         // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
9008                         if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
9009                                 return;
9010                         }
9011                 }
9012
9013                 if (aip->target_objnum != hitter_objnum) {
9014                         aip->aspect_locked_time = 0.0f;
9015                 }
9016
9017                 aip->ok_to_target_timestamp = timestamp(0);
9018
9019                 set_target_objnum(aip, hitter_objnum);
9020                 //if (aip->target_objnum == -1) nprintf(("AI", "Frame %i: Attacking NONE\n",Framecount)); else nprintf(("AI", "Frame %i: Attacking %s\n", Framecount, Ships[Objects[aip->target_objnum].instance].ship_name));
9021                 aip->previous_mode = AIM_GUARD;
9022                 aip->previous_submode = aip->submode;
9023                 aip->mode = AIM_CHASE;
9024                 aip->submode = SM_ATTACK;
9025                 aip->submode_start_time = Missiontime;
9026                 aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
9027         } else if (aip->previous_mode == AIM_GUARD) {
9028                 if (aip->target_objnum == -1) {
9029
9030                         if ( hitter_objp->type == OBJ_SHIP ) {
9031                                 // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
9032                                 if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
9033                                         return;
9034                                 }
9035                         }
9036
9037                         set_target_objnum(aip, hitter_objnum);
9038                 //if (aip->target_objnum == -1) nprintf(("AI", "Frame %i: Attacking NONE\n",Framecount)); else nprintf(("AI", "Frame %i: Attacking %s\n", Framecount, Ships[Objects[aip->target_objnum].instance].ship_name));
9039                         aip->mode = AIM_CHASE;
9040                         aip->submode = SM_ATTACK;
9041                         aip->submode_start_time = Missiontime;
9042                         aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
9043                 } else {
9044                         int     num_attacking_cur, num_attacking_new;
9045
9046                         num_attacking_cur = num_ships_attacking(aip->target_objnum);
9047                         if (num_attacking_cur > 1) {
9048                                 num_attacking_new = num_ships_attacking(hitter_objnum);
9049
9050                                 if (num_attacking_new < num_attacking_cur) {
9051
9052                                         if ( hitter_objp->type == OBJ_SHIP ) {
9053                                                 // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
9054                                                 if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
9055                                                         return;
9056                                                 }
9057                                         }
9058                                         set_target_objnum(aip, hitter_objp-Objects);
9059                 //if (aip->target_objnum == -1) nprintf(("AI", "Frame %i: Attacking NONE\n",Framecount)); else nprintf(("AI", "Frame %i: Attacking %s\n", Framecount, Ships[Objects[aip->target_objnum].instance].ship_name));
9060                                         aip->mode = AIM_CHASE;
9061                                         aip->submode = SM_ATTACK;
9062                                         aip->submode_start_time = Missiontime;
9063                                         aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
9064                                 }
9065                         }
9066                 }
9067         }
9068 }
9069
9070 //      Ship object *hit_objp was hit by ship object *hitter_objp.
9071 //      See if anyone is guarding hit_objp and, if so, do something useful.
9072 void maybe_update_guard_object(object *hit_objp, object *hitter_objp)
9073 {
9074         object  *objp;
9075         ship_obj        *so;
9076
9077         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
9078                 objp = &Objects[so->objnum];
9079                 if (objp->instance != -1) {
9080                         ai_info *aip;
9081                         aip = &Ai_info[Ships[objp->instance].ai_index];
9082
9083                         if ((aip->mode == AIM_GUARD) || (aip->active_goal == AI_ACTIVE_GOAL_DYNAMIC)) {
9084                                 if (aip->guard_objnum == hit_objp-Objects) {
9085                                         guard_object_was_hit(objp, hitter_objp);
9086                                 } else if ((aip->guard_wingnum != -1) && (aip->guard_wingnum == Ai_info[Ships[hit_objp->instance].ai_index].wing)) {
9087                                         guard_object_was_hit(objp, hitter_objp);
9088                                 }
9089                         }
9090                 }
9091         }
9092 }
9093
9094 // Scan missile list looking for bombs homing on guarded_objp
9095 // return 1 if bomb is found (and targeted by guarding_objp), otherwise return 0
9096 int ai_guard_find_nearby_bomb(object *guarding_objp, object *guarded_objp)
9097 {       
9098         missile_obj     *mo;
9099         object          *bomb_objp, *closest_bomb_objp=NULL;
9100         float                   dist, dist_to_guarding_obj,closest_dist_to_guarding_obj=999999.0f;
9101         weapon          *wp;
9102         weapon_info     *wip;
9103
9104         for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
9105                 SDL_assert(mo->objnum >= 0 && mo->objnum < MAX_OBJECTS);
9106                 bomb_objp = &Objects[mo->objnum];
9107
9108                 wp = &Weapons[bomb_objp->instance];
9109                 wip = &Weapon_info[wp->weapon_info_index];
9110
9111                 if ( !(wip->wi_flags & WIF_BOMB) ) {
9112                         continue;
9113                 }
9114
9115                 if ( wp->homing_object != guarded_objp ) {
9116                         continue;
9117                 }
9118
9119                 dist = vm_vec_dist_quick(&bomb_objp->pos, &guarded_objp->pos);
9120
9121                 if (dist < (MAX_GUARD_DIST + guarded_objp->radius)*3) {
9122                         dist_to_guarding_obj = vm_vec_dist_quick(&bomb_objp->pos, &guarding_objp->pos);
9123                         if ( dist_to_guarding_obj < closest_dist_to_guarding_obj ) {
9124                                 closest_dist_to_guarding_obj = dist_to_guarding_obj;
9125                                 closest_bomb_objp = bomb_objp;
9126                         }
9127                 }
9128         }
9129
9130         if ( closest_bomb_objp ) {
9131                 guard_object_was_hit(guarding_objp, closest_bomb_objp);
9132                 return 1;
9133         }
9134
9135         return 0;
9136 }
9137
9138 //      Scan enemy ships and see if one is near enough to guard object to be pursued.
9139 void ai_guard_find_nearby_ship(object *guarding_objp, object *guarded_objp)
9140 {
9141         ship            *guarding_shipp = &Ships[guarding_objp->instance];
9142         ai_info *guarding_aip = &Ai_info[guarding_shipp->ai_index];
9143         ship_obj        *so;
9144         object  *enemy_objp;
9145         float           dist;
9146
9147         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
9148                 enemy_objp = &Objects[so->objnum];
9149
9150                 if (enemy_objp->instance < 0) {
9151                         continue;
9152                 }
9153
9154                 ship    *eshipp = &Ships[enemy_objp->instance];
9155
9156                 //      Don't attack a cargo container or other harmless ships
9157                 if (!(Ship_info[eshipp->ship_info_index].flags & SIF_HARMLESS)) {
9158                         if (guarding_shipp->team != eshipp->team)       {
9159                                 dist = vm_vec_dist_quick(&enemy_objp->pos, &guarded_objp->pos);
9160                                 if (dist < (MAX_GUARD_DIST + guarded_objp->radius)*3) {
9161                                         guard_object_was_hit(guarding_objp, enemy_objp);
9162                                 } else if ((dist < 3000.0f) && (Ai_info[eshipp->ai_index].target_objnum == guarding_aip->guard_objnum)) {
9163                                         //nprintf(("AI", "%i: Enemy %s targeting guard object (%s), %s will attack!!\n", Framecount, eshipp->ship_name, Ships[Objects[guarding_aip->guard_objnum].instance].ship_name, guarding_shipp->ship_name));
9164                                         guard_object_was_hit(guarding_objp, enemy_objp);
9165                                 }
9166                         }
9167                 }
9168         }
9169 }
9170
9171 // Scan for nearby asteroids.  Favor asteroids which have their collide_objnum set to that of the
9172 // guarded ship.  Also, favor asteroids that are closer to the guarding ship, since it looks cooler
9173 // when a ship blows up an asteroid then goes after the pieces that break off.
9174 void ai_guard_find_nearby_asteroid(object *guarding_objp, object *guarded_objp)
9175 {       
9176         float           dist;
9177
9178         object  *closest_asteroid_objp=NULL, *danger_asteroid_objp=NULL, *asteroid_objp;
9179         float           dist_to_self, closest_danger_asteroid_dist=999999.0f, closest_asteroid_dist=999999.0f;
9180
9181         for ( asteroid_objp = GET_FIRST(&obj_used_list); asteroid_objp != END_OF_LIST(&obj_used_list); asteroid_objp = GET_NEXT(asteroid_objp) ) {
9182                 if ( asteroid_objp->type == OBJ_ASTEROID ) {
9183                         // Attack asteroid if near guarded ship
9184                         dist = vm_vec_dist_quick(&asteroid_objp->pos, &guarded_objp->pos);
9185                         if ( dist < (MAX_GUARD_DIST + guarded_objp->radius)*2) {
9186                                 dist_to_self = vm_vec_dist_quick(&asteroid_objp->pos, &guarding_objp->pos);
9187                                 if ( OBJ_INDEX(guarded_objp) == asteroid_collide_objnum(asteroid_objp) ) {
9188                                         if( dist_to_self < closest_danger_asteroid_dist ) {
9189                                                 danger_asteroid_objp=asteroid_objp;
9190                                                 closest_danger_asteroid_dist=dist_to_self;
9191                                         }
9192                                 } 
9193                                 if ( dist_to_self < closest_asteroid_dist ) {
9194                                         // only attack if moving slower than own max speed
9195                                         if ( vm_vec_mag_quick(&asteroid_objp->phys_info.vel) < guarding_objp->phys_info.max_vel.xyz.z ) {
9196                                                 closest_asteroid_dist = dist_to_self;
9197                                                 closest_asteroid_objp = asteroid_objp;
9198                                         }
9199                                 }
9200                         }
9201                 }
9202         }
9203
9204         if ( danger_asteroid_objp ) {
9205                 guard_object_was_hit(guarding_objp, danger_asteroid_objp);
9206         } else if ( closest_asteroid_objp ) {
9207                 guard_object_was_hit(guarding_objp, closest_asteroid_objp);
9208         }
9209 }
9210
9211 //      Scan potential harmful objects and see if one is near enough to guard object to be pursued.
9212 void ai_guard_find_nearby_object()
9213 {
9214         ship                    *shipp = &Ships[Pl_objp->instance];
9215         ai_info         *aip = &Ai_info[shipp->ai_index];
9216         object          *guardobjp;
9217         int                     bomb_found=0;
9218
9219         guardobjp = &Objects[aip->guard_objnum];
9220         
9221         // highest priority is a bomb fired on guarded ship
9222         bomb_found = ai_guard_find_nearby_bomb(Pl_objp, guardobjp);
9223
9224         if ( !bomb_found ) {
9225                 // check for ships if there are no bombs fired at guarded ship
9226                 ai_guard_find_nearby_ship(Pl_objp, guardobjp);
9227
9228                 // if not attacking anything, go for asteroid close to guarded ship
9229                 if ( (aip->target_objnum == -1) && asteroid_count() ) {
9230                         ai_guard_find_nearby_asteroid(Pl_objp, guardobjp);
9231                 }
9232         }
9233 }
9234
9235 // gets closest point on extended axis of cylinder, r_vec, and radius of cylinder
9236 // returns z of axis_point in cyl_objp reference frame
9237 float get_cylinder_points(object *other_objp, object *cyl_objp, vector *axis_pt, vector *r_vec, float *radius)
9238 {
9239         SDL_assert(other_objp->type == OBJ_SHIP);
9240         SDL_assert(cyl_objp->type == OBJ_SHIP);
9241
9242         // get radius of cylinder
9243         polymodel *pm = model_get(Ships[cyl_objp->instance].modelnum);
9244         float tempx, tempy;
9245         tempx = SDL_max(-pm->mins.xyz.x, pm->maxs.xyz.x);
9246         tempy = SDL_max(-pm->mins.xyz.y, pm->maxs.xyz.y);
9247         *radius = SDL_max(tempx, tempy);
9248
9249         // get vec from cylinder to other_obj
9250         vector r_sph;
9251         vm_vec_sub(&r_sph, &other_objp->pos, &cyl_objp->pos);
9252
9253         // get point on axis and on cylinder
9254         // extended_cylinder_z is along extended cylinder
9255         // cylinder_z is capped within cylinder
9256         float extended_cylinder_z = vm_vec_dotprod(&r_sph, &cyl_objp->orient.v.fvec);
9257
9258         // get pt on axis of extended cylinder
9259         vm_vec_scale_add(axis_pt, &cyl_objp->pos, &cyl_objp->orient.v.fvec, extended_cylinder_z);
9260
9261         // get r_vec (pos - axis_pt) normalized
9262         vm_vec_normalized_dir(r_vec, &other_objp->pos, axis_pt);
9263
9264         return extended_cylinder_z;
9265 }
9266
9267 // handler for guard behavior when guarding BIG ships
9268 //      When someone has attacked guarded ship, then attack that ship.
9269 // To attack another ship, switch out of guard mode into chase mode.
9270 void ai_big_guard()
9271 {
9272         
9273         ship                    *shipp = &Ships[Pl_objp->instance];
9274         ai_info         *aip = &Ai_info[shipp->ai_index];
9275         object          *guard_objp;
9276
9277         // sanity checks already done in ai_guard()
9278         guard_objp = &Objects[aip->guard_objnum];
9279
9280         switch (aip->submode) {
9281         case AIS_GUARD_STATIC:
9282         case AIS_GUARD_PATROL:
9283                 {
9284                 vector axis_pt, r_vec, theta_vec;
9285                 float radius, extended_z;
9286
9287                 // get random [0 to 1] based on OBJNUM
9288                 float objval = static_randf(Pl_objp-Objects);
9289
9290                 // get position relative to cylinder of guard_objp              
9291                 extended_z = get_cylinder_points(Pl_objp, guard_objp, &axis_pt, &r_vec, &radius);
9292                 vm_vec_crossprod(&theta_vec, &guard_objp->orient.v.fvec, &r_vec);
9293
9294                 // half ships circle each way
9295                 if (objval > 0.5f) {
9296                         vm_vec_negate(&theta_vec);
9297                 }
9298
9299                 float min_guard_dist = radius + Pl_objp->radius + 50.0f;
9300                 float desired_guard_dist = min_guard_dist + 0.5f * ((1.0f + objval) * MAX_GUARD_DIST);
9301                 float max_guard_dist =     min_guard_dist + 1.0f * ((1.0f + objval) * MAX_GUARD_DIST);
9302
9303                 // get z extents
9304                 float min_z, max_z, length;
9305                 polymodel *pm = model_get(Ships[guard_objp->instance].modelnum);
9306                 min_z = pm->mins.xyz.z;
9307                 max_z = pm->maxs.xyz.z;
9308                 length = max_z - min_z;
9309
9310                 // get desired z
9311                 // how often to choose new desired_z
9312                 // 1*(64) sec < 2000, 2*(64) < 2-4000 3*(64) > 4-8000, etc (Missiontime >> 22 is 64 sec intervals)
9313                 int time_choose = int(floor(log(length * 0.001) / log(2.0)));
9314                 float desired_z = min_z + length * static_randf( (Pl_objp-Objects) ^ (Missiontime >> (22 + time_choose)) );
9315
9316                 // get r from guard_ship
9317                 float cur_guard_rad = vm_vec_dist(&Pl_objp->pos, &axis_pt);
9318
9319                 // is ship within extents of cylinder of ship it is guarding
9320                 int inside = (extended_z > min_z) && (extended_z < min_z + length);
9321
9322                 vector goal_pt;
9323                 // maybe go into orbit mode
9324                 if (cur_guard_rad < max_guard_dist) {
9325                         if ( cur_guard_rad > min_guard_dist ) {
9326                                 if (inside) {
9327                                         // orbit
9328                                         vm_vec_scale_add(&goal_pt, &axis_pt, &r_vec, desired_guard_dist);
9329                                         vm_vec_scale_add2(&goal_pt, &theta_vec, desired_guard_dist);
9330                                 } else {
9331                                         // move to where I can orbit
9332                                         if (extended_z < min_z) {
9333                                                 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, min_z);
9334                                         } else {
9335                                                 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, max_z);
9336                                         }
9337                                         vm_vec_scale_add2(&goal_pt, &r_vec, desired_guard_dist);
9338                                         vm_vec_scale_add2(&goal_pt, &theta_vec, desired_guard_dist);
9339                                 }
9340                         } else {
9341                                 // too close for orbit mode
9342                                 if (inside) {
9343                                         // inside (fly straight out and return circle)
9344                                         vm_vec_scale_add(&goal_pt, &axis_pt, &r_vec, max_guard_dist);
9345                                 } else {
9346                                         // outside (fly to edge and circle)
9347                                         if (extended_z < min_z) {
9348                                                 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, min_z);
9349                                         } else {
9350                                                 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, max_z);
9351                                         }
9352                                         vm_vec_scale_add2(&goal_pt, &r_vec, max_guard_dist);
9353                                         vm_vec_scale_add2(&goal_pt, &theta_vec, desired_guard_dist);
9354                                 }
9355                         }
9356
9357                         if (Pl_objp->phys_info.fspeed > 0) {
9358                                 // modify goal_pt to take account moving guard objp
9359                                 float dist = vm_vec_dist_quick(&Pl_objp->pos, &goal_pt);
9360                                 float time = dist / Pl_objp->phys_info.fspeed;
9361                                 vm_vec_scale_add2(&goal_pt, &guard_objp->phys_info.vel, time);
9362
9363                                 // now modify to move to desired z (at a max of 20 m/s)
9364                                 float delta_z = desired_z - extended_z;
9365                                 float v_z = delta_z * 0.2f;
9366                                 if (v_z < -20) {
9367                                         v_z = -20.0f;
9368                                 } else if (v_z > 20) {
9369                                         v_z = 20.0f;
9370                                 }
9371
9372                                 vm_vec_scale_add2(&goal_pt, &guard_objp->orient.v.fvec, v_z*time);
9373                         }
9374
9375                 } else {
9376                         // cast vector to center of guard_ship adjusted by desired_z
9377                         float delta_z = desired_z - extended_z;
9378                         vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, delta_z);
9379                 }
9380
9381                 // try not to bump into things along the way
9382                 if ( (cur_guard_rad > max_guard_dist) || (extended_z < min_z) || (extended_z > max_z) ) {
9383                         if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_pt, 5.0f)) {
9384                                 return;
9385                         }
9386
9387                         if (avoid_player(Pl_objp, &goal_pt)) {
9388                                 return;
9389                         }
9390                 } else {
9391                         if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_pt, 5.0f)) {
9392                                 return;
9393                         }
9394                 }
9395
9396                 // got the point, now let's go there
9397                 ai_turn_towards_vector(&goal_pt, Pl_objp, flFrametime, Ship_info[Ships[Pl_objp->instance].ship_info_index].srotation_time, NULL, NULL, 0.0f, 0);
9398 //              aip->goal_point = goal_pt;
9399                 accelerate_ship(aip, 1.0f);
9400
9401                 //      Periodically, scan for a nearby ship to attack.
9402                 if (((AI_FrameCount ^ (Pl_objp-Objects)) & 0x07) == 0) {
9403                         ai_guard_find_nearby_object();
9404                 }
9405                 }
9406                 break;
9407
9408         case AIS_GUARD_ATTACK:
9409                 //      The guarded ship has been attacked.  Do something useful!
9410                 ai_chase();
9411                 break;
9412
9413         default:
9414                 //Int3();       //      Illegal submode for Guard mode.
9415                 // AL 06/03/97 comment out Int3() to allow milestone to get out the door
9416                 aip->submode = AIS_GUARD_PATROL;
9417                 break;
9418         }
9419 }
9420
9421 //      Main handler for guard behavior.
9422 //      When someone has attacked guarded ship, then attack that ship.
9423 // To attack another ship, switch out of guard mode into chase mode.
9424 void ai_guard()
9425 {
9426         ship                    *shipp = &Ships[Pl_objp->instance];
9427         ai_info         *aip = &Ai_info[shipp->ai_index];
9428         object          *guard_objp;    
9429         float                   dist_to_guardobj;
9430         vector          vec_to_guardobj;
9431
9432         /*      //      Debug code, find an object to guard.
9433         int finding_guard_objnum = 0;   //      Debug code, to see if body of "if" below gets executed. 
9434         if (aip->guard_objnum == -1) {
9435                 finding_guard_objnum = 1;
9436                 debug_find_guard_object();
9437                 if (aip->guard_objnum == -1)
9438                         return;
9439         }
9440 */
9441         if (aip->guard_objnum == -1) {
9442                 aip->mode = AIM_NONE;
9443                 return;
9444         }
9445
9446         SDL_assert(aip->guard_objnum != -1);
9447
9448         guard_objp = &Objects[aip->guard_objnum];
9449
9450         if (guard_objp == Pl_objp) {
9451                 Int3();         //      This seems illegal.  Why is a ship guarding itself?
9452                 aip->guard_objnum = -1;
9453                 return;
9454         }
9455
9456         // check that I have someone to guard
9457         if (guard_objp->instance == -1) {
9458                 return;
9459         }
9460
9461         //      Not sure whether this should be impossible, or a reasonable cleanup condition.
9462         //      For now (3/31/97), it's getting trapped by an SDL_assert, so clean it up.
9463         if (guard_objp->type != OBJ_SHIP) {
9464                 aip->guard_objnum = -1;
9465                 return;
9466         }
9467
9468         // handler for gurad object with BIG radius
9469         if (guard_objp->radius > BIG_GUARD_RADIUS) {
9470                 ai_big_guard();
9471                 return;
9472         }
9473
9474         float                   objval;
9475         vector          goal_point;
9476         vector          rel_vec;
9477         float                   dist_to_goal_point, dot_to_goal_point, accel_scale;
9478         vector          v2g, rvec;
9479
9480         // get random [0 to 1] based on OBJNUM
9481         objval = static_randf(Pl_objp-Objects);
9482
9483         switch (aip->submode) {
9484         case AIS_GUARD_STATIC:
9485         case AIS_GUARD_PATROL:
9486                 //      Stay near ship
9487                 dist_to_guardobj = vm_vec_normalized_dir(&vec_to_guardobj, &guard_objp->pos, &Pl_objp->pos);
9488
9489                 rel_vec = aip->guard_vec;
9490                 vm_vec_add(&goal_point, &guard_objp->pos, &rel_vec);
9491
9492                 vm_vec_normalized_dir(&v2g, &goal_point, &Pl_objp->pos);
9493                 dist_to_goal_point = vm_vec_dist_quick(&goal_point, &Pl_objp->pos);
9494                 dot_to_goal_point = vm_vec_dot(&v2g, &Pl_objp->orient.v.fvec);
9495                 accel_scale = (1.0f + dot_to_goal_point)/2.0f;
9496
9497                 //      If far away, get closer
9498                 if (dist_to_goal_point > MAX_GUARD_DIST + 1.5 * (Pl_objp->radius + guard_objp->radius)) {
9499                         if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_point, 5.0f)) {
9500                                 return;
9501                         }
9502
9503                         if (avoid_player(Pl_objp, &goal_point)) {
9504                                 return;
9505                         }
9506
9507                         // quite far away, so try to go straight to 
9508                         compute_desired_rvec(&rvec, &goal_point, &Pl_objp->pos);
9509                         ai_turn_towards_vector(&goal_point, Pl_objp, flFrametime, Ship_info[shipp->ship_info_index].srotation_time, NULL, NULL, 0.0f, 0, &rvec);
9510
9511                         accelerate_ship(aip, accel_scale * (0.25f + dist_to_goal_point/700.0f));
9512                 } else {
9513                         if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_point, 2.0f)) {
9514                                 return;
9515                         }
9516
9517                         // get max of guard_objp (1) normal speed (2) dock speed
9518                         float speed = guard_objp->phys_info.speed;
9519
9520                         if (guard_objp->type == OBJ_SHIP) {
9521                                 ai_info *guard_aip = &Ai_info[Ships[guard_objp->instance].ai_index];
9522
9523                                 if (guard_aip->dock_objnum != -1) {
9524                                         speed = SDL_max(speed, Objects[guard_aip->dock_objnum].phys_info.speed);
9525                                 }
9526                         }
9527                         
9528                         //      Deal with guarding a small object.
9529                         //      If going to guard_vec might cause a collision with guarded object, pick a new guard point.
9530                         if (vm_vec_dot(&v2g, &vec_to_guardobj) > 0.8f) {
9531                                 if (dist_to_guardobj < dist_to_goal_point) {
9532                                         ai_set_guard_vec(Pl_objp, guard_objp);  //      OK to return here.
9533                                         return;
9534                                 }
9535                         } 
9536
9537                         if (speed > 10.0f) {
9538                                 //      If goal ship is moving more than a tiny bit, don't orbit it, get near it.
9539                                 if (vm_vec_dist_quick(&goal_point, &Pl_objp->pos) > 40.0f) {
9540                                         if (vm_vec_dot(&Pl_objp->orient.v.fvec, &v2g) < 0.0f) {
9541                                                 //      Just slow down, don't turn.
9542                                                 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed - dist_to_goal_point/10.0f);
9543                                         } else {
9544                                                 //      Goal point is in front.
9545
9546                                                 //      If close to goal point, don't change direction, just change speed.
9547                                                 if (dist_to_goal_point > Pl_objp->radius + 10.0f) {
9548                                                         turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
9549                                                 }
9550                                                 
9551                                                 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed + (dist_to_goal_point-40.0f)/20.0f);
9552                                         }
9553                                 } else {
9554                                         if (dot_to_goal_point > 0.8f) {
9555                                                 turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
9556                                                 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed + dist_to_goal_point*0.1f);
9557                                         } else {
9558                                                 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed - dist_to_goal_point*0.1f - 1.0f);
9559                                         }
9560                                 }
9561                         // consider guard object STILL
9562                         } else if (guard_objp->radius < 50.0f) {
9563                                 if (dist_to_goal_point > 15.0f) {
9564                                         turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
9565                                         set_accel_for_target_speed(Pl_objp, (dist_to_goal_point-10.0f)/2.0f);
9566                                 } else if (Pl_objp->phys_info.speed < 1.0f) {
9567                                         turn_away_from_point(Pl_objp, &guard_objp->pos, 0.0f);
9568                                 }
9569                                 //      It's a big ship
9570                         } else if (dist_to_guardobj > MAX_GUARD_DIST + Pl_objp->radius + guard_objp->radius) {
9571                                 //      Orbiting ship, too far away
9572                                 float dot = turn_towards_tangent(Pl_objp, &guard_objp->pos, (1.0f + objval/2) * guard_objp->radius);
9573                                 accelerate_ship(aip, (1.0f + dot)/2.0f);
9574                         } else if (dist_to_guardobj < Pl_objp->radius + guard_objp->radius) {
9575                                 //      Orbiting ship, got too close
9576                                 turn_away_from_point(Pl_objp, &guard_objp->pos, 0.0f);
9577                                 if ((dist_to_guardobj > guard_objp->radius + Pl_objp->radius + 50.0f) && (guard_objp->phys_info.speed > Pl_objp->phys_info.speed - 1.0f))
9578                                         change_acceleration(aip, 0.25f);
9579                                 else
9580                                         accelerate_ship(aip, 0.5f + objval/4.0f);
9581                         } else {
9582                                 //      Orbiting ship, about the right distance away.
9583                                 float dot = turn_towards_tangent(Pl_objp, &guard_objp->pos, (1.5f + objval/2.0f)*guard_objp->radius);
9584                                 if ((dist_to_guardobj > guard_objp->radius + Pl_objp->radius + 50.0f) && (guard_objp->phys_info.speed > Pl_objp->phys_info.speed - 1.0f))
9585                                         set_accel_for_target_speed(Pl_objp, (0.5f * (1.0f + dot)) * (guard_objp->phys_info.speed + (dist_to_guardobj - guard_objp->radius - Pl_objp->radius)/10.0f));
9586                                 else
9587                                         accelerate_ship(aip, 0.5f * (1.0f + dot) * (0.3f + objval/3.0f));
9588                         }
9589                 }
9590
9591                 //      Periodically, scan for a nearby ship to attack.
9592                 if (((AI_FrameCount ^ (Pl_objp-Objects)) & 0x07) == 0) {
9593                         ai_guard_find_nearby_object();
9594                 }
9595                 break;
9596
9597         case AIS_GUARD_ATTACK:
9598                 //      The guarded ship has been attacked.  Do something useful!
9599                 ai_chase();
9600
9601                 break;
9602         default:
9603                 //Int3();       //      Illegal submode for Guard mode.
9604                 // AL 06/03/97 comment out Int3() to allow milestone to get out the door
9605                 aip->submode = AIS_GUARD_PATROL;
9606                 break;
9607         }
9608
9609 }
9610
9611 // Return the object of the ship that the given object is docked
9612 // with.  Currently, we know a ship is docked when his ai_mode is AIM_DOCK,
9613 // and his submode is AIS_DOCK_3.  I suppose that this is likely to change though.
9614 // Also, the objnum that was is passed in may not be the object that actually
9615 // performed the docking maneuver.  This code will account for that case.
9616 object *ai_find_docked_object( object *docker )
9617 {
9618         ai_info *aip;
9619
9620         // we are trying to find the dockee of docker.  (Note that that these terms
9621         // are totally relative to what is passed in as a parameter.)
9622
9623         // first thing to attempt is to check and see if this object is docked with something.
9624         SDL_assert( docker->type == OBJ_SHIP );         // this had probably better be a ship!!!
9625         aip = &Ai_info[Ships[docker->instance].ai_index];
9626         if ( !(aip->ai_flags & AIF_DOCKED) )            // flag not set if not docked with anything
9627                 return NULL;
9628
9629         if ( aip->dock_objnum == -1 ) {
9630                 Int3();                                                                                 // mwa says this is wrong wrong wrong
9631                 ai_do_objects_undocked_stuff( docker, NULL );
9632                 return NULL;
9633         }
9634
9635         return &Objects[aip->dock_objnum];
9636
9637 }
9638
9639
9640 // define for the points subtracted from score for a rearm started on a player.
9641 #define REPAIR_PENALTY          50
9642
9643
9644 // function to clean up ai flags, variables, and other interesting information
9645 // for a ship that was getting repaired.  The how parameter is useful for multiplayer
9646 // only in that it tells us why the repaired ship is being cleaned up.
9647 void ai_do_objects_repairing_stuff( object *repaired_objp, object *repair_objp, int how )
9648 {
9649         ai_info *aip, *repair_aip;
9650         int             stamp = -1;
9651
9652         SDL_assert( repaired_objp->type == OBJ_SHIP);
9653         aip = &Ai_info[Ships[repaired_objp->instance].ai_index];
9654
9655         // multiplayer
9656         int p_index;
9657         p_index = -1;
9658         if(Game_mode & GM_MULTIPLAYER){
9659                 p_index = multi_find_player_by_object(repaired_objp);           
9660         }               
9661         else {          
9662                 if(repaired_objp == Player_obj){
9663                         p_index = Player_num;
9664                 }
9665         }
9666
9667         switch( how ) {
9668         case REPAIR_INFO_BEGIN:
9669                 aip->ai_flags |= AIF_BEING_REPAIRED;
9670                 aip->ai_flags &= ~AIF_AWAITING_REPAIR;
9671                 stamp = timestamp(-1);
9672
9673                 // if this is a player ship, then subtract the repair penalty from this player's score
9674                 if ( repaired_objp->flags & OF_PLAYER_SHIP ) {
9675                         if ( !(Game_mode & GM_MULTIPLAYER) ) {
9676                                 Player->stats.m_score -= (int)(REPAIR_PENALTY * scoring_get_scale_factor());                    // subtract the penalty
9677                         } else {
9678                                 /*
9679                                 int pnum;
9680
9681                                 // multiplayer game -- find the player, then subtract the score
9682                                 pnum = multi_find_player_by_object( repaired_objp );
9683                                 if ( pnum != -1 ) {
9684                                         Net_players[pnum].player->stats.m_score -= (int)(REPAIR_PENALTY * scoring_get_scale_factor());
9685
9686                                         // squad war
9687                                         multi_team_maybe_add_score(-(int)(REPAIR_PENALTY * scoring_get_scale_factor()), Net_players[pnum].p_info.team);
9688                                 } else {
9689                                         nprintf(("Network", "Couldn't find player for ship %s for repair penalty\n", Ships[repaired_objp->instance].ship_name));
9690                                 }
9691                                 */
9692                         }
9693                 }
9694                 break;
9695
9696         case REPAIR_INFO_BROKEN:
9697                 aip->ai_flags &= ~AIF_BEING_REPAIRED;
9698                 aip->ai_flags |= AIF_AWAITING_REPAIR;
9699                 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9700                 break;
9701
9702         case REPAIR_INFO_END:
9703                 // when only awaiting repair, and the repair is ended, then set dock_objnum to -1.
9704                 if ( aip->ai_flags & AIF_AWAITING_REPAIR ){
9705                         aip->dock_objnum = -1;
9706                 }
9707                 aip->ai_flags &= ~(AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED );
9708                 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9709                 break;
9710
9711         case REPAIR_INFO_QUEUE:
9712                 aip->ai_flags |= AIF_AWAITING_REPAIR;
9713                 if ( aip == Player_ai ){
9714                         hud_support_view_start();
9715                 }
9716                 stamp = timestamp(-1);
9717                 break;
9718
9719         case REPAIR_INFO_ABORT:
9720         case REPAIR_INFO_KILLED:
9721                 // 5/4/98 -- MWA -- Need to set dock objnum to -1 to let code know this guy who was getting
9722                 // repaired (or queued for repair), isn't really going to be docked with anyone anymore.
9723                 aip->dock_objnum = -1;
9724                 aip->ai_flags &= ~AIF_DOCKED;
9725                 aip->ai_flags &= ~(AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED );
9726                 if (repair_objp != NULL) {
9727                         repair_aip = &Ai_info[Ships[repair_objp->instance].ai_index];
9728                         repair_aip->ai_flags &= ~(AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED );
9729                 }               
9730
9731                 if ( p_index >= 0 ) {
9732                         hud_support_view_abort();
9733
9734                         // send appropriate message to player here
9735                         if ( how == REPAIR_INFO_KILLED ){
9736                                 message_send_builtin_to_player( MESSAGE_SUPPORT_KILLED, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_SOON, 0, 0, p_index, -1 );
9737                         } else {
9738                                 if ( repair_objp ){
9739                                         message_send_builtin_to_player( MESSAGE_REPAIR_ABORTED, &Ships[repair_objp->instance], MESSAGE_PRIORITY_NORMAL, MESSAGE_TIME_SOON, 0, 0, p_index, -1 );
9740                                 }
9741                         }
9742                 }
9743
9744                 // add log entry if this is a player
9745                 if ( repaired_objp->flags & OF_PLAYER_SHIP ){
9746                         mission_log_add_entry(LOG_PLAYER_REARM_ABORT, Ships[repaired_objp->instance].ship_name, NULL);
9747                 }
9748
9749                 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9750                 break;
9751
9752         case REPAIR_INFO_COMPLETE:
9753                 // clear the being repaired flag -- and 
9754                 if ( p_index >= 0 ) {
9755                         SDL_assert( repair_objp );
9756                         
9757                         hud_support_view_stop();                        
9758
9759                         message_send_builtin_to_player(MESSAGE_REPAIR_DONE, &Ships[repair_objp->instance], MESSAGE_PRIORITY_LOW, MESSAGE_TIME_SOON, 0, 0, p_index, -1);
9760                 }
9761                 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9762                 break;
9763
9764         case REPAIR_INFO_ONWAY:
9765                 // need to set the dock_signature so that clients in multiplayer games rearm correctly
9766                 SDL_assert( repair_objp );
9767                 aip->dock_signature = repair_objp->signature; 
9768                 aip->dock_objnum = OBJ_INDEX(repair_objp);
9769                 stamp = timestamp(-1);
9770                 break;
9771
9772         default:
9773                 Int3();                 // bogus type of repair info
9774         }
9775
9776         if (repair_objp){
9777                 Ai_info[Ships[repair_objp->instance].ai_index].warp_out_timestamp = stamp;
9778         }
9779
9780         // repair_objp might be NULL is we are cleaning up this mode because of the support ship
9781         // getting killed.
9782         if ( repair_objp ) {
9783                 aip = &Ai_info[Ships[repair_objp->instance].ai_index];
9784                 switch ( how ) {
9785                 case REPAIR_INFO_ONWAY:
9786                         SDL_assert( repaired_objp != NULL );
9787                         aip->goal_objnum = OBJ_INDEX(repaired_objp);
9788                         aip->ai_flags |= AIF_REPAIRING;
9789                         break;
9790
9791                 case REPAIR_INFO_BROKEN:
9792                         break;
9793
9794                 case REPAIR_INFO_END:
9795                 case REPAIR_INFO_ABORT:
9796                 case REPAIR_INFO_KILLED:
9797                         if ( how == REPAIR_INFO_ABORT )
9798                                 aip->goal_objnum = -1;
9799
9800                         aip->ai_flags &= ~AIF_REPAIRING;
9801                         break;
9802                         
9803                 case REPAIR_INFO_QUEUE:
9804                         ai_add_rearm_goal( repaired_objp, repair_objp );
9805                         break;
9806
9807                 case REPAIR_INFO_BEGIN:
9808                 case REPAIR_INFO_COMPLETE:
9809                         break;
9810
9811                 default:
9812                         Int3();         // bogus type of repair info
9813                 }
9814         }
9815
9816         multi_maybe_send_repair_info( repaired_objp, repair_objp, how );
9817 }
9818
9819 //      Cleanup AI stuff for when a ship was supposed to dock with another, but the ship
9820 //      it was supposed to dock with is no longer valid.
9821 void ai_cleanup_dock_mode(ai_info *aip, ship *shipp)
9822 {
9823         object *objp;
9824
9825         objp = &Objects[shipp->objnum];
9826         aip->mode = AIM_NONE;
9827
9828         if (aip->ai_flags & AIF_REPAIRING) {
9829                 SDL_assert( aip->goal_objnum != -1 );
9830                 ai_do_objects_repairing_stuff( &Objects[aip->goal_objnum], &Objects[shipp->objnum], REPAIR_INFO_KILLED );
9831         } else if ( aip->ai_flags & AIF_BEING_REPAIRED ) {
9832                 // MWA -- note that we have to use dock_objnum here instead of goal_objnum.
9833                 SDL_assert( aip->dock_objnum != -1 );
9834                 ai_do_objects_repairing_stuff( &Objects[shipp->objnum], &Objects[aip->dock_objnum], REPAIR_INFO_KILLED );
9835         } else if ( aip->ai_flags & AIF_AWAITING_REPAIR ) {
9836                 // need to find the support ship that has me as a goal_objnum
9837                 // MWA -- note that we have to use dock_objnum here instead of goal_objnum.
9838                 // MWA -- 3/38/98  Check to see if this guy is queued for a support ship, or there is already
9839                 // one in the mission
9840                 if ( mission_is_repair_scheduled(objp) ) {
9841                         mission_remove_scheduled_repair( objp );                        // this function will notify multiplayer clients.
9842                 } else {
9843                         if ( aip->dock_objnum != -1 )
9844                                 ai_do_objects_repairing_stuff( objp, &Objects[aip->dock_objnum], REPAIR_INFO_ABORT );
9845                         else
9846                                 ai_do_objects_repairing_stuff( objp, NULL, REPAIR_INFO_ABORT );
9847                 }
9848         }
9849
9850         if ( aip->ai_flags & AIF_DOCKED ) {
9851                 ai_info *other_aip;
9852
9853                 SDL_assert( aip->dock_objnum != -1 );
9854
9855                 // if docked, and the dock_objnum is not undocking, force them to near last stage
9856                 other_aip = &Ai_info[Ships[Objects[aip->dock_objnum].instance].ai_index];
9857                 if ( (other_aip->mode == AIM_DOCK) && (other_aip->submode < AIS_UNDOCK_3) )
9858                         other_aip->submode = AIS_UNDOCK_3;
9859                 ai_do_objects_undocked_stuff( objp, &Objects[aip->dock_objnum] );
9860         }
9861 }
9862
9863 /*
9864 //      Make dockee_objp shake a bit due to docking.
9865 void ai_dock_shake(object *docker_objp, object *dockee_objp)
9866 {
9867         vector  tangles;
9868         matrix  rotmat, tmp;
9869         float           scale;
9870         angles  *ap;
9871
9872         scale = 0.25f;          //      Compute this based on mass and speed at time of docking.
9873
9874         vm_vec_rand_vec_quick(&tangles);
9875         vm_vec_scale(&tangles, scale);
9876
9877         ap = (angles *) &tangles;
9878
9879         vm_angles_2_matrix(&rotmat, ap);
9880         vm_matrix_x_matrix( &tmp, &dockee_objp->orient, &rotmat );
9881         dockee_objp->orient = tmp;
9882
9883         vm_orthogonalize_matrix(&dockee_objp->orient);
9884
9885         dock_orient_and_approach(docker_objp, dockee_objp, DOA_DOCK_STAY);
9886
9887 }
9888 */
9889
9890 //      Make Pl_objp point at aip->goal_point.
9891 void ai_still()
9892 {
9893         ship    *shipp;
9894         ai_info *aip;
9895
9896         SDL_assert(Pl_objp->type == OBJ_SHIP);
9897         SDL_assert((Pl_objp->instance >= 0) && (Pl_objp->instance < MAX_OBJECTS));
9898
9899         shipp = &Ships[Pl_objp->instance];
9900         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
9901
9902         aip = &Ai_info[shipp->ai_index];
9903
9904         turn_towards_point(Pl_objp, &aip->goal_point, NULL, 0.0f);
9905 }
9906
9907 //      Make *Pl_objp stay near another ship.
9908 void ai_stay_near()
9909 {
9910         ai_info *aip;
9911         int             goal_objnum;
9912
9913         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
9914
9915         goal_objnum = aip->goal_objnum;
9916
9917         if ((goal_objnum < 0) || (Objects[goal_objnum].type != OBJ_SHIP) || (Objects[goal_objnum].signature != aip->goal_signature)) {
9918                 aip->mode = AIM_NONE;
9919         } else {
9920                 float           dist, max_dist, scale;
9921                 vector  rand_vec, goal_pos, vec_to_goal;
9922                 object  *goal_objp;
9923
9924                 goal_objp = &Objects[goal_objnum];
9925
9926                 //      Make not all ships pursue same point.
9927                 static_randvec(Pl_objp-Objects, &rand_vec);
9928
9929                 //      Make sure point is in front hemisphere (relative to Pl_objp's position.
9930                 vm_vec_sub(&vec_to_goal, &goal_objp->pos, &Pl_objp->pos);
9931                 if (vm_vec_dot(&rand_vec, &vec_to_goal) > 1.0f) {
9932                         vm_vec_negate(&rand_vec);
9933                 }
9934
9935                 //      Scale the random vector by an amount proportional to the distance from Pl_objp to the true goal.
9936                 dist = vm_vec_dist_quick(&goal_objp->pos, &Pl_objp->pos);
9937                 max_dist = aip->stay_near_distance;
9938                 scale = dist - max_dist/2;
9939                 if (scale < 0.0f)
9940                         scale = 0.0f;
9941
9942                 vm_vec_scale_add(&goal_pos, &goal_objp->pos, &rand_vec, scale);
9943
9944                 if (max_dist < Pl_objp->radius + goal_objp->radius + 25.0f)
9945                         max_dist = Pl_objp->radius + goal_objp->radius + 25.0f;
9946
9947                 if (dist > max_dist) {
9948                         turn_towards_point(Pl_objp, &goal_pos, NULL, 0.0f);
9949                         accelerate_ship(aip, dist / max_dist - 0.8f);
9950                 }
9951         
9952         }
9953
9954 }
9955
9956 //      Warn player if dock path is obstructed.
9957 int maybe_dock_obstructed(object *cur_objp, object *goal_objp, int big_only_flag)
9958 {
9959         vector  *goalpos, *curpos;
9960         float           radius;
9961         ai_info *aip;
9962         int             collide_objnum;
9963
9964         aip = &Ai_info[Ships[cur_objp->instance].ai_index];
9965
9966         Ai_info[Ships[goal_objp->instance].ai_index].ai_flags &= ~AIF_REPAIR_OBSTRUCTED;
9967
9968         if (goal_objp != Player_obj)
9969                 return -1;
9970
9971         curpos = &cur_objp->pos;
9972         radius = cur_objp->radius;
9973         goalpos = &Path_points[aip->path_cur].pos;
9974         collide_objnum = pp_collide_any(curpos, goalpos, radius, cur_objp, goal_objp, big_only_flag);
9975
9976         if (collide_objnum != -1)
9977                 Ai_info[Ships[goal_objp->instance].ai_index].ai_flags |= AIF_REPAIR_OBSTRUCTED;
9978
9979         return collide_objnum;
9980 }
9981
9982
9983 int Dock_path_warning_given = 0;
9984
9985 //      Docking behavior.
9986 //      Approach a ship, follow path to docking platform, approach platform, after awhile,
9987 //      undock.
9988 void ai_dock()
9989 {
9990         ship                    *shipp = &Ships[Pl_objp->instance];
9991         ai_info         *aip = &Ai_info[shipp->ai_index];
9992         object          *goal_objp;
9993         ship_info       *sip = &Ship_info[shipp->ship_info_index];
9994
9995         //      Make sure object we're supposed to dock with still exists.
9996         if ((aip->goal_objnum == -1) || (Objects[aip->goal_objnum].signature != aip->goal_signature)) {
9997                 ai_cleanup_dock_mode(aip, shipp);
9998                 return;
9999         }
10000
10001         goal_objp = &Objects[aip->goal_objnum];
10002
10003         //      For docking submodes (ie, not undocking), follow path.  Once at second last
10004         //      point on path (point just before point on dock platform), orient into position.
10005         // For undocking, first mode pushes docked ship straight back from docking point
10006         // second mode turns ship and moves to point on docking radius
10007         switch (aip->submode) {
10008
10009                 //      This mode means to find the path to the docking point.
10010         case AIS_DOCK_0:
10011                 //aip->path_start = -1;
10012                 //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10013                 ai_path();
10014                 if (!Dock_path_warning_given && (aip->path_length < 4)) {
10015                         Warning( LOCATION, "Ship '%s' has only %i points on dock path.  Docking will look strange.  Contact Adam.", shipp->ship_name, aip->path_length );
10016                         Dock_path_warning_given = 1;            //      This is on a mission-wide basis, but it's just a hack for now...
10017                 }
10018
10019                 aip->submode = AIS_DOCK_1;
10020                 aip->path_start = -1;
10021                 aip->submode_start_time = Missiontime;
10022                 break;
10023
10024                 //      This mode means to follow the path until just before the end.
10025         case AIS_DOCK_1: {
10026         //      float   dist;
10027                 int     r;
10028
10029                 if ((r = maybe_dock_obstructed(Pl_objp, goal_objp, 1)) != -1) {
10030                         int     r1;
10031                         if ((r1 = maybe_avoid_big_ship(Pl_objp, goal_objp, aip, &goal_objp->pos, 7.0f)) != 0) {
10032                                 nprintf(("AI", "Support ship %s avoiding large ship %s\n", Ships[Pl_objp->instance].ship_name, Ships[Objects[r1].instance].ship_name));
10033                                 break;
10034                         } /*else {
10035                                 nprintf(("AI", "Dock 1: Obstructed by %s\n", Ships[Objects[r].instance].ship_name));
10036                                 accelerate_ship(aip, 0.0f);
10037                                 aip->submode = AIS_DOCK_0;
10038                         } */
10039                 } //else {
10040                 {
10041                         /*dist =*/ ai_path();
10042                         //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10043                         //nprintf(("AI", "Dock 1: Frame: %i, goal point = %i, dist = %7.3f\n", Framecount, aip->path_cur-aip->path_start, dist));
10044
10045                         if (aip->path_cur-aip->path_start >= aip->path_length-1) {              //      If got this far, advance no matter what.
10046                                 aip->submode = AIS_DOCK_2;
10047                                 aip->submode_start_time = Missiontime;
10048                                 aip->path_cur--;
10049                                 SDL_assert(aip->path_cur-aip->path_start >= 0);
10050                         } else if (aip->path_cur-aip->path_start >= aip->path_length-2) {
10051                                 if (Pl_objp->phys_info.speed > goal_objp->phys_info.speed + 1.5f) {
10052                                         set_accel_for_target_speed(Pl_objp, goal_objp->phys_info.speed);
10053                                 } else {
10054                                         aip->submode = AIS_DOCK_2;
10055                                         aip->submode_start_time = Missiontime;
10056                                 }
10057                         }
10058                 }
10059                 break;
10060                                           }
10061         //      This mode means to drag oneself right to the second last point on the path.
10062         //      Path code allows it to overshoot.
10063         case AIS_DOCK_2: {
10064                 float           dist;
10065                 int     r;
10066
10067                 if ((r = maybe_dock_obstructed(Pl_objp, goal_objp,0)) != -1) {
10068                         nprintf(("AI", "Dock 2: Obstructed by %s\n", Ships[Objects[r].instance].ship_name));
10069                         accelerate_ship(aip, 0.0f);
10070                         aip->submode = AIS_DOCK_1;
10071                 } else {
10072                         //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10073                         dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_APPROACH);
10074                         SDL_assert(dist != UNINITIALIZED_VALUE);
10075
10076                         if (dist == DOCK_BACKUP_RETURN_VAL) {
10077                                 int path_num;
10078                                 aip->submode = AIS_DOCK_1;
10079                                 path_num = ai_return_path_num_from_dockbay(&Objects[aip->goal_objnum], aip->dockee_index);
10080                                 SDL_assert(aip->goal_objnum >= 0 && aip->goal_objnum < MAX_OBJECTS);
10081                                 ai_find_path(Pl_objp, aip->goal_objnum, path_num, 0);
10082                                 break;
10083                         }
10084
10085                         //nprintf(("AI", "Dock 2: dist = %7.3f\n", vm_vec_dist_quick(&Pl_objp->pos, &goal_point)));
10086                         float   tolerance;
10087                         if (Objects[aip->goal_objnum].flags & OF_PLAYER_SHIP)
10088                                 tolerance = 6*flFrametime + 1.0f;
10089                         else
10090                                 tolerance = 4*flFrametime + 0.5f;
10091
10092                         if ( dist < tolerance) {
10093                                 aip->submode = AIS_DOCK_3;
10094                                 aip->submode_start_time = Missiontime;
10095                                 aip->path_cur++;
10096                         }
10097                 }
10098                 break;
10099                                                   }
10100
10101         case AIS_DOCK_3:
10102         case AIS_DOCK_3A:
10103                 {
10104                 SDL_assert(aip->goal_objnum != -1);
10105                 int     r;
10106
10107                 if ((r = maybe_dock_obstructed(Pl_objp, goal_objp,0)) != -1) {
10108                         nprintf(("AI", "Dock 1: Obstructed by %s\n", Ships[Objects[r].instance].ship_name));
10109                         accelerate_ship(aip, 0.0f);
10110                         aip->submode = AIS_DOCK_2;
10111                 } else {
10112
10113                         //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10114                         float dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_DOCK);
10115                         SDL_assert(dist != UNINITIALIZED_VALUE);
10116
10117                         if (dist == DOCK_BACKUP_RETURN_VAL) {
10118                                 aip->submode = AIS_DOCK_2;
10119                                 break;
10120                         }
10121
10122                         //nprintf(("AI", "Dock 3: dist = %7.3f\n", dist));
10123
10124                         if (dist < 2*flFrametime * (1.0f + fl_sqrt(goal_objp->phys_info.speed))) {
10125                                 // - Removed by MK on 11/7/97, causes errors for ships docked at mission start: maybe_recreate_path(Pl_objp, aip, 1);
10126                                 dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_DOCK);
10127                                 SDL_assert(dist != UNINITIALIZED_VALUE);
10128
10129                                 physics_ship_init(Pl_objp);
10130
10131                                 ai_do_objects_docked_stuff( Pl_objp, goal_objp );
10132
10133                                 if (aip->submode == AIS_DOCK_3) {
10134                                         snd_play_3d( &Snds[SND_DOCK_ATTACH], &Pl_objp->pos, &View_position );
10135                                         hud_maybe_flash_docking_text(Pl_objp);
10136                                         // ai_dock_shake(Pl_objp, goal_objp);
10137
10138                                         if ((Pl_objp == Player_obj) || (goal_objp == Player_obj))
10139                                                 joy_ff_docked();  // shake player's joystick a little
10140                                 }
10141
10142                                 //      If this ship is repairing another ship...
10143                                 if (aip->ai_flags & AIF_REPAIRING) {
10144                                         aip->submode = AIS_DOCK_4;                      //      Special rearming only dock mode.
10145                                         aip->submode_start_time = Missiontime;
10146                                 } else {
10147                                         aip->submode = AIS_DOCK_4A;
10148                                         aip->submode_start_time = Missiontime;
10149                                 }
10150                         }
10151                 }
10152                 break;
10153                 }
10154
10155                 //      Yes, we just sit here.  We wait for further orders.  No, it's not a bug.
10156         case AIS_DOCK_4A:
10157                 //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10158                 //nprintf(("AI", "."));
10159                 if (aip->active_goal >= 0) {
10160                         mission_log_add_entry(LOG_SHIP_DOCK, Ships[Pl_objp->instance].ship_name, Ships[goal_objp->instance].ship_name);
10161
10162                         if (aip->goals[aip->active_goal].ai_mode == AI_GOAL_DOCK) {
10163                                 ai_mission_goal_complete( aip );                                        // Note, this calls ai_set_default_behavior().
10164                         } 
10165                 } else {        //      Can happen for initially docked ships.
10166                         ai_do_default_behavior( &Objects[Ships[aip->shipnum].objnum] );         // do the default behavior
10167                 }
10168                 
10169                 break;
10170
10171         case AIS_DOCK_4: {
10172                 //      This mode is only for rearming/repairing.
10173                 //      The ship that is performing the rearm enters this mode after it docks.
10174                 SDL_assert((aip->goal_objnum >= -1) && (aip->goal_objnum < MAX_OBJECTS));
10175
10176                 //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10177                 float dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_DOCK);
10178                 SDL_assert(dist != UNINITIALIZED_VALUE);
10179
10180                 SDL_assert(goal_objp->type == OBJ_SHIP);
10181                 ship                    *goal_shipp = &Ships[goal_objp->instance];              
10182                 ai_info         *goal_aip = &Ai_info[goal_shipp->ai_index];
10183
10184                 //nprintf(("AI", "Dock 4: dist = %7.3f\n", dist));
10185
10186                 //      Make sure repair has not broken off.
10187                 if (dist > 5.0f) {      //      Oops, too far away!
10188                         if ( goal_aip->ai_flags & AIF_BEING_REPAIRED )
10189                                 ai_do_objects_repairing_stuff( goal_objp, Pl_objp, REPAIR_INFO_BROKEN);
10190
10191                         if (dist > Pl_objp->radius*2 + goal_objp->radius*2) {
10192                                 //      Got real far away from goal, so move back a couple modes and try again.
10193                                 aip->submode = AIS_DOCK_2;
10194                                 aip->submode_start_time = Missiontime;
10195                         }
10196                 } else {
10197                         if ( goal_aip->ai_flags & AIF_AWAITING_REPAIR )
10198                                 ai_do_objects_repairing_stuff( goal_objp, Pl_objp, REPAIR_INFO_BEGIN );
10199                 }
10200
10201                 break;
10202                                                   }
10203
10204         case AIS_UNDOCK_0: {
10205                 int path_num;
10206                 //      First stage of undocking.
10207
10208                 //nprintf(("AI", "Undock 0:\n"));
10209
10210                 aip->submode = AIS_UNDOCK_1;
10211                 aip->submode_start_time = Missiontime;
10212                 if (aip->dock_objnum == -1) {
10213                         aip->submode = AIS_UNDOCK_3;
10214                 } else {
10215
10216                         // set up the path points for the undocking procedure.  dock_path_index member should
10217                         // have gotten set in the docking code.
10218                         SDL_assert( aip->dock_path_index != -1 );
10219                         path_num = ai_return_path_num_from_dockbay(goal_objp, aip->dock_path_index);
10220                         ai_find_path(Pl_objp, goal_objp-Objects, path_num, 0);
10221
10222                         // Play a ship docking detach sound
10223                         snd_play_3d( &Snds[SND_DOCK_DETACH], &Pl_objp->pos, &View_position );
10224                 }
10225                 break;
10226                                                          }
10227         case AIS_UNDOCK_1: {
10228                 //      Using thrusters, exit from dock station to nearest next dock path point.
10229                 float   dist;
10230                 
10231                 //nprintf(("AI", "Undock 1: time in this mode = %7.3f\n", f2fl(Missiontime - aip->submode_start_time)));
10232
10233                 if (Missiontime - aip->submode_start_time < REARM_BREAKOFF_DELAY) {
10234                         break;          //      Waiting for one second to elapse to let detach sound effect play out.
10235                 }
10236                 else {  // AL - added 05/16/97.  Hack to play depart sound.  Will probably take out.
10237                                         // Assumes that the submode_start_time is not used for AIS_UNDOCK_1 anymore
10238                         if ( aip->submode_start_time != 0 )
10239                                 snd_play_3d( &Snds[SND_DOCK_DEPART], &Pl_objp->pos, &View_position );
10240                         aip->submode_start_time = 0;
10241                 }
10242
10243                 dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_UNDOCK_1);
10244                 SDL_assert(dist != UNINITIALIZED_VALUE);
10245
10246                 float dist_to_dock_obj = vm_vec_dist_quick(&Pl_objp->pos, &Objects[aip->goal_objnum].pos);
10247
10248                 //      Move to within 0.1 units of second last point on path before orienting, or just plain far away from docked-to ship.
10249                 //      This allows undock to complete if first ship flies away.
10250                 if ((dist < 2*flFrametime) || (dist_to_dock_obj > 2*Pl_objp->radius)) {
10251                         aip->submode = AIS_UNDOCK_2;
10252                         aip->submode_start_time = Missiontime;
10253                 }
10254                 break;
10255                                                          }
10256         case AIS_UNDOCK_2: {
10257                 float dist;
10258                 //ai_info *other_aip;
10259
10260                 // get pointer to docked object's aip to reset flags, etc
10261                 SDL_assert( aip->dock_objnum != -1 );
10262                 //other_aip = &Ai_info[Ships[Objects[aip->dock_objnum].instance].ai_index];
10263
10264                 //      Second stage of undocking.
10265                 dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_UNDOCK_2);
10266                 SDL_assert(dist != UNINITIALIZED_VALUE);
10267
10268
10269                 //nprintf(("AI", "Undock 2: dist = %7.3f\n", dist));
10270                 
10271                 //      If at goal point, or quite far away from dock object
10272                 if ((dist < 2.0f) || (vm_vec_dist_quick(&Pl_objp->pos, &goal_objp->pos) > (Pl_objp->radius + goal_objp->radius)*2) || (goal_objp->phys_info.speed > MAX_UNDOCK_ABORT_SPEED) ) {
10273                         // reset the dock flags.  If rearm/repair, reset rearm repair flags for those ships as well.
10274                         if ( sip->flags & SIF_SUPPORT ) {
10275                                 ai_do_objects_repairing_stuff( &Objects[aip->dock_objnum], Pl_objp, REPAIR_INFO_END );
10276                         }
10277
10278                         // clear out flags for AIF_DOCKED for both objects.
10279                         ai_do_objects_undocked_stuff( Pl_objp, goal_objp );
10280                         physics_ship_init(Pl_objp);
10281                         aip->submode = AIS_UNDOCK_3;                            //      The do-nothing mode, until another order is issued
10282
10283                         //aip->ai_flags &= ~AIF_DOCKED;         //      @MK, 9/18/97
10284                         //other_aip->ai_flags &= ~AIF_DOCKED;
10285                         //aip->dock_objnum = -1;                                        // invalidate who obj is docked with
10286                         //other_aip->dock_objnum = -1;                  // MWA 10/07/97 invalide docked objects dock_objnum value as well
10287
10288                         // don't add undock log entries for support ships.
10289                         if ( !(sip->flags & SIF_SUPPORT) )
10290                                 mission_log_add_entry(LOG_SHIP_UNDOCK, Ships[Pl_objp->instance].ship_name, Ships[goal_objp->instance].ship_name);
10291
10292                 }
10293                 break;
10294                 }
10295         case AIS_UNDOCK_3: {
10296                 float dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_UNDOCK_3);
10297                 SDL_assert(dist != UNINITIALIZED_VALUE);
10298
10299                 if (dist < Pl_objp->radius/2 + 5.0f) {
10300                         aip->submode = AIS_UNDOCK_4;
10301                 }
10302
10303                 // possible that this flag hasn't been cleared yet.  When aborting a rearm, this submode might
10304                 // be entered directly.
10305                 if ( (sip->flags & SIF_SUPPORT) && (aip->ai_flags & AIF_REPAIRING) ) {
10306                         ai_do_objects_repairing_stuff( &Objects[aip->goal_objnum], Pl_objp, REPAIR_INFO_ABORT );
10307                 }
10308
10309                 break;
10310                                                  }
10311         case AIS_UNDOCK_4: {
10312                 //ai_info *other_aip;
10313
10314                 // MWA 10/07/97  I'm slightly confused by the dual use of goal_objnum and dock_objnum.  Seems to me
10315                 // that goal_objnum and dock_objnum are the same through this whole docking/undocking process, although
10316                 // I could be wrong.  dock_objnum was reset in undock_2 submode so try to use goal_objnum here to
10317                 // get other ships ai_info pointer
10318                 //SDL_assert( aip->goal_objnum != -1 );
10319                 //other_aip = &Ai_info[Ships[Objects[aip->goal_objnum].instance].ai_index];
10320
10321                 aip->mode = AIM_NONE;
10322                 aip->dock_path_index = -1;              // invalidate the docking path index
10323
10324                 // these flags should have been cleared long ago!
10325                 // Get Allender if you hit one of these!!!!!
10326                 // removed by allender on 2/16 since a ship may be docked with some other ship, but still be the
10327                 // goal_objnum of this ship ending it's undocking mode.
10328                 //SDL_assert( !(aip->ai_flags & AIF_DOCKED) );
10329                 //SDL_assert( !(other_aip->ai_flags & AIF_DOCKED) );
10330                 //SDL_assert( !(aip->ai_flags & AIF_REPAIRING) );
10331                 //SDL_assert( !(other_aip->ai_flags & AIF_BEING_REPAIRED) );
10332                 //SDL_assert( !(other_aip->ai_flags & AIF_AWAITING_REPAIR) );
10333
10334                 // only call mission goal complete if this was indeed an undock goal
10335                 if ( aip->active_goal > -1 ) {
10336                         if ( aip->goals[aip->active_goal].ai_mode == AI_GOAL_UNDOCK )
10337                                 ai_mission_goal_complete( aip );                        // this call should reset the AI mode
10338                         //else
10339                         //      aip->active_goal = -1;                                          // this ensures that this ship might get new goal
10340                 }
10341
10342                 break;
10343                                                          }
10344         default:
10345                 Int3(); //      Error, bogus submode
10346         }
10347
10348 }
10349
10350 // TURRET BEGIN
10351
10352 //      Given an object and a turret on that object, return the global position and forward vector
10353 //      of the turret.   The gun normal is the unrotated gun normal, (the center of the FOV cone), not
10354 // the actual gun normal given using the current turret heading.  But it _is_ rotated into the model's orientation
10355 //      in global space.
10356 void ship_get_global_turret_info(object *objp, model_subsystem *tp, vector *gpos, vector *gvec)
10357 {
10358         matrix  m;
10359         vm_copy_transpose_matrix(&m, &objp->orient);
10360 //      vm_vec_rotate(gpos, &tp->turret_avg_firing_point, &m);
10361         vm_vec_rotate(gpos, &tp->pnt, &m);
10362         vm_vec_add2(gpos, &objp->pos);
10363         vm_vec_rotate(gvec, &tp->turret_norm, &m);      
10364 }
10365
10366 // Given an object and a turret on that object, return the actual firing point of the gun
10367 // and its normal.   This uses the current turret angles.  We are keeping track of which
10368 // gun to fire next in the ship specific info for this turret subobject.  Use this info
10369 // to determine which position to fire from next.
10370 //      Stuffs:
10371 //              *gpos: absolute position of gun firing point
10372 //              *gvec: vector fro *gpos to *targetp
10373 void ship_get_global_turret_gun_info(object *objp, ship_subsys *ssp, vector *gpos, vector *gvec, int use_angles, vector *targetp)
10374 {
10375         vector * gun_pos;
10376         model_subsystem *tp = ssp->system_info;
10377
10378         ship_model_start(objp);
10379
10380         gun_pos = &tp->turret_firing_point[ssp->turret_next_fire_pos % tp->turret_num_firing_points];
10381
10382         model_find_world_point(gpos, gun_pos, tp->model_num, tp->turret_gun_sobj, &objp->orient, &objp->pos );
10383
10384         if (use_angles)
10385                 model_find_world_dir(gvec, &tp->turret_norm, tp->model_num, tp->turret_gun_sobj, &objp->orient, &objp->pos );
10386         else {
10387                 //vector        gun_pos2;
10388                 //vm_vec_add(&gun_pos2, gpos, gun_pos);
10389                 vm_vec_normalized_dir(gvec, targetp, gpos);
10390         }
10391
10392         ship_model_stop(objp);  
10393 }
10394
10395 //      Rotate a turret towards an enemy.
10396 //      Return TRUE if caller should use angles in subsequent rotations.
10397 //      Some obscure model thing only John Slagel knows about.
10398 //      Sets predicted enemy position.
10399 //      If the turret (*ss) has a subsystem targeted, the subsystem is used as the predicted point.
10400 int aifft_rotate_turret(ship *shipp, int parent_objnum, ship_subsys *ss, object *objp, object *lep, vector *predicted_enemy_pos, vector *gvec)
10401 {
10402         if (ss->turret_enemy_objnum != -1)      {
10403                 model_subsystem *tp = ss->system_info;
10404                 vector  gun_pos, gun_vec;
10405                 float           weapon_speed;
10406                 float           weapon_system_strength;
10407
10408                 //      weapon_system_strength scales time enemy in range in 0..1.  So, the lower this is, the worse the aiming will be.
10409                 weapon_system_strength = ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS);
10410
10411                 ship_get_global_turret_info(&Objects[parent_objnum], tp, &gun_pos, &gun_vec);
10412
10413                 weapon_speed = Weapon_info[tp->turret_weapon_type].max_speed;
10414                 float weapon_travel_dist = weapon_speed * Weapon_info[tp->turret_weapon_type].lifetime;
10415
10416                 vector  enemy_point;
10417                 if (ss->targeted_subsys != NULL) {
10418                         if (ss->turret_enemy_objnum != -1) {
10419                                 vm_vec_unrotate(&enemy_point, &ss->targeted_subsys->system_info->pnt, &Objects[ss->turret_enemy_objnum].orient);
10420                                 vm_vec_add2(&enemy_point, &Objects[ss->turret_enemy_objnum].pos);
10421                         }
10422                 } else {
10423                         if ((lep->type == OBJ_SHIP) && (Ship_info[Ships[lep->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
10424                                 ai_big_pick_attack_point_turret(lep, ss, &gun_pos, &gun_vec, &enemy_point, tp->turret_fov, SDL_min(weapon_travel_dist, Weapon_info[tp->turret_weapon_type].weapon_range));
10425                         } else {
10426                                 enemy_point = lep->pos;
10427                         }
10428                 }
10429
10430                 set_predicted_enemy_pos_turret(predicted_enemy_pos, &gun_pos, objp, &enemy_point, &lep->phys_info.vel, weapon_speed, ss->turret_time_enemy_in_range * (weapon_system_strength + 1.0f)/2.0f);
10431
10432                 if (weapon_system_strength < 0.7f) {
10433                         vector  rand_vec;
10434
10435                         static_randvec(Missiontime >> 18, &rand_vec);   //      Return same random number for two seconds.
10436                         //      Add to predicted_enemy_pos value in .45 to 1.5x radius of enemy ship, so will often miss, but not by a huge amount.
10437                         vm_vec_scale_add2(predicted_enemy_pos, &rand_vec, (1.0f - weapon_system_strength)*1.5f * lep->radius);
10438                 }
10439
10440                 vector  v2e;
10441                 vm_vec_normalized_dir(&v2e, predicted_enemy_pos, &gun_pos);
10442                 if (vm_vec_dot(&v2e, gvec) > tp->turret_fov) {
10443                         model_rotate_gun(shipp->modelnum, ss->system_info, &Objects[parent_objnum].orient,
10444                                 &ss->submodel_info_1.angs, &ss->submodel_info_2.angs,
10445                                 &Objects[parent_objnum].pos, predicted_enemy_pos);
10446                 }
10447         }
10448
10449         return 0;
10450 }
10451
10452 //      Determine if subsystem *enemy_subsysp is hittable from objp.
10453 //      If so, return dot product of vector from point abs_gunposp to *enemy_subsysp
10454 float   aifft_compute_turret_dot(object *objp, object *enemy_objp, vector *abs_gunposp, ship_subsys *turret_subsysp, ship_subsys *enemy_subsysp)
10455 {
10456         float   dot_out;
10457         vector  subobj_pos, vector_out;
10458
10459         vm_vec_unrotate(&subobj_pos, &enemy_subsysp->system_info->pnt, &enemy_objp->orient);
10460         vm_vec_add2(&subobj_pos, &enemy_objp->pos);
10461
10462         if (ship_subsystem_in_sight(enemy_objp, enemy_subsysp, abs_gunposp, &subobj_pos, 1, &dot_out, &vector_out)) {
10463                 vector  turret_norm;
10464
10465                 vm_vec_rotate(&turret_norm, &turret_subsysp->system_info->turret_norm, &objp->orient);
10466                 return vm_vec_dot(&turret_norm, &vector_out);
10467         } else
10468                 return -1.0f;
10469
10470 }
10471
10472 #define MAX_AIFFT_TURRETS                       60
10473 ship_subsys *aifft_list[MAX_AIFFT_TURRETS];
10474 float aifft_rank[MAX_AIFFT_TURRETS];
10475 int aifft_list_size = 0;
10476 int aifft_max_checks = 5;
10477 DCF(mf, "")
10478 {
10479         dc_get_arg(ARG_INT);
10480         aifft_max_checks = Dc_arg_int;
10481 }
10482
10483
10484 //      Pick a subsystem to attack on enemy_objp.
10485 //      Only pick one if enemy_objp is a big ship or a capital ship.
10486 //      Returns dot product from turret to subsystem in *dot_out
10487 ship_subsys *aifft_find_turret_subsys(object *objp, ship_subsys *ssp, object *enemy_objp, float *dot_out)
10488 {
10489         ship    *eshipp;
10490         ship_info       *esip;
10491         ship_subsys     *best_subsysp = NULL;
10492         float dot;
10493
10494         SDL_assert(enemy_objp->type == OBJ_SHIP);
10495
10496         eshipp = &Ships[enemy_objp->instance];
10497         esip = &Ship_info[eshipp->ship_info_index];
10498
10499         float   best_dot = 0.0f;
10500         *dot_out = best_dot;
10501
10502         //      Compute absolute gun position.
10503         vector  abs_gun_pos;
10504         vm_vec_unrotate(&abs_gun_pos, &ssp->system_info->pnt, &objp->orient);
10505         vm_vec_add2(&abs_gun_pos, &objp->pos);
10506
10507         //      Only pick a turret to attack on large ships.
10508         if (!(esip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)))
10509                 return best_subsysp;
10510
10511         // Make sure big or huge ship *actually* has subsystems  (ie, knossos)
10512         if (esip->n_subsystems == 0) {
10513                 return best_subsysp;
10514         }
10515
10516         // first build up a list subsystems to traverse
10517         ship_subsys     *pss;
10518         aifft_list_size = 0;
10519         for ( pss = GET_FIRST(&eshipp->subsys_list); pss !=END_OF_LIST(&eshipp->subsys_list); pss = GET_NEXT(pss) ) {
10520                 model_subsystem *psub = pss->system_info;
10521
10522                 // if we've reached max turrets bail
10523                 if(aifft_list_size >= MAX_AIFFT_TURRETS){
10524                         break;
10525                 }
10526
10527                 // Don't process destroyed objects
10528                 if ( pss->current_hits <= 0.0f ){
10529                         continue;
10530                 }
10531                 
10532                 switch (psub->type) {
10533                 case SUBSYSTEM_WEAPONS:
10534                         aifft_list[aifft_list_size] = pss;
10535                         aifft_rank[aifft_list_size++] = 1.4f;
10536                         break;
10537
10538                 case SUBSYSTEM_TURRET:
10539                         aifft_list[aifft_list_size] = pss;
10540                         aifft_rank[aifft_list_size++] = 1.2f;
10541                         break;
10542
10543                 case SUBSYSTEM_SENSORS:
10544                 case SUBSYSTEM_ENGINE:
10545                         aifft_list[aifft_list_size] = pss;
10546                         aifft_rank[aifft_list_size++] = 1.0f;
10547                         break;
10548                 }
10549         }
10550
10551         // DKA:  6/28/99 all subsystems can be destroyed.
10552         //SDL_assert(aifft_list_size > 0);
10553         if (aifft_list_size == 0) {
10554                 return best_subsysp;
10555         }
10556
10557         // determine a stride value so we're not checking too many turrets
10558         int stride = aifft_list_size > aifft_max_checks ? aifft_list_size / aifft_max_checks : 1;
10559         if(stride <= 0){
10560                 stride = 1;
10561         }
10562         int offset = (int)frand_range(0.0f, (float)(aifft_list_size % stride));
10563         int idx;
10564         for(idx=offset; idx<aifft_list_size; idx+=stride){
10565                 dot = aifft_compute_turret_dot(objp, enemy_objp, &abs_gun_pos, ssp, aifft_list[idx]);                   
10566
10567                 if (dot* aifft_rank[idx] > best_dot) {
10568                         best_dot = dot*aifft_rank[idx];
10569                         best_subsysp = aifft_list[idx];
10570                 }
10571         }
10572
10573         SDL_assert(best_subsysp != &eshipp->subsys_list);
10574
10575         *dot_out = best_dot;
10576         return best_subsysp;
10577 }
10578
10579 // Set active weapon for turret
10580 void ai_turret_select_default_weapon(ship_subsys *turret)
10581 {
10582         ship_weapon *twp;
10583
10584         twp = &turret->weapons;
10585
10586         // If a primary weapon is available, select it
10587         if ( twp->num_primary_banks > 0 ) {
10588                 turret->system_info->turret_weapon_type = twp->primary_bank_weapons[0];
10589         } else if ( twp->num_secondary_banks > 0 ) {
10590                 turret->system_info->turret_weapon_type = twp->secondary_bank_weapons[0];
10591         }
10592 }
10593
10594 // return !0 if the specified target should scan for a new target, otherwise return 0
10595 int turret_should_pick_new_target(ship_subsys *turret)
10596 {
10597 //      int target_type;
10598
10599         if ( timestamp_elapsed(turret->turret_next_enemy_check_stamp) ) {
10600                 return 1;
10601         }
10602
10603         return 0;
10604
10605 /*
10606         if ( turret->turret_enemy_objnum == -1 ) {
10607                 return 1;
10608         }
10609                 
10610         target_type = Objects[turret->turret_enemy_objnum].type;
10611         if ( (target_type != OBJ_SHIP) && (target_type != OBJ_ASTEROID) ) {
10612                 return 1;
10613         }
10614
10615         return 0;
10616 */
10617 }
10618
10619 // Set the next fire timestamp for a turret, based on weapon type and ai class
10620 void turret_set_next_fire_timestamp(ship_subsys *turret, ai_info *aip)
10621 {
10622         float   wait;
10623         int     weapon_id;
10624
10625         weapon_id = turret->system_info->turret_weapon_type;
10626
10627         wait = Weapon_info[weapon_id].fire_wait * 1000.0f;
10628
10629         // make side even for team vs. team
10630         if ((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_TEAM)) {
10631                 // flak guns need to fire more rapidly
10632                 if (Weapon_info[weapon_id].wi_flags & WIF_FLAK) {
10633                         wait *= Ship_fire_delay_scale_friendly[Game_skill_level] * 0.5f;
10634                         wait += (Num_ai_classes - aip->ai_class - 1) * 40.0f;
10635                 } else {
10636                         wait *= Ship_fire_delay_scale_friendly[Game_skill_level];
10637                         wait += (Num_ai_classes - aip->ai_class - 1) * 100.0f;
10638                 }
10639         } else {
10640                 // flak guns need to fire more rapidly
10641                 if (Weapon_info[weapon_id].wi_flags & WIF_FLAK) {
10642                         if (Ships[aip->shipnum].team == TEAM_FRIENDLY) {
10643                                 wait *= Ship_fire_delay_scale_friendly[Game_skill_level] * 0.5f;
10644                         } else {
10645                                 wait *= Ship_fire_delay_scale_hostile[Game_skill_level] * 0.5f;
10646                         }       
10647                         wait += (Num_ai_classes - aip->ai_class - 1) * 40.0f;
10648
10649                 } else if (Weapon_info[weapon_id].wi_flags & WIF_HUGE) {
10650                         // make huge weapons fire independently of team
10651                         wait *= Ship_fire_delay_scale_friendly[Game_skill_level];
10652                         wait += (Num_ai_classes - aip->ai_class - 1) * 100.0f;
10653                 } else {
10654                         // give team friendly an advantage
10655                         if (Ships[aip->shipnum].team == TEAM_FRIENDLY) {
10656                                 wait *= Ship_fire_delay_scale_friendly[Game_skill_level];
10657                         } else {
10658                                 wait *= Ship_fire_delay_scale_hostile[Game_skill_level];
10659                         }       
10660                         wait += (Num_ai_classes - aip->ai_class - 1) * 100.0f;
10661                 }
10662         }
10663
10664         // vary wait time +/- 10%
10665         wait *= frand_range(0.9f, 1.1f);
10666         turret->turret_next_fire_stamp = timestamp((int) wait);
10667 }
10668
10669 // Decide  if a turret should launch an aspect seeking missile
10670 int turret_should_fire_aspect(ship_subsys *turret, float dot, int weapon_class)
10671 {
10672         weapon_info *wip;
10673
10674         wip = &Weapon_info[weapon_class];
10675
10676         if ( (dot > AICODE_TURRET_DUMBFIRE_ANGLE) && (turret->turret_time_enemy_in_range >= SDL_min(wip->min_lock_time,AICODE_TURRET_MAX_TIME_IN_RANGE)) ) {
10677                 return 1;
10678         }
10679
10680         return 0;
10681 }
10682
10683 // Update how long current target has been in this turrets range
10684 void turret_update_enemy_in_range(ship_subsys *turret, float seconds)
10685 {
10686         turret->turret_time_enemy_in_range += seconds;
10687
10688         if ( turret->turret_time_enemy_in_range < 0.0f ) {
10689                 turret->turret_time_enemy_in_range = 0.0f;
10690         }
10691
10692         if ( turret->turret_time_enemy_in_range > AICODE_TURRET_MAX_TIME_IN_RANGE ) {
10693                 turret->turret_time_enemy_in_range = AICODE_TURRET_MAX_TIME_IN_RANGE;
10694         }
10695 }
10696
10697
10698
10699 // Fire a weapon from a turret
10700 void turret_fire_weapon(ship_subsys *turret, int parent_objnum, vector *turret_pos, vector *turret_fvec, vector *predicted_pos = NULL)
10701 {
10702         matrix  turret_orient;
10703         int             turret_weapon_class, weapon_objnum;
10704         ai_info *parent_aip;
10705         ship            *parent_ship;
10706         beam_fire_info fire_info;
10707         float flak_range = 0.0f;
10708
10709         parent_aip = &Ai_info[Ships[Objects[parent_objnum].instance].ai_index];
10710         parent_ship = &Ships[Objects[parent_objnum].instance];
10711         turret_weapon_class = turret->system_info->turret_weapon_type;
10712
10713         if (check_ok_to_fire(parent_objnum, turret->turret_enemy_objnum, &Weapon_info[turret_weapon_class])) {
10714                 vm_vector_2_matrix(&turret_orient, turret_fvec, NULL, NULL);
10715                 turret->turret_last_fire_direction = *turret_fvec;
10716
10717                 // set next fire timestamp for the turret
10718                 turret_set_next_fire_timestamp(turret, parent_aip);
10719
10720                 // if this weapon is a beam weapon, handle it specially
10721                 if(Weapon_info[turret_weapon_class].wi_flags & WIF_BEAM){
10722                         // if this beam isn't free to fire
10723                         if (!(turret->weapons.flags & SW_FLAG_BEAM_FREE)) {
10724                                 Int3(); // should never get this far
10725                                 return;
10726                         }
10727
10728                         // stuff beam firing info
10729                         memset(&fire_info, 0, sizeof(beam_fire_info));
10730                         fire_info.accuracy = 1.0f;
10731                         fire_info.beam_info_index = turret_weapon_class;
10732                         fire_info.beam_info_override = NULL;
10733                         fire_info.shooter = &Objects[parent_objnum];
10734                         fire_info.target = &Objects[turret->turret_enemy_objnum];
10735                         fire_info.target_subsys = NULL;
10736                         fire_info.turret = turret;
10737
10738                         // fire a beam weapon
10739                         beam_fire(&fire_info);
10740                 } else {
10741
10742                         // don't fire swarm, but set up swarm info
10743                         if (Weapon_info[turret_weapon_class].wi_flags & WIF_SWARM) {
10744                                 turret_swarm_set_up_info(parent_objnum, turret, turret_weapon_class);
10745                                 return;
10746                         } else {
10747                                 weapon_objnum = weapon_create( turret_pos, &turret_orient, turret_weapon_class, parent_objnum, 0, -1, 1);
10748                                 weapon_set_tracking_info(weapon_objnum, parent_objnum, turret->turret_enemy_objnum, 1, turret->targeted_subsys);                
10749                         }
10750
10751                         //nprintf(("AI", "Turret_time_enemy_in_range = %7.3f\n", ss->turret_time_enemy_in_range));              
10752                         if (weapon_objnum != -1) {
10753                                 Weapons[Objects[weapon_objnum].instance].target_num = turret->turret_enemy_objnum;
10754                                 // AL 1-6-97: Store pointer to turret subsystem
10755                                 Weapons[Objects[weapon_objnum].instance].turret_subsys = turret;
10756
10757                                 if ( Weapon_info[turret_weapon_class].launch_snd != -1 ) {
10758                                         // Don't play turret firing sound if turret sits on player ship... it gets annoying.
10759                                         if ( parent_objnum != OBJ_INDEX(Player_obj) ) {                                         
10760                                                 snd_play_3d( &Snds[Weapon_info[turret_weapon_class].launch_snd], turret_pos, &View_position );                                          
10761                                         }
10762                                 }               
10763
10764                                 // if the gun is a flak gun
10765                                 if(Weapon_info[turret_weapon_class].wi_flags & WIF_FLAK){                       
10766                                         // show a muzzle flash
10767                                         flak_muzzle_flash(turret_pos, turret_fvec, turret_weapon_class);
10768
10769                                         // pick a firing range so that it detonates properly                    
10770                                         flak_pick_range(&Objects[weapon_objnum], predicted_pos, ship_get_subsystem_strength(parent_ship, SUBSYSTEM_WEAPONS));
10771
10772                                         // determine what that range was
10773                                         flak_range = flak_get_range(&Objects[weapon_objnum]);
10774                                 }
10775
10776                                 // in multiplayer (and the master), then send a turret fired packet.
10777                                 if ( MULTIPLAYER_MASTER && (weapon_objnum != -1) ) {
10778                                         int subsys_index;
10779
10780                                         subsys_index = ship_get_index_from_subsys(turret, parent_objnum );
10781                                         SDL_assert( subsys_index != -1 );
10782                                         if(Weapon_info[turret_weapon_class].wi_flags & WIF_FLAK){                       
10783                                                 send_flak_fired_packet( parent_objnum, subsys_index, weapon_objnum, flak_range );
10784                                         } else {
10785                                                 send_turret_fired_packet( parent_objnum, subsys_index, weapon_objnum );
10786                                         }
10787                                 }
10788                         }
10789                 }
10790         } else {
10791                 float wait = 1000.0f * frand_range(0.9f, 1.1f);
10792                 turret->turret_next_fire_stamp = timestamp((int) wait);
10793         }
10794 }
10795
10796 void turret_swarm_fire_from_turret(ship_subsys *turret, int parent_objnum, int target_objnum, ship_subsys *target_subsys)
10797 {
10798         int turret_weapon_class, weapon_objnum;
10799         matrix turret_orient;
10800         vector turret_pos, turret_fvec;
10801
10802         // parent not alive, quick out.
10803         if (Objects[parent_objnum].type != OBJ_SHIP) {
10804                 return;
10805         }
10806
10807         //      change firing point
10808         ship_get_global_turret_gun_info(&Objects[parent_objnum], turret, &turret_pos, &turret_fvec, 1, NULL);
10809         turret->turret_next_fire_pos++;
10810
10811         // get class [index into Weapon_info array
10812         turret_weapon_class = turret->system_info->turret_weapon_type;
10813         SDL_assert(Weapon_info[turret_weapon_class].wi_flags & WIF_SWARM);
10814
10815         // make turret_orient from turret_fvec -- turret->turret_last_fire_direction
10816         vm_vector_2_matrix(&turret_orient, &turret_fvec, NULL, NULL);
10817
10818         // create weapon and homing info
10819         weapon_objnum = weapon_create(&turret_pos, &turret_orient, turret_weapon_class, parent_objnum, 0, -1, 1);
10820         weapon_set_tracking_info(weapon_objnum, parent_objnum, target_objnum, 1, target_subsys);
10821
10822         // do other cool stuff if weapon is created.
10823         if (weapon_objnum > -1) {
10824                 Weapons[Objects[weapon_objnum].instance].turret_subsys = turret;
10825                 Weapons[Objects[weapon_objnum].instance].target_num = turret->turret_enemy_objnum;
10826
10827                 // maybe sound
10828                 if ( Weapon_info[turret_weapon_class].launch_snd != -1 ) {
10829                         // Don't play turret firing sound if turret sits on player ship... it gets annoying.
10830                         if ( parent_objnum != OBJ_INDEX(Player_obj) ) {
10831                                 snd_play_3d( &Snds[Weapon_info[turret_weapon_class].launch_snd], &turret_pos, &View_position );
10832                         }
10833                 }
10834                 
10835                 // in multiplayer (and the master), then send a turret fired packet.
10836                 if ( MULTIPLAYER_MASTER && (weapon_objnum != -1) ) {
10837                         int subsys_index;
10838
10839                         subsys_index = ship_get_index_from_subsys(turret, parent_objnum );
10840                         SDL_assert( subsys_index != -1 );
10841                         send_turret_fired_packet( parent_objnum, subsys_index, weapon_objnum );
10842                 }
10843         }
10844 }
10845
10846 int Num_ai_firing = 0;
10847 int Num_find_turret_enemy = 0;
10848 int Num_turrets_fired = 0;
10849 //      Given a turret tp and its parent parent_objnum, fire from the turret at its enemy.
10850 void ai_fire_from_turret(ship *shipp, ship_subsys *ss, int parent_objnum)
10851 {
10852         float           weapon_firing_range;
10853         vector  v2e;
10854         object  *lep;           //      Last enemy pointer
10855         model_subsystem *tp = ss->system_info;
10856         int             use_angles, turret_weapon_class;
10857         vector  predicted_enemy_pos;
10858         object  *objp;
10859         ai_info *aip;
10860
10861         if (!Ai_firing_enabled) {
10862                 return;
10863         }
10864
10865         if (ss->current_hits < 0.0f) {
10866                 return;
10867         }
10868
10869         if ( ship_subsys_disrupted(ss) ){               // AL 1/19/98: Make sure turret isn't suffering disruption effects
10870                 return;
10871         }
10872
10873         // Check turret free
10874         if (ss->weapons.flags & SW_FLAG_TURRET_LOCK) {
10875                 return;
10876         }
10877
10878         // If beam weapon, check beam free
10879         if ( (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM) && !(ss->weapons.flags & SW_FLAG_BEAM_FREE) ) {
10880                 return;
10881         }
10882
10883         SDL_assert( shipp->objnum == parent_objnum );
10884
10885         if ( tp->turret_weapon_type < 0 ){
10886                 return;
10887         }
10888
10889         // Monitor number of calls to ai_fire_from_turret
10890         Num_ai_firing++;
10891
10892         turret_weapon_class = tp->turret_weapon_type;
10893
10894         // AL 09/14/97: ensure ss->turret_enemy_objnum != -1 before setting lep
10895         if ( (ss->turret_enemy_objnum >= 0 && ss->turret_enemy_objnum < MAX_OBJECTS) && (ss->turret_enemy_sig == Objects[ss->turret_enemy_objnum].signature)) {
10896                 lep = &Objects[ss->turret_enemy_objnum];
10897
10898                 // MK -- here is where turret is targeting a bomb.  I simply return for now.  We should force
10899                 // a target change -- or better yet, never pick a weapon when this turret has a "huge" weapon
10900                 // loaded.
10901
10902                 // we only care about targets which are ships.
10903                 //if ( lep->type != OBJ_SHIP )
10904                 //      return;
10905
10906                 //      If targeted a small ship and have a huge weapon, don't fire.  But this shouldn't happen, as a small ship should not get selected.
10907                 if ( Weapon_info[turret_weapon_class].wi_flags & WIF_HUGE ) {
10908                         if ( lep->type != OBJ_SHIP ) {
10909                                 return;
10910                         }
10911                         if ( !(Ship_info[Ships[lep->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) ) {
10912                                 return;
10913                         }
10914                 }
10915
10916                 // If targeting protected or beam protected ship, don't fire.  Reset enemy objnum
10917                 if (lep->type == OBJ_SHIP) {
10918                         // Check if we're targeting a protected ship
10919                         if (lep->flags & OF_PROTECTED) {
10920                                 ss->turret_enemy_objnum = -1;
10921                                 ss->turret_time_enemy_in_range = 0.0f;
10922                                 return;
10923                         }
10924
10925                         // Check if we're targeting a beam protected ship with a beam weapon
10926                         if ( (lep->flags & OF_BEAM_PROTECTED) && (Weapon_info[turret_weapon_class].wi_flags & WIF_BEAM) ) {
10927                                 ss->turret_enemy_objnum = -1;
10928                                 ss->turret_time_enemy_in_range = 0.0f;
10929                                 return;
10930                         }
10931                 }
10932         } else {
10933                 ss->turret_enemy_objnum = -1;
10934                 lep = NULL;
10935         }
10936         
10937         SDL_assert((parent_objnum >= 0) && (parent_objnum < MAX_OBJECTS));
10938         objp = &Objects[parent_objnum];
10939         SDL_assert(objp->type == OBJ_SHIP);
10940         aip = &Ai_info[Ships[objp->instance].ai_index];
10941
10942         // Use the turret info for all guns, not one gun in particular.
10943         vector   gvec, gpos;
10944         ship_get_global_turret_info(&Objects[parent_objnum], tp, &gpos, &gvec);
10945
10946         // Rotate the turret even if time hasn't elapsed, since it needs to turn to face its target.
10947         use_angles = aifft_rotate_turret(shipp, parent_objnum, ss, objp, lep, &predicted_enemy_pos, &gvec);
10948
10949         if ( !timestamp_elapsed(ss->turret_next_fire_stamp)){
10950                 return;
10951         }
10952
10953         // Don't try to fire beyond weapon_limit_range
10954         weapon_firing_range = SDL_min(Weapon_info[tp->turret_weapon_type].lifetime * Weapon_info[tp->turret_weapon_type].max_speed, Weapon_info[tp->turret_weapon_type].weapon_range);
10955
10956         // if beam weapon in nebula and target not tagged, decrase firing range
10957         extern int Nebula_sec_range;
10958         if (Weapon_info[turret_weapon_class].wi_flags & WIF_BEAM) {
10959                 if ( !((shipp->tag_left > 0) || (shipp->level2_tag_left > 0)) ) {
10960                         if (Nebula_sec_range) {
10961                                 weapon_firing_range *= float(BEAM_NEBULA_RANGE_REDUCE_FACTOR);
10962                         }
10963                 }
10964         }
10965
10966         if (ss->turret_enemy_objnum != -1) {
10967                 float dist_to_enemy = vm_vec_normalized_dir(&v2e, &predicted_enemy_pos, &gpos) - lep->radius;
10968                 if (dist_to_enemy > weapon_firing_range) {
10969                         ss->turret_enemy_objnum = -1;           //      Force picking of new enemy.
10970                 }
10971         }
10972
10973         // Turret spawn weapons are a special case.  They fire if there are enough enemies in the 
10974         // immediate area (not necessarily in the turret fov).
10975         if ( Weapon_info[turret_weapon_class].wi_flags & WIF_SPAWN ) {
10976                 int num_ships_nearby;
10977                 num_ships_nearby = num_nearby_fighters(get_enemy_team_mask(parent_objnum), &gpos, 1500.0f);
10978                 if (( num_ships_nearby >= 3 ) || ((num_ships_nearby >= 2) && (frand() < 0.1f))) {
10979                         turret_fire_weapon(ss, parent_objnum, &gpos, &ss->turret_last_fire_direction);
10980                 } else {
10981                         ss->turret_next_fire_stamp = timestamp(1000);   //      Regardless of firing rate, don't check whether should fire for awhile.
10982                 }
10983                 return;
10984         }
10985
10986         //      Maybe pick a new enemy.
10987         if ( turret_should_pick_new_target(ss) ) {
10988                 Num_find_turret_enemy++;
10989                 int objnum = find_turret_enemy(ss, parent_objnum, &gpos, &gvec, ss->turret_enemy_objnum, tp->turret_fov, Weapon_info[turret_weapon_class].wi_flags & WIF_HUGE);
10990                 SDL_assert(objnum < 0 || is_target_beam_valid(ss, objnum));
10991
10992                 if (objnum != -1) {
10993                         if (ss->turret_enemy_objnum == -1) {
10994                                 ss->turret_enemy_objnum = objnum;
10995                                 ss->turret_enemy_sig = Objects[objnum].signature;
10996                                 // why return?
10997                                 return;
10998                         } else {
10999                                 ss->turret_enemy_objnum = objnum;
11000                                 ss->turret_enemy_sig = Objects[objnum].signature;
11001                         }
11002                 } else {
11003                         ss->turret_enemy_objnum = -1;
11004                 }
11005
11006                 if (ss->turret_enemy_objnum != -1) {
11007                         float   dot = 1.0f;
11008                         lep = &Objects[ss->turret_enemy_objnum];
11009                         if ( lep->type == OBJ_SHIP ) {
11010                                 ss->targeted_subsys = aifft_find_turret_subsys(objp, ss, lep, &dot);                            
11011                         }
11012                         ss->turret_next_enemy_check_stamp = timestamp((int) (SDL_max(dot, 0.5f)*2000.0f) + 1000);
11013                 } else {
11014                         ss->turret_next_enemy_check_stamp = timestamp((int) (2000.0f * frand_range(0.9f, 1.1f)));       //      Check every two seconds
11015                 }
11016         }
11017
11018         //      If still don't have an enemy, return.  Or, if enemy is protected, return.
11019         if (ss->turret_enemy_objnum != -1) {
11020                 //      Don't shoot at ship we're going to dock with.
11021                 if (ss->turret_enemy_objnum == aip->dock_objnum) {
11022                         ss->turret_enemy_objnum = -1;
11023                         return;
11024                 }
11025
11026                 if (Objects[ss->turret_enemy_objnum].flags & OF_PROTECTED) {
11027                         //      This can happen if the enemy was selected before it became protected.
11028                         ss->turret_enemy_objnum = -1;
11029                         return;
11030                 }
11031                 lep = &Objects[ss->turret_enemy_objnum];
11032         } else {
11033                 if (timestamp_until(ss->turret_next_fire_stamp) < 500) {
11034                         ss->turret_next_fire_stamp = timestamp(500);
11035                 }
11036                 return;
11037         }
11038
11039         if ( lep == NULL ){
11040                 return;
11041         }
11042
11043         SDL_assert(ss->turret_enemy_objnum != -1);
11044
11045         float dot = vm_vec_dot(&v2e, &gvec);
11046
11047         if (dot > tp->turret_fov ) {
11048                 // Ok, the turret is lined up... now line up a particular gun.
11049                 int ok_to_fire = 0;
11050                 float dist_to_enemy;
11051
11052                 // We're ready to fire... now get down to specifics, like where is the
11053                 // actual gun point and normal, not just the one for whole turret.
11054                 ship_get_global_turret_gun_info(&Objects[parent_objnum], ss, &gpos, &gvec, use_angles, &predicted_enemy_pos);
11055                 ss->turret_next_fire_pos++;
11056
11057                 // Fire in the direction the turret is facing, not right at the target regardless of turret dir.
11058                 vm_vec_sub(&v2e, &predicted_enemy_pos, &gpos);
11059                 dist_to_enemy = vm_vec_normalize(&v2e);
11060                 dot = vm_vec_dot(&v2e, &gvec);
11061
11062                 // if the weapon is a flak gun, add some jitter to its aim so it fires in a "cone" to make a cool visual effect
11063                 // and make them less lethal
11064                 if(Weapon_info[turret_weapon_class].wi_flags & WIF_FLAK){
11065                         flak_jitter_aim(&v2e, dist_to_enemy, ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS));
11066                 }
11067
11068                 // Fire if:
11069                 //              dumbfire and nearly pointing at target.
11070                 //              heat seeking and target in a fairly wide cone.
11071                 //              aspect seeking and target is locked.
11072                 turret_weapon_class = tp->turret_weapon_type;
11073
11074                 // if dumbfire (lasers and non-homing missiles)
11075                 if ( !(Weapon_info[turret_weapon_class].wi_flags & WIF_HOMING) ) {
11076                         if ((dist_to_enemy < 75.0f) || (dot > AICODE_TURRET_DUMBFIRE_ANGLE )) {
11077                                 turret_update_enemy_in_range(ss, 2*Weapon_info[turret_weapon_class].fire_wait);
11078                                 ok_to_fire = 1;
11079                         }
11080                 } else if ( Weapon_info[turret_weapon_class].wi_flags & WIF_HOMING_HEAT ) {     // if heat seekers
11081                         if ((dist_to_enemy < 50.0f) || (dot > AICODE_TURRET_HEATSEEK_ANGLE )) {
11082                                 turret_update_enemy_in_range(ss, 2*Weapon_info[turret_weapon_class].fire_wait);
11083                                 ok_to_fire = 1;
11084                         }
11085                 } else if ( Weapon_info[turret_weapon_class].wi_flags & WIF_HOMING_ASPECT ) {   // if aspect seeker
11086                         if ((dist_to_enemy < 50.0f) || (dot > AICODE_TURRET_DUMBFIRE_ANGLE )) {
11087                                 turret_update_enemy_in_range(ss, 2*Weapon_info[turret_weapon_class].fire_wait);
11088                         }
11089                         if ( turret_should_fire_aspect(ss, dot, turret_weapon_class) ) {
11090                                 ok_to_fire = 1;
11091                         }
11092                 }
11093
11094                 if ( ok_to_fire ) {
11095                         Num_turrets_fired++;
11096                         
11097                         turret_fire_weapon(ss, parent_objnum, &gpos, &v2e, &predicted_enemy_pos);                                               
11098                 } else {
11099                         turret_update_enemy_in_range(ss, -4*Weapon_info[tp->turret_weapon_type].fire_wait);
11100                         ss->turret_next_fire_stamp = timestamp(500);
11101                 }
11102         } else {
11103                 // Lost him!
11104                 ss->turret_enemy_objnum = -1;           //      Reset enemy objnum, find a new one next frame.
11105                 ss->turret_time_enemy_in_range = 0.0f;
11106         }
11107 }
11108
11109 // TURRET END
11110
11111 #ifndef NDEBUG
11112 #define MAX_AI_DEBUG_RENDER_STUFF       100
11113 typedef struct ai_render_stuff {
11114         ship_subsys     *ss;
11115         int                     parent_objnum;
11116 } ai_render_stuff;
11117
11118 ai_render_stuff AI_debug_render_stuff[MAX_AI_DEBUG_RENDER_STUFF];
11119
11120 int     Num_AI_debug_render_stuff = 0;
11121
11122 void ai_debug_render_stuff()
11123 {
11124         vertex  vert1, vert2;
11125         vector  gpos2;
11126         int             i;
11127
11128         for (i=0; i<Num_AI_debug_render_stuff; i++) {
11129                 ship_subsys     *ss;
11130                 int     parent_objnum;
11131                 vector  gpos, gvec;
11132                 model_subsystem *tp;
11133
11134                 ss = AI_debug_render_stuff[i].ss;
11135                 tp = ss->system_info;
11136
11137                 parent_objnum = AI_debug_render_stuff[i].parent_objnum;
11138
11139                 ship_get_global_turret_info(&Objects[parent_objnum], tp, &gpos, &gvec);
11140                 g3_rotate_vertex(&vert1, &gpos);
11141                 vm_vec_scale_add(&gpos2, &gpos, &gvec, 20.0f);
11142                 g3_rotate_vertex(&vert2, &gpos2);
11143                 gr_set_color(0, 0, 255);
11144                 g3_draw_sphere(&vert1, 2.0f);
11145                 gr_set_color(255, 0, 255);
11146                 g3_draw_sphere(&vert2, 2.0f);
11147                 g3_draw_line(&vert1, &vert2);
11148         }
11149
11150         // draw from beta to its goal point
11151 /*      for (i=0; i<6; i++) {
11152                 ai_info *aip = &Ai_info[i];
11153                 gr_set_color(0, 0, 255);
11154                 g3_rotate_vertex(&vert1, &Objects[i].pos);
11155                 g3_rotate_vertex(&vert2, &aip->goal_point);
11156                 g3_draw_line(&vert1, &vert2);
11157         } */
11158         
11159
11160         Num_AI_debug_render_stuff = 0;
11161 }
11162
11163 #endif
11164
11165 #ifndef NDEBUG
11166 int     Msg_count_4996 = 0;
11167 #endif
11168
11169 //      --------------------------------------------------------------------------
11170 // Process subobjects of object objnum.
11171 //      Deal with engines disabled.
11172 void process_subobjects(int objnum)
11173 {
11174         model_subsystem *psub;
11175         ship_subsys     *pss;
11176         object  *objp = &Objects[objnum];
11177         ship            *shipp = &Ships[objp->instance];
11178         ai_info *aip = &Ai_info[shipp->ai_index];
11179         ship_info       *sip = &Ship_info[shipp->ship_info_index];
11180
11181         for ( pss = GET_FIRST(&shipp->subsys_list); pss !=END_OF_LIST(&shipp->subsys_list); pss = GET_NEXT(pss) ) {
11182                 psub = pss->system_info;
11183
11184                 // Don't process destroyed objects
11185                 if ( pss->current_hits <= 0.0f ) 
11186                         continue;
11187
11188                 switch (psub->type) {
11189                 case SUBSYSTEM_TURRET:
11190                         if ( psub->turret_num_firing_points > 0 )       {
11191                                 ai_fire_from_turret(shipp, pss, objnum);
11192                         } else {
11193 #ifndef NDEBUG
11194                                 if (!Msg_count_4996) {
11195                                         Warning( LOCATION, "Ship '%s' has turrets with no guns!\nProbably a model problem, so get an artist!", shipp->ship_name );
11196                                         Msg_count_4996++;
11197                                 }
11198 #endif
11199                                 }
11200                         break;
11201
11202                 case SUBSYSTEM_ENGINE:
11203                 case SUBSYSTEM_NAVIGATION:
11204                 case SUBSYSTEM_COMMUNICATION:
11205                 case SUBSYSTEM_WEAPONS:
11206                 case SUBSYSTEM_SENSORS:
11207                 case SUBSYSTEM_UNKNOWN:
11208                         break;
11209
11210                 // next set of subsystems may rotation
11211                 case SUBSYSTEM_RADAR:
11212                 case SUBSYSTEM_SOLAR:
11213 #ifndef MAKE_FS1
11214                 case SUBSYSTEM_GAS_COLLECT:
11215                 case SUBSYSTEM_ACTIVATION:
11216 #endif
11217                         break;
11218                 default:
11219                         Error(LOCATION, "Illegal subsystem type.\n");
11220                 }
11221
11222                 // do solar/radar/gas/activator rotation here
11223                 if ( psub->flags & MSS_FLAG_ROTATES )   {
11224                         if (psub->flags & MSS_FLAG_STEPPED_ROTATE       ) {
11225                                 submodel_stepped_rotate(psub, &pss->submodel_info_1);
11226                         } else {
11227                                 submodel_rotate(psub, &pss->submodel_info_1 );
11228                         }
11229                 }
11230
11231         }
11232
11233         //      Deal with a ship with blown out engines.
11234         if (ship_get_subsystem_strength(shipp, SUBSYSTEM_ENGINE) == 0.0f) {
11235                 if (sip->flags & (SIF_FIGHTER | SIF_BOMBER)) {
11236                         // AL: Only attack forever if not trying to depart to a docking bay.  Need to have this in, since
11237                         //     a ship may get repaired... and it should still try to depart.  Since docking bay departures
11238                         //     are not handled as goals, we don't want to leave the AIM_BAY_DEPART mode.
11239                         if ( aip->mode != AIM_BAY_DEPART ) {
11240                                 ai_attack_object(objp, NULL, 99, NULL);         //      Regardless of current mode, enter attack mode.
11241                                 aip->submode = SM_ATTACK_FOREVER;                               //      Never leave attack submode, don't avoid, evade, etc.
11242                         }
11243                 }
11244         }
11245
11246
11247 }
11248
11249 //      Given an object and the wing it's in, return its index in the wing list.
11250 //      This defines its location in the wing formation.
11251 //      If the object can't be found in the wing, return -1.
11252 //      *objp           object of interest
11253 //      wingnum the wing *objp is in
11254 int get_wing_index(object *objp, int wingnum)
11255 {
11256         wing    *wingp;
11257         int     i;
11258
11259         SDL_assert((wingnum >= 0) && (wingnum < MAX_WINGS));
11260
11261         wingp = &Wings[wingnum];
11262
11263         for (i=wingp->current_count-1; i>=0; i--)
11264                 if ( objp->instance == wingp->ship_index[i] )
11265                         break;
11266
11267         return i;               //      Note, returns -1 if string not found.
11268 }
11269
11270 //      Given a wing, return a pointer to the object of its leader.
11271 //      Asserts if object not found.
11272 //      Currently, the wing leader is defined as the first object in the wing.
11273 //      wingnum         Wing number in Wings array.
11274 //      If wing leader is disabled, swap it with another ship.
11275 object * get_wing_leader(int wingnum)
11276 {
11277         wing            *wingp;
11278         int             ship_num;
11279
11280         SDL_assert((wingnum >= 0) && (wingnum < MAX_WINGS));
11281
11282         wingp = &Wings[wingnum];
11283
11284         SDL_assert(wingp->current_count != 0);                  //      Make sure there is a leader
11285
11286         ship_num = wingp->ship_index[0];
11287
11288         //      If this ship is disabled, try another ship in the wing.
11289         int n = 0;
11290         while (ship_get_subsystem_strength(&Ships[ship_num], SUBSYSTEM_ENGINE) == 0.0f) {
11291                 n++;
11292                 if (n >= wingp->current_count)
11293                         break;  
11294                 ship_num = wingp->ship_index[n];
11295         }
11296
11297         if (( n != 0) && (n != wingp->current_count)) {
11298                 int t = wingp->ship_index[0];
11299                 wingp->ship_index[0] = wingp->ship_index[n];
11300                 wingp->ship_index[n] = t;
11301         }
11302
11303         return &Objects[Ships[ship_num].objnum];
11304 }
11305
11306 #define DEFAULT_WING_X_DELTA            1.0f
11307 #define DEFAULT_WING_Y_DELTA            0.25f
11308 #define DEFAULT_WING_Z_DELTA            0.75f
11309 #define DEFAULT_WING_MAG                (fl_sqrt(DEFAULT_WING_X_DELTA*DEFAULT_WING_X_DELTA + DEFAULT_WING_Y_DELTA*DEFAULT_WING_Y_DELTA + DEFAULT_WING_Z_DELTA*DEFAULT_WING_Z_DELTA))
11310 // next constant is higher that MAX_SHIPS_IN_WINGS to deal with forming on player's wing
11311 #define MAX_FORMATION_ROWS              4
11312
11313 //      Given a position in a wing, return the desired location of the ship relative to the leader
11314 //      *_delta_vec             OUTPUT.  delta vector based on wing_index
11315 //      wing_index              position in wing.
11316 void get_wing_delta(vector *_delta_vec, int wing_index)
11317 {
11318         int     wi0;
11319
11320         SDL_assert(wing_index >= 0);
11321
11322         int     k, row, column;
11323
11324         int bank = wing_index / (MAX_FORMATION_ROWS*(MAX_FORMATION_ROWS+1)/2);
11325         wi0 = wing_index % (MAX_FORMATION_ROWS * (MAX_FORMATION_ROWS+1)/2);
11326
11327         k = 0;
11328         for (row=1; row<MAX_FORMATION_ROWS+1; row++) {
11329                 k += row;
11330                 if (wi0 < k)
11331                         break;
11332         }
11333
11334         row--;
11335         column = wi0 - k + row + 1;
11336
11337         _delta_vec->xyz.x = ((float) column - (float) row/2.0f) * DEFAULT_WING_X_DELTA/DEFAULT_WING_MAG;
11338         _delta_vec->xyz.y = ((float)row + (float)bank*2.25f) * DEFAULT_WING_Y_DELTA/DEFAULT_WING_MAG;
11339         _delta_vec->xyz.z = - ((float)row + 0.5f * (float) bank) * DEFAULT_WING_Z_DELTA/DEFAULT_WING_MAG;
11340 }
11341
11342 //      Compute the largest radius of a ship in a *objp's wing.
11343 float gwlr_1(object *objp, ai_info *aip)
11344 {
11345         int             wingnum = aip->wing;
11346         float           max_radius;
11347         object  *o;
11348         ship_obj        *so;
11349
11350         SDL_assert(wingnum >= 0);
11351
11352         max_radius = objp->radius;
11353
11354         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11355                 o = &Objects[so->objnum];
11356                 if (Ai_info[Ships[o->instance].ai_index].wing == wingnum)
11357                         if (o->radius > max_radius)
11358                                 max_radius = o->radius;
11359         }
11360
11361         return max_radius;
11362 }
11363
11364 //      Compute the largest radius of a ship forming on *objp's wing.
11365 float gwlr_object_1(object *objp, ai_info *aip)
11366 {
11367         float           max_radius;
11368         object  *o;
11369         ship_obj        *so;
11370
11371         max_radius = objp->radius;
11372
11373         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11374                 o = &Objects[so->objnum];
11375                 if (Ai_info[Ships[o->instance].ai_index].goal_objnum == OBJ_INDEX(objp))
11376                         if (o->radius > max_radius)
11377                                 max_radius = o->radius;
11378         }
11379
11380         return max_radius;
11381 }
11382
11383 //      For the wing that *objp is part of, return the largest ship radius in that wing.
11384 float get_wing_largest_radius(object *objp, int formation_object_flag)
11385 {
11386         ship            *shipp;
11387         ai_info *aip;
11388
11389         SDL_assert(objp->type == OBJ_SHIP);
11390         SDL_assert((objp->instance >= 0) && (objp->instance < MAX_OBJECTS));
11391         shipp = &Ships[objp->instance];
11392         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11393         aip = &Ai_info[shipp->ai_index];
11394
11395         if (formation_object_flag) {
11396                 return gwlr_object_1(objp, aip);
11397         } else {
11398                 return gwlr_1(objp, aip);
11399         }
11400
11401 }
11402
11403 float Wing_y_scale = 2.0f;
11404 float Wing_scale = 1.0f;
11405 DCF(wing_y_scale, "")
11406 {
11407         dc_get_arg(ARG_FLOAT);
11408         Wing_y_scale = Dc_arg_float;
11409 }
11410
11411 DCF(wing_scale, "")
11412 {
11413         dc_get_arg(ARG_FLOAT);
11414         Wing_scale = Dc_arg_float;
11415 }
11416
11417 // Given a wing leader and a position in the wing formation, return the desired absolute location to fly to.
11418 //      Returns result in *result_pos.
11419 void get_absolute_wing_pos(vector *result_pos, object *leader_objp, int wing_index, int formation_object_flag)
11420 {
11421         vector  wing_delta, rotated_wing_delta;
11422         float           wing_spread_size;
11423
11424         get_wing_delta(&wing_delta, wing_index);                //      Desired location in leader's reference frame
11425
11426         wing_spread_size = SDL_max(50.0f, 3.0f * get_wing_largest_radius(leader_objp, formation_object_flag) + 15.0f);
11427
11428         // for player obj (1) move ships up 20% (2) scale formation up 20%
11429         if (leader_objp->flags & OF_PLAYER_SHIP) {
11430                 wing_delta.xyz.y *= Wing_y_scale;
11431                 wing_spread_size *= Wing_scale;
11432         }
11433
11434         vm_vec_scale(&wing_delta, wing_spread_size * (1.0f + leader_objp->phys_info.speed/70.0f));
11435
11436         vm_vec_unrotate(&rotated_wing_delta, &wing_delta, &leader_objp->orient);        //      Rotate into leader's reference.
11437
11438         vm_vec_add(result_pos, &leader_objp->pos, &rotated_wing_delta); //      goal_point is absolute 3-space point.
11439 }
11440
11441 #ifndef NDEBUG
11442 int Debug_render_wing_phantoms;
11443
11444 void render_wing_phantoms(object *objp)
11445 {
11446         int             i;
11447         ship            *shipp;
11448         ai_info *aip;
11449         int             wingnum;
11450         int             wing_index;             //      Index in wing struct, defines 3-space location in wing.
11451         vector  goal_point;
11452         
11453         SDL_assert(objp->type == OBJ_SHIP);
11454         SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11455
11456         shipp = &Ships[objp->instance];
11457         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11458
11459         aip = &Ai_info[shipp->ai_index];
11460
11461         wingnum = aip->wing;
11462
11463         if (wingnum == -1)
11464                 return;
11465
11466         wing_index = get_wing_index(objp, wingnum);
11467
11468         //      If this ship is NOT the leader, abort.
11469         if (wing_index != 0)
11470                 return;
11471
11472         for (i=0; i<32; i++)
11473                 if (Debug_render_wing_phantoms & (1 << i)) {
11474                         get_absolute_wing_pos(&goal_point, objp, i, 0);
11475         
11476                         vertex  vert;
11477                         gr_set_color(255, 0, 128);
11478                         g3_rotate_vertex(&vert, &goal_point);
11479                         g3_draw_sphere(&vert, 2.0f);
11480                 }
11481
11482         Debug_render_wing_phantoms = 0;
11483
11484 }
11485
11486 void render_wing_phantoms_all()
11487 {
11488         object  *objp;
11489         ship_obj        *so;
11490
11491         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11492                 ship            *shipp;
11493                 ai_info *aip;
11494                 int             wingnum;
11495                 int             wing_index;             //      Index in wing struct, defines 3-space location in wing.
11496
11497                 objp = &Objects[so->objnum];
11498                 
11499                 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11500                 shipp = &Ships[objp->instance];
11501                 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11502
11503                 aip = &Ai_info[shipp->ai_index];
11504
11505                 wingnum = aip->wing;
11506
11507                 if (wingnum == -1)
11508                         continue;
11509
11510                 wing_index = get_wing_index(objp, wingnum);
11511
11512                 //      If this ship is NOT the leader, abort.
11513                 if (wing_index != 0)
11514                         continue;
11515                 
11516                 render_wing_phantoms(objp);
11517
11518                 return;
11519         }
11520 }
11521
11522 #endif
11523
11524 //      Hook from goals code to AI.
11525 //      Force a wing to fly in formation.
11526 //      Sets AIF_FORMATION bit in ai_flags.
11527 //      wingnum         Wing to force to fly in formation
11528 void ai_fly_in_formation(int wingnum)
11529 {
11530         object  *objp;
11531         ship            *shipp;
11532         ship_obj        *so;
11533
11534         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11535                 objp = &Objects[so->objnum];
11536                 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11537
11538                 shipp = &Ships[objp->instance];
11539                 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11540
11541                 if (Ai_info[shipp->ai_index].wing == wingnum) {
11542                         Ai_info[shipp->ai_index].ai_flags |= AIF_FORMATION_WING;
11543                         Ai_info[shipp->ai_index].ai_flags &= ~AIF_FORMATION_OBJECT;
11544                 }
11545         }
11546 }
11547
11548 //      Hook from goals code to AI.
11549 //      Force a wing to abandon formation flying.
11550 //      Clears AIF_FORMATION bit in ai_flags.
11551 //      wingnum         Wing to force to fly in formation
11552 void ai_disband_formation(int wingnum)
11553 {
11554         object  *objp;
11555         ship            *shipp;
11556         ship_obj        *so;
11557
11558         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11559                 objp = &Objects[so->objnum];
11560                 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11561
11562                 shipp = &Ships[objp->instance];
11563                 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11564
11565                 if (Ai_info[shipp->ai_index].wing == wingnum) {
11566                         Ai_info[shipp->ai_index].ai_flags &= ~AIF_FORMATION_WING;
11567                 }
11568         }
11569 }
11570
11571 float   Leader_chaos = 0.0f;
11572 int Chaos_frame = -1;
11573
11574 //      Return true if objp is flying in an erratic manner
11575 //      Only true if objp is a player
11576 int formation_is_leader_chaotic(object *objp)
11577 {
11578         if (Game_mode & GM_MULTIPLAYER)
11579                 return 0;
11580
11581         if (objp != Player_obj)
11582                 return 0;
11583
11584         if (Framecount != Chaos_frame) {
11585                 float   speed_scale;
11586                 float   fdot, udot;
11587
11588                 speed_scale = 3.0f + objp->phys_info.speed * 0.1f;
11589
11590                 fdot = 5.0f * (1.0f - vm_vec_dot(&objp->orient.v.fvec, &objp->last_orient.v.fvec)) * flFrametime;
11591                 udot = 8.0f * (1.0f - vm_vec_dot(&objp->orient.v.uvec, &objp->last_orient.v.uvec)) * flFrametime;
11592
11593                 Leader_chaos += fdot * speed_scale + udot * speed_scale;
11594
11595                 Leader_chaos *= (1.0f - flFrametime*0.2f);
11596
11597                 if (Leader_chaos < 0.0f)
11598                         Leader_chaos = 0.0f;
11599                 else if (Leader_chaos > 1.7f)
11600                         Leader_chaos = 1.7f;
11601
11602                 //nprintf(("AI", "Frame %i: chaos = %7.4f\n", Framecount, Leader_chaos));
11603
11604                 Chaos_frame = Framecount;
11605         }
11606
11607         return (Leader_chaos > 1.0f);
11608 }
11609
11610 // Fly in formation.
11611 //      Make Pl_objp assume its proper place in formation.
11612 //      If the leader of the wing is doing something stupid, like fighting a battle,
11613 //      then the poor sap wingmates will be in for a "world of hurt"
11614 //      Return TRUE if we need to process this object's normal mode
11615 int ai_formation()
11616 {
11617         object  *leader_objp;
11618         ship            *shipp;
11619         ai_info *aip, *laip;
11620         int             wingnum;
11621         int             wing_index;             //      Index in wing struct, defines 3-space location in wing.
11622         int             player_wing;    // index of the players wingnum
11623         vector  goal_point, future_goal_point_5, future_goal_point_2, future_goal_point_x, future_goal_point_1000x, vec_to_goal, dir_to_goal;
11624         float           dot_to_goal, dist_to_goal, leader_speed;
11625
11626         SDL_assert(Pl_objp->type == OBJ_SHIP);
11627         SDL_assert((Pl_objp->instance >= 0) && (Pl_objp->instance < MAX_SHIPS));
11628
11629         shipp = &Ships[Pl_objp->instance];
11630
11631         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11632
11633         aip = &Ai_info[shipp->ai_index];
11634
11635         SDL_assert((aip->ai_flags & AIF_FORMATION) != AIF_FORMATION);   //      Make sure not both types of formation flying in effect.
11636
11637         //      Determine which kind of formation flying.
11638         //      If tracking an object, not in waypoint mode:
11639         if (aip->ai_flags & AIF_FORMATION_OBJECT) {
11640                 if ((aip->goal_objnum < 0) || (aip->goal_objnum >= MAX_OBJECTS)) {
11641                         aip->ai_flags &= ~AIF_FORMATION_OBJECT;
11642                         return 1;
11643                 }
11644                 
11645                 wing_index = ai_formation_object_get_slotnum(aip->goal_objnum, Pl_objp);
11646                 leader_objp = &Objects[aip->goal_objnum];
11647         } else {        //      Formation flying in waypoint mode.
11648                 SDL_assert(aip->ai_flags & AIF_FORMATION_WING);
11649                 if (aip->mode != AIM_WAYPOINTS) {
11650                         aip->ai_flags &= ~AIF_FORMATION_WING;
11651                         return 1;
11652                 }
11653
11654                 wingnum = aip->wing;
11655
11656                 if (wingnum == -1)
11657                         return 1;
11658
11659                 // disable formation flying for any ship in the players wing
11660                 player_wing = Ships[Player_obj->instance].wingnum;
11661                 if ( (player_wing != -1) && (wingnum == player_wing) )
11662                         return 1;
11663
11664                 wing_index = get_wing_index(Pl_objp, wingnum);
11665
11666                 leader_objp = get_wing_leader(wingnum);
11667
11668         }
11669
11670         //      If docked with a ship in this wing, only the more massive one actually flies in formation.
11671         if (aip->dock_objnum != -1) {
11672                 object  *other_objp = &Objects[aip->dock_objnum];
11673                 ai_info *other_aip = &Ai_info[Ships[other_objp->instance].ai_index];
11674
11675                 if (aip->wing == other_aip->wing) {
11676                         if (Pl_objp->phys_info.mass < other_objp->phys_info.mass)
11677                                 return 0;
11678                         else if (Pl_objp->phys_info.mass == other_objp->phys_info.mass) {
11679                                 if (Pl_objp->signature < other_objp->signature)
11680                                         return 0;
11681                         }
11682                 }
11683         }
11684
11685         SDL_assert(leader_objp != NULL);
11686         laip = &Ai_info[Ships[leader_objp->instance].ai_index];
11687
11688         //      Make sure we're really in this wing.
11689         if (wing_index == -1)
11690                 return 1;
11691
11692         //      If this ship is the leader, abort, as he doesn't have to follow anyone.
11693         if (wing_index == 0) {
11694                 // nprintf(("AI", "Hmm, wing leader %s in ai_formation for no good reason.\n", shipp->ship_name));
11695                 return 1;
11696         }
11697
11698         if (aip->mode == AIM_WAYPOINTS) {
11699                 aip->wp_list = laip->wp_list;
11700                 if (laip->wp_index < Waypoint_lists[laip->wp_list].count)
11701                         aip->wp_index = laip->wp_index;
11702                 else
11703                         aip->wp_index = Waypoint_lists[laip->wp_list].count - 1;
11704                 aip->wp_flags = laip->wp_flags;
11705                 aip->wp_dir = laip->wp_dir;
11706         }
11707
11708         #ifndef NDEBUG
11709         Debug_render_wing_phantoms |= (1 << wing_index);
11710         #endif
11711
11712         leader_speed = leader_objp->phys_info.speed;
11713         vector leader_vec = leader_objp->phys_info.vel;
11714
11715         get_absolute_wing_pos(&goal_point, leader_objp, wing_index, aip->ai_flags & AIF_FORMATION_OBJECT);
11716         vm_vec_scale_add(&future_goal_point_5, &goal_point, &leader_vec, 10.0f);
11717         vm_vec_scale_add(&future_goal_point_2, &goal_point, &leader_vec, 5.0f);
11718         vm_vec_scale_add(&future_goal_point_x, &goal_point, &leader_objp->orient.v.fvec, 10.0f);        //      used when very close to destination
11719         vm_vec_scale_add(&future_goal_point_1000x, &goal_point, &leader_objp->orient.v.fvec, 1000.0f);  //      used when very close to destination
11720
11721         //      Now, get information telling this object how to turn and accelerate to get to its
11722         //      desired location.
11723         vm_vec_sub(&vec_to_goal, &goal_point, &Pl_objp->pos);
11724         if ( vm_vec_mag_quick(&vec_to_goal) < AICODE_SMALL_MAGNITUDE )
11725                 vec_to_goal.xyz.x += 0.1f;
11726
11727         vm_vec_copy_normalize(&dir_to_goal, &vec_to_goal);
11728         //dot_to_goal = vm_vec_dot(&dir_to_goal, &leader_objp->orient.v.fvec);
11729         dot_to_goal = vm_vec_dot(&dir_to_goal, &Pl_objp->orient.v.fvec);
11730         dist_to_goal = vm_vec_dist_quick(&Pl_objp->pos, &goal_point);
11731         float   dist_to_goal_2 = vm_vec_dist_quick(&Pl_objp->pos, &future_goal_point_2);
11732
11733         // nprintf(("AI", "dot = %7.3f, dist = %8.3f, speed = %7.3f, leader speed = %7.3f\n", dot_to_goal, dist_to_goal, Pl_objp->phys_info.speed, leader_objp->phys_info.speed));
11734
11735         int     chaotic_leader = 0;
11736
11737         chaotic_leader = formation_is_leader_chaotic(leader_objp);      //      Set to 1 if leader is player and flying erratically.  Causes ships to not aggressively pursue formation location.
11738
11739         if (dist_to_goal > 500.0f) {
11740                 turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
11741                 accelerate_ship(aip, 1.0f);
11742         } else if (dist_to_goal > 200.0f) {
11743                 if (dot_to_goal > -0.5f) {
11744                         turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
11745                         float range_speed = shipp->current_max_speed - leader_speed;
11746                         if (range_speed > 0.0f)
11747                                 set_accel_for_target_speed(Pl_objp, leader_speed + range_speed * (dist_to_goal+100.0f)/500.0f);
11748                         else
11749                                 set_accel_for_target_speed(Pl_objp, shipp->current_max_speed);
11750                 } else {
11751                         turn_towards_point(Pl_objp, &future_goal_point_5, NULL, 0.0f);
11752                         if (leader_speed > 10.0f)
11753                                 set_accel_for_target_speed(Pl_objp, leader_speed *(1.0f + dot_to_goal));
11754                         else
11755                                 set_accel_for_target_speed(Pl_objp, 10.0f);
11756                 }
11757         } else {
11758                 vector  v2f2;
11759                 float   dot_to_f2;
11760
11761                 vm_vec_normalized_dir(&v2f2, &future_goal_point_2, &Pl_objp->pos);
11762                 dot_to_f2 = vm_vec_dot(&v2f2, &Pl_objp->orient.v.fvec);
11763
11764                 //      Leader flying like a maniac.  Don't try hard to form on wing.
11765                 if (chaotic_leader) {
11766                         turn_towards_point(Pl_objp, &future_goal_point_2, NULL, 0.0f);
11767                         set_accel_for_target_speed(Pl_objp, SDL_min(leader_speed*0.8f, 20.0f));
11768                 } else if (dist_to_goal > 75.0f) {
11769                         turn_towards_point(Pl_objp, &future_goal_point_2, NULL, 0.0f);
11770                         float   delta_speed;
11771                         float range_speed = shipp->current_max_speed - leader_speed;
11772                         if (range_speed > 0.0f)
11773                                 delta_speed = dist_to_goal_2/500.0f * range_speed;
11774                         else
11775                                 delta_speed = shipp->current_max_speed - leader_speed;
11776                         if (dot_to_goal < 0.0f) {
11777                                 delta_speed = -delta_speed;
11778                                 if (-delta_speed > leader_speed/2)
11779                                         delta_speed = -leader_speed/2;
11780                         }
11781
11782                         if (leader_speed < 5.0f)
11783                                 if (delta_speed < 5.0f)
11784                                         delta_speed = 5.0f;
11785
11786                         float scale = dot_to_f2;
11787                         if (scale < 0.1f)
11788                                 scale = 0.0f;
11789                         else
11790                                 scale *= scale;
11791
11792                         set_accel_for_target_speed(Pl_objp, scale * (leader_speed + delta_speed));
11793                 } else {
11794                         //nprintf(("AI", "Dot = %7.3f\n", dot_to_goal));
11795
11796                         if (leader_speed < 5.0f) {
11797                                 //      Leader very slow.  If not close to goal point, get very close.  Note, keep trying to get close unless
11798                                 //      moving very slowly, else momentum can carry far away from goal.
11799
11800                                 if ((dist_to_goal > 10.0f) || ((Pl_objp->phys_info.speed > leader_speed + 2.5f) && (dot_to_goal > 0.5f))) {
11801                                         //nprintf(("MK", "(1) "));
11802                                         turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
11803                                         set_accel_for_target_speed(Pl_objp, leader_speed + dist_to_goal/10.0f);
11804                                 } else {
11805                                         if (Pl_objp->phys_info.speed < 0.5f) {
11806                                                 //nprintf(("MK", "(2) "));
11807                                                 turn_towards_point(Pl_objp, &future_goal_point_1000x, NULL, 0.0f);
11808                                         } else {
11809                                                 //nprintf(("MK", "(3) "));
11810                                         }
11811                                         set_accel_for_target_speed(Pl_objp, leader_speed);
11812                                 }
11813                                 //nprintf(("MK", "dist: %7.3f, dot: %6.3f, speed: %7.3f\n", dist_to_goal, dot_to_goal, Pl_objp->phys_info.speed));
11814                         } else if (dist_to_goal > 10.0f) {
11815                                 float   dv;
11816
11817                                 //future_goal_point_2;
11818
11819                                 turn_towards_point(Pl_objp, &future_goal_point_2, NULL, 0.0f);
11820
11821                                 if (dist_to_goal > 25.0f) {
11822                                         if (dot_to_goal < 0.3f)
11823                                                 dv = -0.1f;
11824                                         else
11825                                                 dv = dot_to_goal - 0.2f;
11826
11827                                         set_accel_for_target_speed(Pl_objp, leader_speed + dist_to_goal/5.0f * dv);
11828                                 } else {
11829                                         set_accel_for_target_speed(Pl_objp, leader_speed + 1.5f * dot_to_goal - 1.0f);
11830                                 }
11831                         } else {
11832                                 if (Pl_objp->phys_info.speed < 0.1f)
11833                                         turn_towards_point(Pl_objp, &future_goal_point_1000x, NULL, 0.0f);
11834                                 else
11835                                         turn_towards_point(Pl_objp, &future_goal_point_x, NULL, 0.0f);
11836                                 set_accel_for_target_speed(Pl_objp, 0.0f);
11837                         }
11838                 }
11839
11840         }
11841
11842         //      See how different this ship's bank is relative to wing leader
11843         float   up_dot = vm_vec_dot(&leader_objp->orient.v.uvec, &Pl_objp->orient.v.uvec);
11844         if (up_dot < 0.996f) {
11845                 vector  w_out;
11846                 matrix  new_orient;
11847                 vector  angular_accel;
11848
11849                 vm_vec_copy_scale(&angular_accel, &Pl_objp->phys_info.max_rotvel, 0.2f);
11850                 vm_matrix_interpolate(&leader_objp->orient, &Pl_objp->orient, &Pl_objp->phys_info.rotvel, flFrametime, &new_orient, &w_out, &Pl_objp->phys_info.max_rotvel, &angular_accel, 1);
11851
11852         //      nprintf(("AI", "Frame %d Bashing formation orient.  Dot was %6.3f, becomes %6.3f\n", Framecount, up_dot, vm_vec_dot(&leader_objp->orient.v.uvec, &new_orient.v.uvec)));
11853                 Pl_objp->orient = new_orient;
11854                 Pl_objp->phys_info.rotvel = w_out;
11855         //      Pl_objp->phys_info.desired_rotvel = w_out;
11856         } else {
11857                 Pl_objp->phys_info.rotvel.xyz.z = 0.0f;
11858         }
11859
11860         return 0;
11861 }
11862
11863 //      Return index of object repairing object objnum.
11864 int find_repairing_objnum(int objnum)
11865 {
11866         object          *objp;
11867         ship                    *shipp;
11868         ship_info       *sip;
11869         ship_obj                *so;
11870
11871         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11872                 objp = &Objects[so->objnum];
11873
11874                 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11875
11876                 shipp = &Ships[objp->instance];
11877                 sip = &Ship_info[shipp->ship_info_index];
11878
11879                 if (sip->flags & SIF_SUPPORT) {
11880                         ai_info *aip;
11881
11882                         aip = &Ai_info[shipp->ai_index];
11883
11884                         if (aip->goal_objnum == objnum) {
11885                                 return objp-Objects;
11886                         }
11887                 }
11888         }
11889
11890         return -1;
11891 }
11892
11893 //      If object *objp is being repaired, deal with it!
11894 void ai_do_repair_frame(object *objp, ai_info *aip, float frametime)
11895 {
11896         if (Ships[objp->instance].team == TEAM_TRAITOR) {
11897                 ai_abort_rearm_request(objp);
11898                 return;
11899         }
11900
11901         if (aip->ai_flags & (AIF_BEING_REPAIRED | AIF_AWAITING_REPAIR)) {
11902                 int     dock_objnum;
11903                 ai_info *repair_aip;
11904
11905                 dock_objnum = aip->dock_objnum; // find_repairing_objnum(objp-Objects);
11906                 //SDL_assert(dock_objnum != -1);
11907                 if (dock_objnum == -1)
11908                         return;
11909                 if (Objects[dock_objnum].signature != aip->dock_signature) {
11910                         Int3();         //      Curious -- object numbers match, but signatures do not.
11911                                                         //      Must mean original repair ship died and was replaced by current ship.
11912                         return;
11913                 }
11914         
11915                 repair_aip = &Ai_info[Ships[Objects[dock_objnum].instance].ai_index];
11916                 //SDL_assert(repair_aip->mode == AIM_DOCK);
11917
11918                 if (aip->ai_flags & AIF_BEING_REPAIRED) {
11919                         // SDL_assert(repair_aip->submode == AIS_DOCK_4);
11920
11921                         //      Wait awhile into the mode to synchronize with sound effect.
11922                         if (Missiontime - repair_aip->submode_start_time > REARM_SOUND_DELAY) {
11923                                 int repaired;
11924
11925                                 repaired = ship_do_rearm_frame( objp, frametime );              // hook to do missile rearming
11926
11927                                 //      See if fully repaired.  If so, cause process to stop.
11928                                 if ( repaired && (repair_aip->submode == AIS_DOCK_4)) {
11929
11930                                         repair_aip->submode = AIS_UNDOCK_0;
11931                                         repair_aip->submode_start_time = Missiontime;
11932
11933                                         // if repairing player object -- tell him done with repair
11934                                         if ( !MULTIPLAYER_CLIENT ){
11935                                                 ai_do_objects_repairing_stuff( objp, &Objects[dock_objnum], REPAIR_INFO_COMPLETE );
11936                                         }
11937                                 }
11938                         }
11939                 } else if (aip->ai_flags & AIF_AWAITING_REPAIR) {
11940                         //      If this ship has been awaiting repair for 90+ seconds, abort.
11941                         if ( !MULTIPLAYER_CLIENT ) {
11942                                 if ((Game_mode & GM_MULTIPLAYER) || (objp != Player_obj)) {
11943                                         if ((repair_aip->goal_objnum == OBJ_INDEX(objp)) && (timestamp_elapsed(aip->abort_rearm_timestamp))) {
11944                                                 ai_abort_rearm_request(objp);
11945                                                 aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP);
11946                                         }
11947                                 }
11948                         }
11949                 }
11950         } else {
11951                 // AL 11-24-97: If this is the player ship, ensure the repair sound isn't playing.  We need to
11952                 //              do this check, since this is a looping sound, and may continue on if rearm/repair
11953                 //              finishes abnormally once sound begins looping.
11954                 if ( objp == Player_obj ) {
11955                         player_stop_repair_sound();
11956                 }
11957         }
11958 }
11959
11960 //      Shell around dock_orient_and_approach to detect whether dock process should be aborted.
11961 //      obj1 is the ship performing the repair.
11962 //      obj2 is the ship being repaired.
11963 void call_doa(object *obj1, object *obj2, ship_info *sip1)
11964 {
11965         if (sip1->flags & SIF_SUPPORT) {
11966                 if (obj2->phys_info.speed > MAX_REPAIR_SPEED) {
11967
11968                         // call the ai_abort rearm request code
11969                         ai_abort_rearm_request( obj2 );
11970                 } else
11971                         dock_orient_and_approach(obj1, obj2, DOA_DOCK_STAY);
11972         } else {
11973                 if (Ship_info[Ships[obj1->instance].ship_info_index].flags & SIF_CARGO)
11974                         dock_orient_and_approach(obj1, obj2, DOA_DOCK_STAY);
11975                 else if (Ship_info[Ships[obj2->instance].ship_info_index].flags & SIF_CARGO)
11976                         dock_orient_and_approach(obj2, obj1, DOA_DOCK_STAY);
11977                 else {
11978                         //mprintf(("Warning: Not sure, but making %s [%s] move to stay docked with %s [%s]\n",
11979                         //      Ships[obj1->instance].ship_name, Ship_info[Ships[obj1->instance].ship_info_index].name, Ships[obj2->instance].ship_name, Ship_info[Ships[obj2->instance].ship_info_index].name));
11980                         dock_orient_and_approach(obj1, obj2, DOA_DOCK_STAY);
11981
11982                 }
11983         }
11984
11985 }
11986
11987 //      Maybe launch a countermeasure.
11988 //      Also, detect a supposed homing missile that no longer exists.
11989 void ai_maybe_launch_cmeasure(object *objp, ai_info *aip)
11990 {
11991         float                   dist;
11992         ship_info       *sip;
11993         ship                    *shipp;
11994
11995         shipp = &Ships[objp->instance];
11996         sip = &Ship_info[shipp->ship_info_index];
11997
11998         if (!(sip->flags & (SIF_SMALL_SHIP | SIF_TRANSPORT)))
11999                 return;
12000
12001         if (!shipp->cmeasure_count)
12002                 return;
12003
12004         if ( !timestamp_elapsed(shipp->cmeasure_fire_stamp) )
12005                 return;
12006
12007         //      If not on player's team and Skill_level + ai_class is low, never fire a countermeasure.  The ship is too dumb.
12008         if (shipp->team != Player_ship->team) {
12009                 if (Game_skill_level + aip->ai_class < 4){
12010                         return;
12011                 }
12012         }
12013
12014         if ((aip->nearest_locked_object != -1) && (Objects[aip->nearest_locked_object].type == OBJ_WEAPON)) {
12015                 object  *weapon_objp;
12016
12017                 weapon_objp = &Objects[aip->nearest_locked_object];
12018
12019                 if ((dist = vm_vec_dist_quick(&objp->pos, &weapon_objp->pos)) < weapon_objp->phys_info.speed*2.0f) {
12020         
12021                         aip->nearest_locked_distance = dist;
12022                         //      Verify that this object is really homing on us.
12023
12024                         float   fire_chance;
12025
12026                         //      For ships on player's team, have constant, average chance to fire.
12027                         //      For enemies, increasing chance with higher skill level.
12028                         if (shipp->team == Player_ship->team)
12029                                 fire_chance = Cmeasure_fire_chance[NUM_SKILL_LEVELS/2];
12030                         else
12031                                 fire_chance = Cmeasure_fire_chance[Game_skill_level];
12032
12033                         //      Decrease chance to fire at lower ai class.
12034                         fire_chance *= (float) aip->ai_class/Num_ai_classes;
12035
12036                         float r = frand();
12037                         if (fire_chance < r) {
12038                                 //nprintf(("AI", "Not firing countermeasure due to skill level: %7.3f < %7.3f\n", fire_chance, r));
12039                                 shipp->cmeasure_fire_stamp = timestamp(CMEASURE_WAIT + (int) (fire_chance*2000));               //      Wait 1/2 second (CMEASURE_WAIT) + additional delay to decrease chance of firing very soon.
12040                                 return;
12041                         }
12042
12043                         if (weapon_objp->type == OBJ_WEAPON) {
12044                                 if (weapon_objp->instance >= 0) {
12045                                         //nprintf(("AI", "Firing countermeasure at time t=%7.3f\n", f2fl(Missiontime)));
12046                                         ship_launch_countermeasure(objp);
12047                                         shipp->cmeasure_fire_stamp = timestamp(2*CMEASURE_WAIT);
12048                                         return;
12049                                 }
12050                         }
12051         
12052                 }
12053         }
12054
12055         return;
12056 }
12057
12058 //      --------------------------------------------------------------------------
12059 void ai_preprocess_ignore_objnum(object *objp, ai_info *aip)
12060 {
12061 //      if (aip->ignore_objnum == UNUSED_OBJNUM)
12062 //              return;
12063
12064         if (aip->ai_flags & AIF_TEMPORARY_IGNORE) {
12065                 if (timestamp_elapsed(aip->ignore_expire_timestamp)) {
12066                         aip->ignore_objnum = UNUSED_OBJNUM;
12067                 }
12068         }
12069
12070         if (is_ignore_object(aip, aip->goal_objnum)) {
12071                 aip->goal_objnum = -1;
12072                 // AL 12-11-97: If in STRAFE mode, we need to ensure that target_objnum is also
12073                 //              set to -1
12074                 if ( aip->mode == AIM_STRAFE ) {
12075                         aip->target_objnum = -1;
12076                 }
12077         }
12078
12079         if (is_ignore_object(aip, aip->target_objnum))
12080                 aip->target_objnum = -1;
12081 }
12082
12083 /*
12084 void ai_safety_circle_spot()
12085 {
12086         vector  goal_point;
12087         ship_info       *sip;
12088
12089         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
12090
12091         goal_point = Ai_info[Ships[Pl_objp->instance].ai_index].goal_point;
12092         turn_towards_tangent(Pl_objp, &goal_point, 50.0f);
12093
12094         set_accel_for_target_speed(Pl_objp, sip->max_speed/4.0f);
12095
12096 //      float dist = vm_vec_dist_quick(&goal_point, &Pl_objp->pos);
12097 //      nprintf(("AI", "Ship %s circling %7.3f %7.3f %7.3f.  Distance = %7.3f\n", Ships[Pl_objp->instance].ship_name, goal_point.xyz.x, goal_point.xyz.y, goal_point.xyz.z, dist));
12098
12099 }
12100 */
12101
12102 #define CHASE_CIRCLE_DIST               100.0f
12103
12104 void ai_chase_circle(object *objp)
12105 {
12106         float           dist_to_goal;
12107         float           target_speed;
12108         vector  goal_point;
12109         ship_info       *sip;
12110         ai_info         *aip;
12111
12112         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
12113
12114         target_speed = sip->max_speed/4.0f;
12115         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
12116
12117         SDL_assert(vm_vec_mag(&aip->goal_point) >= 0.0f);               //      Supposedly detects bogus vector
12118
12119         goal_point = aip->goal_point;
12120
12121         if (aip->ignore_objnum == UNUSED_OBJNUM) {
12122                 dist_to_goal = vm_vec_dist_quick(&aip->goal_point, &objp->pos);
12123
12124                 if (dist_to_goal > 2*CHASE_CIRCLE_DIST) {
12125                         vector  vec_to_goal;
12126                         //      Too far from circle goal, create a new goal point.
12127                         vm_vec_normalized_dir(&vec_to_goal, &aip->goal_point, &objp->pos);
12128                         vm_vec_scale_add(&aip->goal_point, &objp->pos, &vec_to_goal, CHASE_CIRCLE_DIST);
12129                 }
12130
12131                 goal_point = aip->goal_point;
12132         } else if (is_ignore_object(aip, aip->ignore_objnum)) {
12133                 object  *ignore_objp = &Objects[aip->ignore_objnum];
12134
12135                 vector  tvec1;
12136                 float           dist;
12137
12138                 dist = vm_vec_normalized_dir(&tvec1, &Pl_objp->pos, &ignore_objp->pos);
12139
12140                 if (dist < ignore_objp->radius*2 + 1500.0f) {
12141                         vm_vec_scale_add(&goal_point, &Pl_objp->pos, &tvec1, ignore_objp->radius*2 + 1400.0f);
12142                         if (dist < ignore_objp->radius*2 + 1300.0f)
12143                                 target_speed = sip->max_speed * (1.25f - dist/(ignore_objp->radius*2 + 1500.0f));
12144                 }
12145         }
12146
12147         SDL_assert(vm_vec_mag(&aip->goal_point) >= 0.0f);               //      Supposedly detects bogus vector
12148
12149         turn_towards_tangent(Pl_objp, &goal_point, 10*objp->radius + 200.0f);
12150
12151         set_accel_for_target_speed(Pl_objp, target_speed);
12152
12153 }
12154
12155 #define SHIELD_BALANCE_RATE     0.2f            //      0.1f -> takes 10 seconds to equalize shield.
12156
12157 //      Transfer shield energy to most recently hit section from others.
12158 void ai_transfer_shield(object *objp, int quadrant_num)
12159 {
12160         int     i;
12161         float   transfer_amount;
12162         float   transfer_delta;
12163         ship_info       *sip;
12164         float   max_quadrant_strength;
12165
12166         sip = &Ship_info[Ships[objp->instance].ship_info_index];
12167         max_quadrant_strength = sip->shields/MAX_SHIELD_SECTIONS;
12168
12169         transfer_amount = 0.0f;
12170         transfer_delta = (SHIELD_BALANCE_RATE/2) * max_quadrant_strength;
12171
12172         if (objp->shields[quadrant_num] + (MAX_SHIELD_SECTIONS-1)*transfer_delta > max_quadrant_strength)
12173                 transfer_delta = (max_quadrant_strength - objp->shields[quadrant_num])/(MAX_SHIELD_SECTIONS-1);
12174
12175         for (i=0; i<MAX_SHIELD_SECTIONS; i++)
12176                 if (i != quadrant_num) {
12177                         if (objp->shields[i] >= transfer_delta) {
12178                                 objp->shields[i] -= transfer_delta;
12179                                 transfer_amount += transfer_delta;
12180                         } else {
12181                                 transfer_amount += objp->shields[i];
12182                                 objp->shields[i] = 0.0f;
12183                         }
12184                 }
12185
12186         objp->shields[quadrant_num] += transfer_amount;
12187 }
12188
12189 void ai_balance_shield(object *objp)
12190 {
12191         int     i;
12192         float   shield_strength_avg;
12193         float   delta;
12194
12195
12196         shield_strength_avg = get_shield_strength(objp)/MAX_SHIELD_SECTIONS;
12197
12198         delta = SHIELD_BALANCE_RATE * shield_strength_avg;
12199
12200         for (i=0; i<MAX_SHIELD_SECTIONS; i++)
12201                 if (objp->shields[i] < shield_strength_avg) {
12202                         add_shield_strength(objp, delta);
12203                         if (objp->shields[i] > shield_strength_avg)
12204                                 objp->shields[i] = shield_strength_avg;
12205                 } else {
12206                         add_shield_strength(objp, -delta);
12207                         if (objp->shields[i] < shield_strength_avg)
12208                                 objp->shields[i] = shield_strength_avg;
12209                 }
12210 }
12211
12212 //      Manage the shield for this ship.
12213 //      Try to max out the side that was most recently hit.
12214 void ai_manage_shield(object *objp, ai_info *aip)
12215 {
12216         ship_info *sip;
12217
12218         sip = &Ship_info[Ships[objp->instance].ship_info_index];
12219
12220         if (timestamp_elapsed(aip->shield_manage_timestamp)) {
12221                 float           delay;
12222
12223                 //      Scale time until next manage shield based on Skill_level.
12224                 //      Ships on player's team are treated as if Skill_level is average.
12225                 if (Ships[objp->instance].team != Player_ship->team){
12226                         delay = Shield_manage_delays[Game_skill_level];
12227                 } else {
12228                         delay = Shield_manage_delays[NUM_SKILL_LEVELS/2];
12229                 }
12230
12231                 //      Scale between 1x and 3x based on ai_class
12232                 delay = delay + delay * (float) (3*(Num_ai_classes - aip->ai_class - 1) / (Num_ai_classes - 1));
12233                 aip->shield_manage_timestamp = timestamp((int) (delay * 1000.0f));
12234
12235                 if (sip->flags & SIF_SMALL_SHIP) {
12236                         if (Missiontime - aip->last_hit_time < F1_0*10)
12237                                 ai_transfer_shield(objp, aip->last_hit_quadrant);
12238                         else
12239                                 ai_balance_shield(objp);
12240                 }
12241
12242                 // nprintf(("AI", "Time: %7.3f Next: %7.3f, Shields: %7.3f %7.3f %7.3f %7.3f\n", f2fl(Missiontime), f2fl(Missiontime) + delay, objp->shields[0], objp->shields[1], objp->shields[2], objp->shields[3]));
12243         }
12244 }
12245
12246 //      See if object *objp should evade an incoming missile.
12247 //      *aip is the ai_info pointer within *objp.
12248 void ai_maybe_evade_locked_missile(object *objp, ai_info *aip)
12249 {
12250         ship                    *shipp;
12251
12252         shipp = &Ships[objp->instance];
12253
12254         //      Only small ships evade an incoming missile.  Why would a capital ship try to swerve?
12255         if (!(Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
12256                 return;
12257         }
12258
12259         if (aip->ai_flags & (AIF_NO_DYNAMIC | AIF_KAMIKAZE)) {  //      If not allowed to pursue dynamic objectives, don't evade.  Dumb?  Maybe change. -- MK, 3/15/98
12260                 return;
12261         }
12262
12263         if (aip->nearest_locked_object != -1) {
12264                 object  *missile_objp;
12265
12266                 missile_objp = &Objects[aip->nearest_locked_object];
12267
12268                 if (Weapons[missile_objp->instance].homing_object != objp) {
12269                         //nprintf(("AI", "\nMissile lost home!"));
12270                         aip->nearest_locked_object = -1;
12271                         return;
12272                 }
12273
12274                 if ((missile_objp->type == OBJ_WEAPON) && (Weapon_info[Weapons[missile_objp->instance].weapon_info_index].wi_flags & WIF_HOMING)) {
12275                         float dist = vm_vec_dist_quick(&missile_objp->pos, &objp->pos);
12276                         float dist2 = 4.0f  * vm_vec_mag_quick(&missile_objp->phys_info.vel);                   
12277                         if (dist < dist2) {
12278                                 switch (aip->mode) {
12279                                 //      If in AIM_STRAFE mode, don't evade if parent of weapon is targeted ship.
12280                                 case AIM_STRAFE:
12281                                         if ((missile_objp->parent != -1) && (missile_objp->parent == aip->target_objnum)) {
12282                                                 ;
12283                                         } else {
12284                                                 ;               //      Alan -- If you want to handle incoming weapons from someone other than the ship
12285                                                                 //      the strafing ship is attacking, do it here.
12286                                         }
12287                                         break;
12288                                 case AIM_CHASE:
12289                                         //      Don't always go into evade weapon mode.  Usually, a countermeasure gets launched.
12290                                         // If low on countermeasures, more likely to try to evade.  If 8+, never evade due to low cmeasures.
12291                                         if (((((Missiontime >> 18) ^ OBJ_INDEX(objp)) & 3) == 0) || 
12292                                                 (objp->phys_info.speed < 40.0f) ||
12293                                                 (frand() < 1.0f - (float) shipp->cmeasure_count/8.0f)) {
12294                                                 if (aip->submode != SM_ATTACK_FOREVER) {        //      SM_ATTACK_FOREVER means engines blown.
12295                                                         aip->submode = SM_EVADE_WEAPON;
12296                                                         aip->submode_start_time = Missiontime;
12297                                                 }
12298                                         }
12299                                         break;
12300                                 case AIM_DOCK:  //      Ships in dock mode can evade iif they are not currently repairing or docked.
12301                                         if (aip->ai_flags & (AIF_REPAIRING | AIF_DOCKED))
12302                                                 break;
12303                                 case AIM_GUARD:
12304                                         //      If in guard mode and far away from guard object, don't pursue guy that hit me.
12305                                         if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
12306                                                 if (vm_vec_dist_quick(&objp->pos, &Objects[aip->guard_objnum].pos) > 500.0f) {
12307                                                         return;
12308                                                 }
12309                                         }
12310                                 case AIM_EVADE:
12311                                 case AIM_GET_BEHIND:
12312                                 case AIM_STAY_NEAR:
12313                                 case AIM_STILL:
12314                                 case AIM_AVOID:
12315                                 case AIM_WAYPOINTS:
12316                                 case AIM_NONE:
12317                                 case AIM_BIGSHIP:
12318                                 case AIM_PATH:
12319                                 case AIM_BE_REARMED:
12320                                 case AIM_SAFETY:
12321                                 case AIM_BAY_EMERGE:
12322                                         aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
12323                                         aip->previous_mode = aip->mode;
12324                                         aip->previous_submode = aip->submode;
12325                                         aip->mode = AIM_EVADE_WEAPON;
12326                                         aip->submode = -1;
12327                                         aip->submode_start_time = Missiontime;
12328                                         aip->mode_time = timestamp(MAX_EVADE_TIME);     //      Max time to evade.
12329                                         //nprintf(("AI", "%s Evade weapon in frame #%i\n", Ships[objp->instance].ship_name, AI_FrameCount));
12330                                         break;
12331                                 case AIM_EVADE_WEAPON:          //      Note: We don't want to change mode on another evasion, or previous_mode will get bashed.
12332                                 case AIM_PLAY_DEAD:
12333                                 case AIM_BAY_DEPART:
12334                                 case AIM_SENTRYGUN:
12335                                         break;
12336                                 case AIM_WARP_OUT:
12337                                         break;
12338                                 default:
12339                                         Int3();                 //      Hey, what mode is it?
12340                                         break;
12341                                 }
12342                         }
12343                 } else {
12344                         aip->nearest_locked_object = -1;
12345                 }
12346         }
12347 }
12348
12349 //      Maybe evade a dumbfire weapon that was fired when Pl_objp was targeted.
12350 //      Have an 80% chance of evading in a second
12351 void maybe_evade_dumbfire_weapon(ai_info *aip)
12352 {
12353         //      Only small ships evade an incoming missile.  Why would a capital ship try to swerve?
12354         if (!(Ship_info[Ships[Pl_objp->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
12355                 return;
12356         }
12357
12358         //      Make sure in a mode in which we evade dumbfire weapons.
12359         switch (aip->mode) {
12360         case AIM_CHASE:
12361                 if (aip->submode == SM_ATTACK_FOREVER) {
12362                         return;
12363                 }
12364         case AIM_GUARD:
12365                 //      If in guard mode and far away from guard object, don't pursue guy that hit me.
12366                 if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
12367                         if (vm_vec_dist_quick(&Objects[Ships[aip->shipnum].objnum].pos, &Objects[aip->guard_objnum].pos) > 500.0f) {
12368                                 return;
12369                         }
12370                 }
12371         case AIM_STILL:
12372         case AIM_STAY_NEAR:
12373         case AIM_EVADE:
12374         case AIM_GET_BEHIND:
12375         case AIM_AVOID:
12376         case AIM_PATH:
12377         case AIM_NONE:
12378         case AIM_WAYPOINTS:
12379         case AIM_SAFETY:
12380                 break;
12381         case AIM_STRAFE:
12382         case AIM_BIGSHIP:
12383         case AIM_DOCK:
12384         case AIM_PLAY_DEAD:
12385         case AIM_EVADE_WEAPON:
12386         case AIM_BAY_EMERGE:
12387         case AIM_BAY_DEPART:
12388         case AIM_SENTRYGUN:
12389         case AIM_WARP_OUT:
12390                 return;
12391         default:
12392                 Int3(); //      Bogus mode!
12393                 return;
12394         }
12395
12396         if (is_instructor(&Objects[Ships[aip->shipnum].objnum]))
12397                 return; //      Instructor doesn't evade.
12398
12399         float t = ai_endangered_by_weapon(aip);
12400         if ((t > 0.0f) && (t < 1.0f)) {
12401         // Check if this weapon is from a large ship Pl_objp is attacking... if so, enter strafe mode
12402                 if ( ai_big_maybe_enter_strafe_mode(Pl_objp, aip->danger_weapon_objnum) ) {
12403                         return;
12404                 }
12405
12406                 switch (aip->mode) {
12407                 case AIM_CHASE:
12408                         switch (aip->submode) {
12409                         case SM_EVADE:
12410                         case SM_ATTACK_FOREVER:
12411                         case SM_AVOID:
12412                         case SM_GET_AWAY:
12413                         case SM_EVADE_WEAPON:
12414                                 break;
12415                         default:
12416                                 if (ai_near_full_strength(Pl_objp, &Ship_info[Ships[Pl_objp->instance].ship_info_index])) {
12417                                         //mprintf(("Ship %s entered super mode at %7.3f\n", Ships[Pl_objp->instance].ship_name, 1.0f * Missiontime / (1<<16)));
12418                                         aip->submode = SM_SUPER_ATTACK;
12419                                         aip->submode_start_time = Missiontime;
12420                                         aip->last_attack_time = Missiontime;
12421                                 } else {
12422                                         //mprintf(("Ship %s entered dumbfire evade mode at %7.3f\n", Ships[Pl_objp->instance].ship_name, 1.0f * Missiontime / (1<<16)));
12423                                         aip->submode = SM_EVADE_WEAPON;
12424                                         aip->submode_start_time = Missiontime;
12425                                 }
12426                                 break;
12427                         }
12428                         break;
12429                 case AIM_GUARD:
12430                 case AIM_STILL:
12431                 case AIM_STAY_NEAR:
12432                 case AIM_EVADE:
12433                 case AIM_GET_BEHIND:
12434                 case AIM_AVOID:
12435                 case AIM_PATH:
12436                 case AIM_NONE:
12437                 case AIM_WAYPOINTS:
12438                 case AIM_SAFETY:
12439                         if (!(aip->ai_flags & (AIF_NO_DYNAMIC | AIF_KAMIKAZE)) && (Ship_info[Ships[aip->shipnum].ship_info_index].flags & SIF_SMALL_SHIP)) {
12440                                 aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
12441                                 aip->previous_mode = aip->mode;
12442                                 aip->previous_submode = aip->submode;
12443                                 aip->mode = AIM_EVADE_WEAPON;
12444                                 aip->submode = -1;
12445                                 aip->submode_start_time = Missiontime;
12446                                 aip->mode_time = timestamp(MAX_EVADE_TIME);     //      Evade for up to five seconds.
12447                         }
12448                         break;
12449                 case AIM_STRAFE:
12450                 case AIM_BIGSHIP:
12451                 case AIM_DOCK:
12452                 case AIM_PLAY_DEAD:
12453                 case AIM_EVADE_WEAPON:
12454                 case AIM_BAY_EMERGE:
12455                 case AIM_BAY_DEPART:
12456                 case AIM_SENTRYGUN:
12457                         break;
12458                 default:
12459                         Int3(); //      Bogus mode!
12460                 }
12461         }
12462 }
12463
12464 // determine what path to use when emerging from a fighter bay
12465 // input:       pl_objp =>      pointer to object for ship that is arriving
12466 //                              pos             =>      output parameter, it is the starting world pos for path choosen
12467 //                              v.fvec          =>      output parameter, this is the forward vector that ship has when arriving
12468 //
12469 // exit:                -1              =>      path could not be located
12470 //                               0              => success
12471 int ai_acquire_emerge_path(object *pl_objp, int parent_objnum, vector *pos, vector *fvec)
12472 {
12473         int                     path_index, sb_path_index;
12474         ship                    *parent_sp = NULL;
12475         polymodel       *pm;
12476         ai_info         *aip;
12477         ship_bay                *sb;
12478         pnode                   *pnp;
12479         vector          *next_point;
12480
12481         aip = &Ai_info[Ships[pl_objp->instance].ai_index];
12482
12483         if ( parent_objnum == -1 ) {
12484                 Int3();
12485                 return -1;
12486         }
12487
12488         parent_sp = &Ships[Objects[parent_objnum].instance];
12489
12490         SDL_assert(parent_sp != NULL);
12491         pm = model_get( parent_sp->modelnum );
12492         sb = pm->ship_bay;
12493
12494         if ( sb == NULL ) 
12495                 return -1;
12496
12497         if ( sb->num_paths <= 0 ) 
12498                 return -1;
12499
12500         // try to find a bay path that is not taken
12501         sb_path_index = Ai_last_arrive_path++;
12502
12503         if ( sb_path_index >= sb->num_paths ) {
12504                 sb_path_index=0;
12505                 Ai_last_arrive_path=0;
12506         }
12507
12508         path_index = sb->paths[sb_path_index];
12509         if ( path_index == -1 ) 
12510                 return -1;
12511
12512         // create the path for pl_objp to follow
12513         create_model_exit_path(pl_objp, &Objects[parent_objnum], path_index, pm->paths[path_index].nverts);
12514         
12515         // Set this flag, so we don't bother recreating the path... we won't need to update the path
12516         // that has just been created.
12517 //      aip->ai_flags |= AIF_USE_STATIC_PATH;
12518
12519         // now return to the caller what the starting world pos and starting fvec for the ship will be
12520         SDL_assert((aip->path_start >= 0) && (aip->path_start < MAX_PATH_POINTS));
12521         pnp = &Path_points[aip->path_start];
12522         *pos = pnp->pos;
12523
12524         // calc the forward vector using the starting two points of the path
12525         pnp = &Path_points[aip->path_start+1];
12526         next_point = &pnp->pos;
12527         vm_vec_normalized_dir(fvec, next_point, pos);
12528
12529         // record the parent objnum, since we'll need it once we're done with following the path
12530         aip->goal_objnum = parent_objnum;
12531         aip->goal_signature = Objects[parent_objnum].signature;
12532         aip->mode = AIM_BAY_EMERGE;
12533         aip->submode_start_time = Missiontime;
12534
12535         // set up starting vel
12536         vector vel;
12537         float speed;
12538         speed = Ship_info[Ships[pl_objp->instance].ship_info_index].max_speed;
12539         vel = *fvec;
12540         vm_vec_scale( &vel, speed );
12541         pl_objp->phys_info.vel = vel;
12542         pl_objp->phys_info.desired_vel = vel;
12543         pl_objp->phys_info.prev_ramp_vel.xyz.x = 0.0f;
12544         pl_objp->phys_info.prev_ramp_vel.xyz.y = 0.0f;
12545         pl_objp->phys_info.prev_ramp_vel.xyz.z = speed;
12546         pl_objp->phys_info.forward_thrust = 0.0f;               // How much the forward thruster is applied.  0-1.
12547
12548         return 0;       
12549 }
12550
12551 // clean up path data used for emerging from a fighter bay
12552 void ai_emerge_bay_path_cleanup(ai_info *aip)
12553 {
12554         aip->path_start = -1;
12555         aip->path_cur = -1;
12556         aip->path_length = 0;
12557         aip->mode = AIM_NONE;
12558 }
12559
12560 // handler for AIM_BAY_EMERGE
12561 void ai_bay_emerge()
12562 {
12563         ai_info *aip;
12564         int             parent_died=0;
12565
12566         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
12567
12568         // if no path to follow, leave this mode
12569         if ( aip->path_start < 0 ) {
12570                 aip->mode = AIM_NONE;
12571                 return;
12572         }
12573
12574         // ensure parent ship is still alive
12575         if ( aip->goal_objnum < 0 ) {
12576                 parent_died=1;
12577         } 
12578         if ( !parent_died ) {
12579                 if ( Objects[aip->goal_objnum].signature != aip->goal_signature ) {
12580                         parent_died=1;
12581                 }
12582         }
12583
12584         if ( !parent_died ) {
12585                 SDL_assert(Objects[aip->goal_objnum].type == OBJ_SHIP);
12586                 if ( Ships[Objects[aip->goal_objnum].instance].flags & SF_DYING ) {
12587                         parent_died = 1;
12588                 }
12589         }
12590
12591         if ( parent_died ) {
12592                 ai_emerge_bay_path_cleanup(aip);
12593                 return;
12594         }
12595
12596         // follow the path to the final point
12597         ai_path();
12598
12599         // New test: must have been in AI_EMERGE mode for at least 10 seconds, and be a minimum distance from the start point
12600         if ( ( (Missiontime - aip->submode_start_time) > 10*F1_0 ) && (vm_vec_dist_quick(&Pl_objp->pos, &Objects[aip->goal_objnum].pos) > 0.75f * Objects[aip->goal_objnum].radius)) {
12601                 // erase path
12602                 ai_emerge_bay_path_cleanup(aip);
12603         }
12604
12605         // 2-25-99: Need this check to fix an assert for supercap ships... maybe we'll only do this check for supercaps 
12606         if (aip->path_cur > (aip->path_start+aip->path_length-1)) {
12607                 ai_emerge_bay_path_cleanup(aip);
12608         }       
12609 }
12610
12611 // Select the closest depart path
12612 //
12613 //      input:  aip     =>              ai info pointer to ship seeking to depart
12614 //                              pm              =>              pointer to polymodel for the ship contining the ship bay/depart paths
12615 //
12616 // exit:                >=0     =>              ship bay path index for depart path (ie index into sb->paths[])
12617 //                              -1              =>              no path could be found
12618 //
12619 // NOTE: this function should only be used for calculating closest depart paths for ai mode
12620 //                      AI_BAY_DEPART.  It tries to find the closest path that isn't already in use
12621 int ai_find_closest_depart_path(ai_info *aip, polymodel *pm)
12622 {
12623         int                     i, j, best_path, best_free_path;
12624         float                   dist, min_dist, min_free_dist;
12625         vector          *source;
12626         model_path      *mp;
12627         ship_bay                *sb;
12628
12629         sb = pm->ship_bay;
12630
12631         best_free_path = best_path = -1;
12632         min_free_dist = min_dist = 1e20f;
12633         SDL_assert(aip->shipnum >= 0);
12634         source = &Objects[Ships[aip->shipnum].objnum].pos;
12635
12636         for ( i = 0; i < sb->num_paths; i++ ) {
12637
12638
12639                 mp = &pm->paths[sb->paths[i]];
12640                 for ( j = 0; j < mp->nverts; j++ ) {
12641                         dist = vm_vec_dist_squared(source, &mp->verts[j].pos);
12642
12643                         if ( dist < min_dist ) {
12644                                 min_dist = dist;
12645                                 best_path = i;
12646                         }
12647
12648                         // If this is a free path
12649                         if ( !(sb->depart_flags & (1<<i)) ) {
12650                                 if ( dist < min_free_dist ) {
12651                                         min_free_dist = dist;
12652                                         best_free_path = i;
12653                                 }
12654                         }
12655                 }
12656         }
12657
12658         if ( best_free_path >= 0 ) {
12659                 return best_free_path;          
12660         }
12661
12662         return best_path;
12663 }
12664
12665 // determine what path to use when trying to depart to a fighter bay
12666 // NOTE: this should be called when AIM_BAY_DEPART mode is set
12667 //
12668 // input:       pl_objp =>      pointer to object for ship that is departing
12669 //
12670 // exit:                -1      =>      could not find depart path
12671 //                              0       => found depart path
12672 int ai_acquire_depart_path(object *pl_objp, int parent_objnum)
12673 {
12674         int                     objnum, path_index;
12675         polymodel       *pm;
12676         ai_info         *aip;
12677         ship                    *sp;
12678         ship_bay                *sb;
12679
12680         aip = &Ai_info[Ships[pl_objp->instance].ai_index];
12681
12682         if ( parent_objnum == -1 ) {
12683                 ship_obj        *so;
12684
12685                 // for now just locate a captial ship on the same team:
12686                 so = GET_FIRST(&Ship_obj_list);
12687                 objnum = -1;
12688                 while(so != END_OF_LIST(&Ship_obj_list)){
12689                         sp = &Ships[Objects[so->objnum].instance];
12690                         if ( (Ship_info[sp->ship_info_index].flags & (SIF_HUGE_SHIP)) && (sp->team == Ships[pl_objp->instance].team) ) {
12691                                 objnum = so->objnum;
12692                                 break;
12693                         }
12694                         so = GET_NEXT(so);
12695                 } 
12696         } else {
12697                 objnum = parent_objnum;
12698         }
12699
12700         aip->path_start = -1;
12701
12702         if ( objnum == -1 )
12703                 return -1;
12704
12705         pm = model_get( Ships[Objects[objnum].instance].modelnum );
12706         sb = pm->ship_bay;
12707
12708         if ( sb == NULL ) 
12709                 return -1;
12710         if ( sb->num_paths <= 0 ) 
12711                 return -1;
12712
12713 /*
12714         
12715         path_index = -1;
12716         for ( i = 0; i < sb->num_paths; i++ ) {
12717                 if ( !(sb->depart_flags & (1<<i)) ) {
12718                         sb->depart_flags |= (1<<i);
12719                         path_index = sb->paths[i];
12720                         aip->submode_parm0 = i;                 // use mode-specific parameter to record ship bay path index
12721                         break;
12722                 }
12723         }
12724 */
12725         
12726         // take the closest path we can find
12727         int ship_bay_path;
12728         ship_bay_path = ai_find_closest_depart_path(aip, pm);
12729
12730         if (ship_bay_path == -1) {
12731                 return -1;
12732         }
12733
12734         path_index = sb->paths[ship_bay_path];
12735         aip->submode_parm0 = ship_bay_path;
12736         sb->depart_flags |= (1<<ship_bay_path);
12737
12738         if ( path_index == -1 ) {
12739                 return -1;
12740         }
12741
12742         SDL_assert(pm->n_paths > path_index);
12743         ai_find_path(pl_objp, objnum, path_index, 0);
12744
12745         // Set this flag, so we don't bother recreating the path... we won't need to update the path
12746         // that has just been created.
12747         aip->ai_flags &= ~AIF_USE_STATIC_PATH;
12748
12749         aip->goal_objnum = objnum;
12750         aip->goal_signature = Objects[objnum].signature;
12751         aip->mode = AIM_BAY_DEPART;
12752
12753         Ships[pl_objp->instance].flags |= SF_DEPART_DOCKBAY;
12754         return 0;
12755 }
12756
12757 // handler for AIM_BAY_DEPART
12758 void ai_bay_depart()
12759 {
12760         ai_info *aip;
12761
12762         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
12763
12764         // if no path to follow, leave this mode
12765         if ( aip->path_start < 0 ) {
12766                 aip->mode = AIM_NONE;
12767                 return;
12768         }
12769
12770         // check if parent ship still exists, if not abort depart 
12771         if ( aip->goal_signature != Objects[aip->goal_objnum].signature ) {
12772                 aip->mode = AIM_NONE;
12773                 return;
12774         }
12775
12776         // follow the path to the final point
12777         ai_path();
12778
12779         // if the final point is reached, let default AI take over
12780         if ( aip->path_cur >= (aip->path_start+aip->path_length) ) {
12781                 polymodel       *pm;
12782                 ship_bay                *sb;
12783
12784                 pm = model_get( Ships[Objects[aip->goal_objnum].instance].modelnum );
12785                 sb = pm->ship_bay;
12786                 if ( sb != NULL ) {
12787                         sb->depart_flags &= ~(1<<aip->submode_parm0);
12788                 }
12789
12790                 // make ship disappear
12791                 Pl_objp->flags |= OF_SHOULD_BE_DEAD;
12792                 ship_departed( Pl_objp->instance );
12793
12794                 // clean up path stuff
12795                 aip->path_start = -1;
12796                 aip->path_cur = -1;
12797                 aip->path_length = 0;
12798                 aip->mode = AIM_NONE;
12799         }
12800 }
12801
12802 // Handler for AIM_SENTRYGUN.  This AI mode is for sentry guns only (ie floating turrets).
12803 void ai_sentrygun()
12804 {
12805         // Nothing to do here.  Turret firing is handled via process_subobjects().
12806         // If you want the sentry guns to do anything beyond firing their turrets at enemies, add it here!
12807 }
12808
12809 //      --------------------------------------------------------------------------
12810 //      Execute behavior given by aip->mode.
12811 void ai_execute_behavior(ai_info *aip)
12812 {
12813         switch (aip->mode) {
12814         case AIM_CHASE:
12815                 if (En_objp) {
12816                         ai_chase();
12817                 } else if (aip->submode == SM_EVADE_WEAPON) {
12818                         evade_weapon();
12819                         // maybe reset submode
12820                         if (aip->danger_weapon_objnum == -1) {
12821                                 aip->submode = SM_ATTACK;
12822                                 aip->submode_start_time = Missiontime;
12823                                 aip->last_attack_time = Missiontime;
12824                         }
12825                 } else {
12826                         //      Don't circle if this is the instructor.
12827                         ship    *shipp = &Ships[aip->shipnum];
12828                         ship_info       *sip = &Ship_info[shipp->ship_info_index];
12829
12830                         if (SDL_strncasecmp(shipp->ship_name, INSTRUCTOR_SHIP_NAME, strlen(INSTRUCTOR_SHIP_NAME))) {
12831                                 if (sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
12832                                         aip->mode = AIM_NONE;
12833                                 } else {
12834                                         ai_chase_circle(Pl_objp);
12835                                 }
12836                         }
12837                 }
12838                 break;
12839         case AIM_EVADE:
12840                 if (En_objp) {
12841                         ai_evade();
12842                 } else {
12843                         vector  tvec;
12844                         vm_vec_scale_add(&tvec, &Pl_objp->pos, &Pl_objp->orient.v.rvec, 100.0f);
12845                         turn_towards_point(Pl_objp, &tvec, NULL, 0.0f);
12846                         accelerate_ship(aip, 0.5f);
12847                 }
12848                 break;
12849         case AIM_STILL:
12850                 ai_still();
12851                 break;
12852         case AIM_STAY_NEAR:
12853                 ai_stay_near();
12854                 break;
12855         case AIM_GUARD:
12856                 ai_guard();
12857                 break;
12858         case AIM_WAYPOINTS:
12859                 ai_waypoints();
12860                 break;
12861         case AIM_DOCK:
12862                 ai_dock();
12863                 break;
12864         case AIM_NONE:
12865                 // ai_formation();
12866                 break;
12867         case AIM_BIGSHIP:
12868                 ai_big_ship(Pl_objp);
12869                 break;
12870         case AIM_PATH: {
12871                 int path_num;
12872                 path_num = ai_return_path_num_from_dockbay(&Objects[aip->goal_objnum], 0);
12873                 ai_find_path(Pl_objp, aip->goal_objnum, path_num, 0);
12874                 ai_path();
12875                 break;
12876         }
12877         case AIM_SAFETY:
12878                 ai_safety();
12879                 break;
12880         case AIM_EVADE_WEAPON:
12881                 evade_weapon();
12882                 break;
12883         case AIM_STRAFE:
12884                 if (En_objp) {
12885                         SDL_assert(En_objp->type == OBJ_SHIP);
12886                         ai_big_strafe();        // strafe a big ship
12887                 } else {
12888                         aip->mode = AIM_NONE;
12889                 }
12890                 break;
12891         case AIM_BAY_EMERGE:
12892                 ai_bay_emerge();
12893                 break;
12894         case AIM_BAY_DEPART:
12895                 ai_bay_depart();
12896                 break;
12897         case AIM_SENTRYGUN:
12898                 ai_sentrygun();
12899                 break;
12900         case AIM_WARP_OUT:
12901                 break;          //      Note, handled directly from ai_frame().
12902         default:
12903                 Int3();         //      This should never happen -- MK, 5/12/97 
12904                 break;
12905         }
12906
12907         if ( !(ship_get_SIF(aip->shipnum) & SIF_NOT_FLYABLE) ) {
12908                 maybe_evade_dumbfire_weapon(aip);
12909         }
12910 }
12911
12912 //      Auxiliary function for maybe_request_support.
12913 //      Return 1 if subsystem "type" is worthy of repair, else return 0.
12914 //      Since subsystems cannot be repaired if they are at 0 strength, don't return 1 if subsystem is dead.
12915 int mrs_subsystem(ship *shipp, int type)
12916 {
12917         float   t;
12918
12919         t = ship_get_subsystem_strength(shipp, type);
12920
12921         if (t > 0.0f) {
12922                 return (int) ((1.0f - t) * 3);
12923         } else {
12924                 return 3;
12925         }
12926 }
12927
12928 //      Return number of ships on *objp's team that are currently rearming.
12929 int num_allies_rearming(object *objp)
12930 {
12931         ship_obj        *so;
12932         int             team;
12933         int             count = 0;
12934
12935         team = Ships[objp->instance].team;
12936
12937         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
12938                 object  *A;
12939                 
12940                 SDL_assert (so->objnum != -1);
12941                 A = &Objects[so->objnum];
12942
12943                 if (Ships[A->instance].team == team) {
12944                         if (Ai_info[Ships[A->instance].ai_index].ai_flags & (AIF_REPAIRING | AIF_AWAITING_REPAIR)) {
12945                                 count++;
12946                         }
12947                 }
12948         }
12949
12950         return count;
12951 }
12952
12953
12954 //      Maybe ship *objp should request support (rearm/repair).
12955 //      If it does, return TRUE, else return FALSE.
12956 int maybe_request_support(object *objp)
12957 {
12958         ship_info       *sip;
12959         ship                    *shipp;
12960         ai_info         *aip;
12961         int                     desire;
12962
12963         SDL_assert(objp->type == OBJ_SHIP);
12964         shipp = &Ships[objp->instance];
12965         aip = &Ai_info[shipp->ai_index];
12966         sip = &Ship_info[shipp->ship_info_index];
12967
12968         if (!timestamp_elapsed(aip->next_rearm_request_timestamp))
12969                 return 0;
12970
12971         //      Only fighters and bombers request support.
12972         if (!(sip->flags & (SIF_FIGHTER | SIF_BOMBER)))
12973                 return 0;
12974
12975         //      A ship that is currently awaiting does not need support!
12976         if (aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED))
12977                 return 0;
12978
12979         if (!is_support_allowed(objp))
12980                 return 0;
12981
12982         //if (shipp->team != TEAM_FRIENDLY)
12983         //      return 0;
12984
12985         //      Compute a desire value.
12986         //      Desire of 0 means no reason to request support.
12987         //      1 is slight, 2 more, etc.  Maximum is around 20.  Anything larger than 3 is pretty strong.
12988         desire = 0;
12989
12990         //      Set desire based on hull strength.
12991         //      No: We no longer repair hull, so this would cause repeated repair requests.
12992         //desire += 6 - (int) ((objp->hull_strength/sip->initial_hull_strength) * 6.0f);
12993
12994         //      Set desire based on key subsystems.
12995         desire += 2*mrs_subsystem(shipp, SUBSYSTEM_ENGINE);     //      Note, disabled engine forces repair request, regardless of nearby enemies.
12996         desire += mrs_subsystem(shipp, SUBSYSTEM_COMMUNICATION);
12997         desire += mrs_subsystem(shipp, SUBSYSTEM_WEAPONS);
12998         desire += mrs_subsystem(shipp, SUBSYSTEM_SENSORS);
12999
13000         //      Set desire based on percentage of secondary weapons.
13001         ship_weapon *swp = &shipp->weapons;
13002
13003         for ( int i = 0; i < swp->num_secondary_banks; i++ ) {
13004                 if (swp->secondary_bank_start_ammo[i] > 0) {
13005 //                      float r = (float) swp->secondary_bank_ammo[i]*Weapon_info[swp->secondary_bank_weapons[i]].cargo_size/swp->secondary_bank_capacity[i];
13006                         float r = (float) swp->secondary_bank_ammo[i]/swp->secondary_bank_start_ammo[i];
13007                         desire += (int) ((1.0f - r) * 3.0f);
13008                 }
13009         }
13010
13011         //      If no reason to repair, don't bother to see if it's safe to repair.
13012         if (desire == 0){
13013                 return 0;
13014         }
13015
13016         //      Compute danger threshold.
13017         //      Balance this with desire and maybe request support.
13018         if (ai_good_time_to_rearm( objp )) {
13019                 ai_issue_rearm_request(objp);
13020                 return 1;
13021         } else if (num_allies_rearming(objp) < 2) {
13022                 if (desire >= 8) {      //      guarantees disabled will cause repair request
13023                         ai_issue_rearm_request(objp);
13024                 } else if (desire >= 3) {               //      >= 3 means having a single subsystem fully blown will cause repair.
13025                         int     count;
13026                         int objnum = find_nearby_hostile(OBJ_INDEX(objp), get_enemy_team_mask(OBJ_INDEX(objp)), 2000.0f, &count);
13027
13028                         if ((objnum == -1) || (count < 2) || (vm_vec_dist_quick(&objp->pos, &Objects[objnum].pos) > 3000.0f*count/desire)) {
13029                                 ai_issue_rearm_request(objp);
13030                                 return 1;
13031                         } else {
13032                                 //nprintf(("AI", "Would like to rearm, but enemy only %7.3f units away.\n", vm_vec_dist_quick(&objp->pos, &Objects[objnum].pos)));
13033                         }
13034                 }
13035         }
13036
13037         return 0;
13038
13039 }
13040
13041 void ai_set_mode_warp_out(object *objp, ai_info *aip)
13042 {
13043         ai_abort_rearm_request(objp);
13044         if (aip->mode != AIM_WARP_OUT) {
13045                 aip->mode = AIM_WARP_OUT;
13046                 aip->submode = AIS_WARP_1;
13047         }
13048 }
13049
13050 //      Maybe warp ship out.
13051 //      Shivan and HoL fighter/bomber warp out if their weapons subsystems have been destroyed.
13052 void ai_maybe_warp_out(object *objp)
13053 {
13054         ship    *shipp;
13055
13056         // don't do anything if in a training mission.
13057         if ( The_mission.game_type & MISSION_TYPE_TRAINING )
13058                 return;
13059
13060         SDL_assert(objp->type == OBJ_SHIP);
13061
13062         shipp = &Ships[objp->instance];
13063         ai_info *aip = &Ai_info[shipp->ai_index];
13064
13065         if (aip->mode == AIM_WARP_OUT)
13066                 return;
13067
13068         //      If a support ship with no goals and low hull, warp out.  Be sure that there are no pending goals
13069         // in the support ships ai_goal array.  Just process this ships goals.
13070         ship_info       *sip = &Ship_info[shipp->ship_info_index];
13071         if (sip->flags & SIF_SUPPORT) {
13072                 if ( timestamp_elapsed(aip->warp_out_timestamp) ) {
13073                         ai_process_mission_orders( OBJ_INDEX(objp), aip );
13074                         if ( (aip->dock_objnum == -1) && (objp->hull_strength/sip->initial_hull_strength < 0.25f) ) {
13075                                 ai_set_mode_warp_out(objp, aip);
13076                         }
13077                 }
13078         }
13079
13080         //      Friendly don't warp out, they'll eventually request support.
13081         if (shipp->team == TEAM_FRIENDLY)
13082                 return;
13083
13084         if (!(shipp->flags & SF_DEPARTING)) {
13085                 if (sip->flags & (SIF_FIGHTER | SIF_BOMBER)) {
13086                         if (aip->warp_out_timestamp == 0) {
13087                                 //if (ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS) == 0.0f) {
13088                                 //      aip->warp_out_timestamp = timestamp(((myrand() % 10) + 10) * 1000);
13089                                 //}
13090                         } else if (timestamp_elapsed(aip->warp_out_timestamp)) {
13091                                 ai_set_mode_warp_out(objp, aip);
13092                         }
13093                 }
13094         }
13095 }
13096
13097 //      Warp this ship out.
13098 void ai_warp_out(object *objp)
13099 {
13100         // if dying, don't warp out.
13101         if (Ships[objp->instance].flags & SF_DYING) {
13102                 return;
13103         }
13104
13105         ai_info *aip;
13106
13107         aip = &Ai_info[Ships[objp->instance].ai_index];
13108
13109         switch (aip->submode) {
13110         case AIS_WARP_1:
13111                 aip->force_warp_time = timestamp(10*1000);      //      Try to avoid a collision for up to ten seconds.
13112                 aip->submode = AIS_WARP_2;
13113                 break;
13114         case AIS_WARP_2:                        //      Make sure won't collide with any object.
13115                 if (timestamp_elapsed(aip->force_warp_time) || !collide_predict_large_ship(objp, objp->radius*2.0f + 100.0f)) {
13116                         aip->submode = AIS_WARP_3;
13117
13118                         // maybe recalculate collision pairs.
13119                         if (ship_get_warp_speed(objp) > ship_get_max_speed(&Ships[objp->instance])) {
13120                                 // recalculate collision pairs
13121                                 OBJ_RECALC_PAIRS(objp); 
13122                         }
13123
13124                         aip->force_warp_time = timestamp(4*1000);               //      Try to attain target speed for up to 4 seconds.
13125                 } else {
13126                         vector  goal_point;
13127                         vm_vec_scale_add(&goal_point, &objp->pos, &objp->orient.v.uvec, 100.0f);
13128                         turn_towards_point(objp, &goal_point, NULL, 0.0f);
13129                         accelerate_ship(aip, 0.0f);
13130                 }
13131                 break;
13132         case AIS_WARP_3:
13133                 //      Rampup desired_vel in here from current to desired velocity and set PF_USE_VEL. (not sure this is the right flag)
13134                 //      desired velocity is computed in shipfx_calculate_warp_time().  See shipfx#572 for sample code.
13135                 float   speed, goal_speed;
13136                 float shipfx_calculate_warp_speed(object*);
13137                 goal_speed = shipfx_calculate_warp_speed(objp);
13138
13139                 // HUGE ships go immediately to AIS_WARP_4
13140                 if (Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_HUGE_SHIP) {
13141                         aip->submode = AIS_WARP_4;
13142                         break;
13143                 }
13144                 //compute_warpout_stuff(objp, &goal_speed, &warp_time, &warp_pos);
13145                 //goal_speed = 80.0f;
13146                 //set_accel_for_target_speed(objp, 40.0f);
13147                 // DKA 8/11/99 objp->phys_info.flags |= PF_USE_VEL;     This flag is set in object code if warping out and AIS_WARP >= 3, properly accounting for blown engines
13148                 speed = goal_speed * flFrametime + objp->phys_info.speed * (1.0f - flFrametime);
13149                 vm_vec_copy_scale(&objp->phys_info.vel, &objp->orient.v.fvec, speed);
13150                 objp->phys_info.desired_vel = objp->phys_info.vel;
13151                 // nprintf(("AI", "Frame %i, speed = %7.3f, goal = %7.3f\n", Framecount, vm_vec_mag_quick(&objp->phys_info.vel), goal_speed));
13152                 if (timestamp_elapsed(aip->force_warp_time) || (fl_abs(objp->phys_info.speed - goal_speed) < 2.0f))
13153                         aip->submode = AIS_WARP_4;
13154                 break;
13155         case AIS_WARP_4: {
13156                 shipfx_warpout_start(objp);
13157                 aip->submode = AIS_WARP_5;
13158                 break;
13159         }
13160         case AIS_WARP_5:
13161                 break;
13162         default:
13163                 Int3();         //      Illegal submode for warping out.
13164         }
13165 }
13166
13167 //      Return object index of weapon that could produce a shockwave that should be known about to *objp.
13168 //      Return nearest one.
13169 int ai_find_shockwave_weapon(object *objp, ai_info *aip)
13170 {
13171         missile_obj     *mo;
13172         float   nearest_dist = 999999.9f;
13173         int     nearest_index = -1;
13174
13175         for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
13176                 object          *A;
13177                 weapon          *wp;
13178                 weapon_info     *wip;
13179         
13180                 SDL_assert(mo->objnum >= 0 && mo->objnum < MAX_OBJECTS);
13181                 A = &Objects[mo->objnum];
13182
13183                 SDL_assert(A->type == OBJ_WEAPON);
13184                 SDL_assert((A->instance >= 0) && (A->instance < MAX_WEAPONS));
13185                 wp = &Weapons[A->instance];
13186                 wip = &Weapon_info[wp->weapon_info_index];
13187                 SDL_assert( wip->subtype == WP_MISSILE );
13188
13189                 if (wip->shockwave_speed > 0.0f) {
13190                         float   dist;
13191
13192                         dist = vm_vec_dist_quick(&objp->pos, &A->pos);
13193                         if (dist < nearest_dist) {
13194                                 nearest_dist = dist;
13195                                 nearest_index = mo->objnum;
13196                         }
13197                 }
13198         }
13199
13200         return nearest_index;
13201
13202 }
13203
13204 #define EVADE_SHOCKWAVE_DAMAGE_THRESHOLD                100.0f
13205
13206 //      Tell all ships to avoid a big ship that is blowing up.
13207 //      Only avoid if shockwave is fairly large.
13208 //      OK to tell everyone to avoid.  If they're too far away, that gets cleaned up in the frame interval.
13209 void ai_announce_ship_dying(object *dying_objp)
13210 {
13211         float damage = ship_get_exp_damage(dying_objp);
13212         if (damage >= EVADE_SHOCKWAVE_DAMAGE_THRESHOLD) {
13213                 ship_obj        *so;
13214
13215                 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
13216                         if (Ship_info[Ships[Objects[so->objnum].instance].ship_info_index].flags & (SIF_SMALL_SHIP | SIF_FREIGHTER)) {
13217                                 ai_info *aip;
13218
13219                                 aip = &Ai_info[Ships[Objects[so->objnum].instance].ai_index];
13220
13221                                 if ( !(aip->ai_flags & (AIF_DOCKED|AIF_BEING_REPAIRED)) ) {
13222                                         aip->ai_flags |= AIF_AVOID_SHOCKWAVE_SHIP;
13223                                 }
13224                         }
13225                 }
13226         }
13227 }
13228
13229
13230 //      Return object index of weapon that could produce a shockwave that should be known about to *objp.
13231 //      Return nearest one.
13232 int ai_find_shockwave_ship(object *objp, ai_info *aip)
13233 {
13234         ship_obj        *so;
13235         float   nearest_dist = 999999.9f;
13236         int     nearest_index = -1;
13237
13238         for ( so = GET_NEXT(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
13239                 object          *A;
13240                 ship                    *shipp;
13241         
13242                 SDL_assert(so->objnum >= 0 && so->objnum < MAX_OBJECTS);
13243                 A = &Objects[so->objnum];
13244
13245                 SDL_assert(A->type == OBJ_SHIP);
13246                 SDL_assert((A->instance >= 0) && (A->instance < MAX_SHIPS));
13247                 shipp = &Ships[A->instance];
13248                 //      Only look at objects in the process of dying.
13249                 if (shipp->flags & SF_DYING) {
13250                         float damage = ship_get_exp_damage(objp);
13251
13252                         if (damage >= EVADE_SHOCKWAVE_DAMAGE_THRESHOLD) {               //      Only evade quite large blasts
13253                                 float   dist;
13254
13255                                 dist = vm_vec_dist_quick(&objp->pos, &A->pos);
13256                                 if (dist < nearest_dist) {
13257                                         nearest_dist = dist;
13258                                         nearest_index = so->objnum;
13259                                 }
13260                         }
13261                 }
13262         }
13263
13264         return nearest_index;
13265
13266 }
13267
13268 int aas_1(object *objp, ai_info *aip, vector *safe_pos)
13269 {
13270         // MAKE SURE safe_pos DOES NOT TAKE US TOWARD THE A SHIP WE'RE ATTACKING.
13271         if (aip->ai_flags & AIF_AVOID_SHOCKWAVE_WEAPON) {
13272                 //      If we don't currently know of a weapon to avoid, try to find one.
13273                 //      If we can't find one, then clear the bit so we don't keep coming here.
13274                 if (aip->shockwave_object == -1) {
13275                         int shockwave_weapon = ai_find_shockwave_weapon(objp, aip);
13276                         if (shockwave_weapon == -1) {
13277                                 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13278                                 return 0;
13279                         } else {
13280                                 aip->shockwave_object = shockwave_weapon;
13281                         }
13282                 }
13283
13284                 //      OK, we have reason to believe we should avoid aip->shockwave_object.
13285                 SDL_assert(aip->shockwave_object > -1);
13286                 object  *weapon_objp = &Objects[aip->shockwave_object];
13287                 if (weapon_objp->type != OBJ_WEAPON) {
13288                         aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13289                         aip->shockwave_object = -1;
13290                         return 0;
13291                 }
13292
13293                 weapon  *weaponp = &Weapons[weapon_objp->instance];
13294                 weapon_info     *wip = &Weapon_info[weaponp->weapon_info_index];
13295                 object *target_ship_obj = NULL;
13296
13297                 if (wip->shockwave_speed == 0.0f) {
13298                         aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13299                         aip->shockwave_object = -1;
13300                         return 0;
13301                 }
13302
13303                 float   danger_dist;
13304                 vector  expected_pos;           //      Position at which we expect the weapon to detonate.
13305                 int             pos_set = 0;
13306
13307                 danger_dist = wip->outer_radius;
13308                 //      Set predicted position of detonation.
13309                 //      If an aspect locked missile, assume it will detonate at the homing position.
13310                 //      If not, which is not possible in a default FreeSpace weapon, then predict it will detonate at some
13311                 //      time in the future, this time based on max lifetime and life left.
13312                 if (wip->wi_flags & WIF_HOMING_ASPECT) {
13313                         expected_pos = weaponp->homing_pos;
13314                 //      if (weaponp->homing_object && weaponp->homing_object->type == OBJ_SHIP) {
13315                 //              target_ship_obj = weaponp->homing_object;
13316                 //      }
13317                         pos_set = 1;
13318                         if (IS_VEC_NULL(&weaponp->homing_pos)) {
13319                                 pos_set = 0;
13320                                 if (weaponp->target_num != -1) {
13321                                         if (Objects[weaponp->target_num].type == OBJ_SHIP) {
13322                                                 target_ship_obj = &Objects[weaponp->target_num];
13323                                                 expected_pos = target_ship_obj->pos;
13324                                                 pos_set = 1;
13325                                         }
13326                                 }
13327                         }
13328                 }
13329
13330                 if (!pos_set) {
13331                         float   time_scale;
13332
13333                         if (wip->lifetime - weaponp->lifeleft > 5.0f) {
13334                                 time_scale = 1.0f;
13335                         } else {
13336                                 time_scale = weaponp->lifeleft/2.0f;
13337                         }
13338
13339                         vm_vec_scale_add(&expected_pos, &weapon_objp->pos, &weapon_objp->orient.v.fvec, time_scale);
13340                 }
13341
13342                 //      See if too far away to care about shockwave.
13343                 if (vm_vec_dist_quick(&objp->pos, &expected_pos) > danger_dist*2.0f) {
13344                         //aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13345                         return 0;
13346                 } else {
13347                         // try to find a safe position
13348                         vector vec_from_exp;
13349                         float dir = 1.0f;
13350                         vm_vec_sub(&vec_from_exp, &objp->pos, &expected_pos);
13351                         float dot = vm_vec_dotprod(&vec_from_exp, &weapon_objp->orient.v.fvec);
13352                         if (dot > -30) {
13353                                 // if we're already on the other side of the explosion, don't try to fly behind it
13354                                 dir = -1.0f;
13355                         }
13356
13357                         //      Fly towards a point behind the weapon.
13358                         vm_vec_scale_add(safe_pos, &weapon_objp->pos, &weapon_objp->orient.v.fvec, -50000.0f*dir);
13359
13360                         // verify safe_pos will not make us collide with our target objnum, else try 2 other vecs
13361                         // don't bang your head, else go
13362 //                      int go_safe = FALSE;
13363                         int go_safe = TRUE;
13364 /*                      if (target_ship_obj) {
13365                                 if (pp_collide(&objp->pos, safe_pos, target_ship_obj, objp->radius)) {
13366                                         // try up to 2 other random directions
13367                                         vector dir_vec, rand_vec;
13368                                         int idx;
13369                                         for (idx=0; idx<2; idx++) {
13370                                                 vm_vec_rand_vec_quick(&rand_vec);
13371                                                 vm_vec_scale_add(&dir_vec, &weapon_objp->orient.v.fvec, &rand_vec, 0.5f);
13372                                                 vm_vec_scale_add(safe_pos, &weapon_objp->pos, &dir_vec, -50000.0f*dir);
13373                                                 if ( !pp_collide(&objp->pos, safe_pos, target_ship_obj, objp->radius) ) {
13374                                                         go_safe = TRUE;
13375                                                         break;
13376                                                 }
13377                                         }
13378                                 } else { // direct path is safe
13379                                         go_safe = TRUE;
13380                                 }
13381                         } else { // no target_obj_ship
13382                                 go_safe = TRUE;
13383                         } */
13384
13385                         if (go_safe) {
13386                                 return 1;
13387                         } else {
13388                                 // can't figure out a good way to go
13389                                 return 0;
13390                         }
13391                 }
13392         } else if (aip->ai_flags & AIF_AVOID_SHOCKWAVE_SHIP) {
13393                 if (aip->shockwave_object == -1) {
13394                         int shockwave_ship = ai_find_shockwave_ship(objp, aip);
13395                         if (shockwave_ship == -1) {
13396                                 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_SHIP;
13397                                 return 0;
13398                         } else {
13399                                 aip->shockwave_object = shockwave_ship;
13400                         }
13401                 }
13402
13403                 SDL_assert(aip->shockwave_object > -1);
13404                 object  *ship_objp = &Objects[aip->shockwave_object];
13405                 if (ship_objp == objp) {
13406                         aip->shockwave_object = -1;
13407                         return 0;
13408                 }
13409
13410                 if (ship_objp->type != OBJ_SHIP) {
13411                         aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_SHIP;
13412                         return 0;
13413                 }
13414
13415                 //      Optimize note! Don't really have to normalize.  We only need a point away from the blowing-up ship.
13416                 vector safe_vec;
13417
13418                 vm_vec_normalized_dir(&safe_vec, &objp->pos, &ship_objp->pos);
13419                 vm_vec_scale_add(safe_pos, &ship_objp->pos, &safe_vec, 50000.0f);       //      Fly away from the ship.
13420
13421                 float outer_rad = ship_get_exp_outer_rad(ship_objp);
13422
13423                 if (vm_vec_dist_quick(&objp->pos, &ship_objp->pos) > outer_rad*1.5f) {
13424                         aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13425                         return 0;
13426                 }
13427
13428                 return 1;
13429
13430         } else {
13431                 Int3(); //      Illegal -- supposedly avoiding a shockwave, but neither ship nor weapon.  What is it!?
13432         }
13433
13434         return 0;
13435 }
13436
13437 /*
13438 int rct_done = 0;
13439
13440 void rand_chance_test()
13441 {
13442         int     i;
13443         float   frametime;
13444
13445         if (rct_done)
13446                 return;
13447
13448         rct_done = 1;
13449
13450         for (frametime=0.02f; frametime<0.25f; frametime *= 1.25f) {
13451                 float   chance;
13452
13453                 nprintf(("AI", "%6.4f: ", frametime));
13454                 for (chance=0.25f; chance<2.5f; chance += 0.25f) {
13455                         int count = 0;
13456
13457                         for (i=0; i<100.0f/frametime; i++) {
13458                                 if (rand_chance(frametime, chance))
13459                                         count++;
13460                         }
13461                         nprintf(("AI", "%3i ", count));
13462                 }
13463                 nprintf(("AI", "\n"));
13464         }
13465 }
13466 */
13467
13468 //      --------------------------------------------------------------------------
13469 //      Make object *objp avoid the nearest dangerous shockwave-producing weapon.
13470 //      If it looks like there is no valid shockwave-producing weapon then clear the AIF_AVOID_SHOCKWAVE_WEAPON bit in ai_flags and return.
13471 //      Return 1 if avoiding a shockwave, else return 0.
13472 int ai_avoid_shockwave(object *objp, ai_info *aip)
13473 {
13474         vector  safe_pos;
13475
13476         //rand_chance_test();
13477         // BIG|HUGE do not respond to shockwaves
13478         if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) {
13479                 // don't come here again
13480                 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE;
13481                 return 0;
13482         }
13483
13484         //      Don't all react right away.
13485         if (!(aip->ai_flags & AIF_AVOID_SHOCKWAVE_STARTED))
13486                 if (!rand_chance(flFrametime, (float) aip->ai_class/4.0f + 0.25f))      //      Chance to avoid in 1 second is 0.25 + ai_class/4
13487                         return 0;
13488
13489         if (!aas_1(objp, aip, &safe_pos)) {
13490                 aip->ai_flags |= AIF_AVOID_SHOCKWAVE_STARTED;
13491                 return 0;
13492         }
13493
13494         aip->ai_flags |= AIF_AVOID_SHOCKWAVE_STARTED;
13495
13496         //      OK, evade the shockwave!
13497         turn_towards_point(objp, &safe_pos, NULL, 0.0f);
13498         vector  vec_to_safe_pos;
13499         float           dot_to_goal;
13500
13501         vm_vec_normalized_dir(&vec_to_safe_pos, &safe_pos, &objp->pos);
13502
13503         dot_to_goal = vm_vec_dot(&objp->orient.v.fvec, &vec_to_safe_pos);
13504         if (dot_to_goal < -0.5f)
13505                 accelerate_ship(aip, 0.3f);
13506         else {
13507                 accelerate_ship(aip, 1.0f + dot_to_goal);
13508                 if (dot_to_goal > 0.2f) {
13509                         if (!(objp->phys_info.flags & PF_AFTERBURNER_ON )) {
13510                                 afterburners_start(objp);
13511                                 aip->afterburner_stop_time = Missiontime + 2*F1_0;
13512                         }
13513                 }
13514         }
13515
13516         return 1;
13517 }
13518
13519 //      Awaiting repair.  Be useful.
13520 //      Probably fly towards incoming repair ship.
13521 //      Return true if this ship is close to being repaired, else return false.
13522 int ai_await_repair_frame(object *objp, ai_info *aip)
13523 {
13524         if (!(aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED)))
13525                 return 0;
13526
13527         if (aip->dock_objnum == -1)
13528                 return 0;
13529
13530         ship    *shipp;
13531         ship_info       *sip;
13532
13533         shipp = &Ships[Objects[aip->dock_objnum].instance];
13534         sip = &Ship_info[shipp->ship_info_index];
13535
13536         aip->ai_flags &= ~AIF_FORMATION_OBJECT; //      Prevents endless rotation.
13537
13538         if (!(sip->flags & SIF_SUPPORT))
13539                 return 0;
13540
13541         vector  goal_point;
13542         object  *repair_objp;
13543
13544         repair_objp = &Objects[aip->dock_objnum];
13545
13546         if (Ships[repair_objp->instance].team == TEAM_TRAITOR) {
13547                 ai_abort_rearm_request(repair_objp);
13548                 return 0;
13549         }
13550
13551         vm_vec_scale_add(&goal_point, &repair_objp->pos, &repair_objp->orient.v.uvec, -50.0f);  //      Fly towards point below repair ship.
13552
13553         vector  vtr;
13554         float dist = vm_vec_normalized_dir(&vtr, &goal_point, &objp->pos);
13555         float dot = vm_vec_dot(&vtr, &objp->orient.v.fvec);
13556
13557         if (dist > 200.0f) {
13558                 //nprintf(("AI", "%s flying towards %s for repair, dist = %7.3f\n", Ships[objp->instance].ship_name, &Ships[repair_objp->instance].ship_name, dist));
13559                 accelerate_ship(aip, (0.9f + dot) * dist/1500.0f);
13560                 turn_towards_point(objp, &goal_point, NULL, 0.0f);
13561         } else {
13562                 accelerate_ship(aip, 0.0f);
13563                 //nprintf(("AI", "%s sitting still awaiting repair from %s, dist = %7.3f\n", Ships[objp->instance].ship_name, &Ships[repair_objp->instance].ship_name, dist));
13564         }
13565
13566         return 1;
13567 }
13568
13569 //      Maybe cause this ship to self-destruct.
13570 //      Currently, any small ship (SIF_SMALL_SHIP) that has been disabled will self-destruct after awhile.
13571 //      Maybe should only do this if they are preventing their wing from re-entering.
13572 void ai_maybe_self_destruct(object *objp, ai_info *aip)
13573 {
13574         //      Friendly ships can be repaired, so no self-destruct.
13575         //      In multiplayer, just don't self-destruct.  I figured there would be a problem. -- MK, 3/19/98.
13576         if ((Ships[objp->instance].team == TEAM_FRIENDLY) || (Game_mode & GM_MULTIPLAYER))
13577                 return;
13578
13579         //      Small ships in a wing blow themselves up after awhile if engine or weapons system has been destroyed.
13580         //      Reason: Don't want them to prevent a re-emergence of the wing.
13581         //      Note: Don't blow up if not in a wing for two reasons: One, won't affect re-emergence of waves and (1) disable the Dragon
13582         //      mission would be broken.
13583         if ((Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_SMALL_SHIP) && (Ships[objp->instance].wingnum != -1)) {
13584                 if ((ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) ||
13585                         (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_WEAPONS) <= 0.0f)) {
13586                         if (aip->self_destruct_timestamp < 0)
13587                                 aip->self_destruct_timestamp = timestamp(90 * 1000);    //      seconds until self-destruct
13588                 } else {
13589                         aip->self_destruct_timestamp = -1;
13590                 }
13591
13592                 if (aip->self_destruct_timestamp < 0) {
13593                         return;
13594                 }
13595
13596                 if (timestamp_elapsed(aip->self_destruct_timestamp)) {
13597                         ship_apply_local_damage( objp, objp, &objp->pos, objp->hull_strength*flFrametime + 1.0f, MISS_SHIELDS);
13598                 }
13599         }
13600 }
13601
13602 // Determine if pl_objp needs a new target, called from ai_frame()
13603 int ai_need_new_target(object *pl_objp, int target_objnum)
13604 {
13605         object *objp;
13606
13607         if ( target_objnum < 0 ) {
13608                 return 1;
13609         }
13610
13611         objp = &Objects[target_objnum];
13612
13613         if ( (objp->type != OBJ_SHIP) && (objp->type != OBJ_ASTEROID) && (objp->type != OBJ_WEAPON) ) {
13614                 return 1;
13615         }
13616
13617         if ( objp->type == OBJ_SHIP ) {
13618                 if ( Ships[objp->instance].flags & SF_DYING ) {
13619                         return 1;
13620                 } else if (Ships[objp->instance].team == Ships[pl_objp->instance].team)
13621                         return 1;
13622         }
13623
13624         return 0;
13625 }
13626
13627 //      If *objp is recovering from a collision with a big ship, handle it.
13628 //      Return true if recovering.
13629 int maybe_big_ship_collide_recover_frame(object *objp, ai_info *aip)
13630 {
13631         float   dot, dist;
13632         vector  v2g;
13633         
13634         if (aip->ai_flags & AIF_BIG_SHIP_COLLIDE_RECOVER_1) {
13635                 ai_turn_towards_vector(&aip->big_recover_pos_1, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, NULL, NULL, 0.0f, 0, NULL);
13636                 dist = vm_vec_normalized_dir(&v2g, &aip->big_recover_pos_1, &objp->pos);
13637                 dot = vm_vec_dot(&objp->orient.v.fvec, &v2g);
13638                 accelerate_ship(aip, dot);
13639
13640                 //      If close to desired point, or 15+ seconds since entered this mode, continue to next mode.
13641                 if ((timestamp_until(aip->big_recover_timestamp) < -15*1000) || (dist < (0.5f + flFrametime) * objp->phys_info.speed)) {
13642                         aip->ai_flags &= ~AIF_BIG_SHIP_COLLIDE_RECOVER_1;
13643                         aip->ai_flags |= AIF_BIG_SHIP_COLLIDE_RECOVER_2;
13644                 }
13645
13646                 return 1;
13647
13648         } else if (aip->ai_flags & AIF_BIG_SHIP_COLLIDE_RECOVER_2) {
13649                 ai_turn_towards_vector(&aip->big_recover_pos_2, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, NULL, NULL, 0.0f, 0, NULL);
13650                 dist = vm_vec_normalized_dir(&v2g, &aip->big_recover_pos_2, &objp->pos);
13651                 dot = vm_vec_dot(&objp->orient.v.fvec, &v2g);
13652                 accelerate_ship(aip, dot);
13653
13654                 //      If close to desired point, or 30+ seconds since started avoiding collision, done avoiding.
13655                 if ((timestamp_until(aip->big_recover_timestamp) < -30*1000) || (dist < (0.5f + flFrametime) * objp->phys_info.speed)) {
13656                         aip->ai_flags &= ~AIF_BIG_SHIP_COLLIDE_RECOVER_2;
13657                         aip->ai_flags &= ~AIF_TARGET_COLLISION;
13658                 }
13659
13660                 return 1;
13661         }
13662
13663         if (aip->ai_flags & AIF_TARGET_COLLISION) {
13664                 aip->ai_flags &= ~AIF_TARGET_COLLISION;
13665         }
13666         return 0;
13667 }
13668
13669 void validate_mode_submode(ai_info *aip)
13670 {
13671         switch (aip->mode) {
13672         case AIM_CHASE:
13673                 // check valid submode
13674                 switch (aip->submode) {
13675                 case SM_CONTINUOUS_TURN:
13676                 case SM_ATTACK:
13677                 case SM_EVADE_SQUIGGLE:
13678                 case SM_EVADE_BRAKE:    
13679                 case SM_EVADE:          
13680                 case SM_SUPER_ATTACK:
13681                 case SM_AVOID:  
13682                 case SM_GET_BEHIND:
13683                 case SM_GET_AWAY:               
13684                 case SM_EVADE_WEAPON:
13685                 case SM_FLY_AWAY:       
13686                 case SM_ATTACK_FOREVER:
13687                         break;
13688                 default:
13689                         Int3();
13690                 }
13691                 break;
13692
13693         case AIM_STRAFE:
13694                 // check valid submode
13695                 switch(aip->submode) {
13696                 case AIS_STRAFE_ATTACK:
13697                 case AIS_STRAFE_AVOID:
13698                 case AIS_STRAFE_RETREAT1:
13699                 case AIS_STRAFE_RETREAT2:
13700                 case AIS_STRAFE_POSITION:
13701                         break;
13702                 default:
13703                         Int3();
13704                 }
13705                 break;
13706         }
13707 }
13708
13709 //      --------------------------------------------------------------------------
13710 // Process AI object "objnum".
13711 void ai_frame(int objnum)
13712 {
13713         ship            *shipp = &Ships[Objects[objnum].instance];
13714         ai_info *aip = &Ai_info[shipp->ai_index];
13715         int             target_objnum;
13716
13717 //      validate_mode_submode(aip);
13718
13719         SDL_assert((aip->mode != AIM_WAYPOINTS) || (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC));
13720
13721         // Set globals defining the current object and its enemy object.
13722         Pl_objp = &Objects[objnum];
13723
13724         if (aip->mode == AIM_WARP_OUT) {
13725                 ai_warp_out(Pl_objp);
13726                 return;
13727         }
13728
13729 /*      //      HACK! TEST! REMOVE ME!
13730         if (Ship_info[shipp->ship_info_index].flags & SIF_BIG_SHIP)
13731                 if (shipp->team == Player_ship->team)
13732                         aip->mode = AIM_CHASE;
13733 */
13734
13735 //      if (!SDL_strncasecmp(Ships[Pl_objp->instance].ship_name, "cancer", 6))
13736 //              nprintf(("AI", "Ship %s: mode = %s, submode = %i\n", Ships[Pl_objp->instance].ship_name, Mode_text[aip->mode], aip->submode));
13737
13738         ai_maybe_self_destruct(Pl_objp, aip);
13739
13740 //      if ( timestamp_elapsed(aip->goal_check_time) ) {
13741                 ai_process_mission_orders( objnum, aip );
13742 //              aip->goal_check_time = timestamp_rand(1000,2000);
13743 //      }
13744
13745         //      Avoid a shockwave, if necessary.  If a shockwave and rearming, stop rearming.
13746         if (aip->ai_flags & AIF_AVOID_SHOCKWAVE) {
13747                 if (ai_avoid_shockwave(Pl_objp, aip)) {
13748                         aip->ai_flags &= ~(AIF_BIG_SHIP_COLLIDE_RECOVER_1 | AIF_BIG_SHIP_COLLIDE_RECOVER_2);
13749                         if (aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED))
13750                                 ai_abort_rearm_request(Pl_objp);
13751                         return;
13752                 }
13753         } else {
13754                 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_STARTED;
13755         }
13756
13757         // moved call to ai_do_repair frame here from below because of the subsequent if statment returning
13758         // if the ship is getting repaired
13759         //      If waiting to be repaired, just stop and sit.
13760         ai_do_repair_frame(Pl_objp, aip, flFrametime);
13761         if ((aip->ai_flags & AIF_AWAITING_REPAIR) || (aip->ai_flags & AIF_BEING_REPAIRED)) {
13762                 if (ai_await_repair_frame(Pl_objp, aip))
13763                         return;
13764         }
13765
13766         if (aip->mode == AIM_PLAY_DEAD)
13767                 return;
13768
13769         //      If recovering from a collision with a big ship, don't continue.
13770         if (maybe_big_ship_collide_recover_frame(Pl_objp, aip))
13771                 return;
13772
13773         ai_preprocess_ignore_objnum(Pl_objp, aip);
13774         target_objnum = set_target_objnum(aip, aip->target_objnum);
13775
13776         // nprintf(("AI", "Frame %i: Coords = %7.3f %7.3f %7.3f\n", AI_FrameCount, Pl_objp->pos.xyz.x, Pl_objp->pos.xyz.y, Pl_objp->pos.xyz.z));
13777
13778         SDL_assert(objnum != target_objnum);
13779
13780         ai_manage_shield(Pl_objp, aip);
13781         
13782         if ( maybe_request_support(Pl_objp) ) {
13783                 if ( Ships[Pl_objp->instance].flags & SF_FROM_PLAYER_WING ) {
13784                         ship_maybe_tell_about_rearm(shipp);
13785                 }
13786         }
13787
13788         ai_maybe_warp_out(Pl_objp);
13789
13790 /*
13791         //      If this ship is attacking an object's subsystems and someone else destroyed
13792         //      the subsystem, it could continue attacking the ship.  Need to invalidate the objnum.
13793         if (target_objnum >= 0)
13794                 if (Objects[target_objnum].flags & OF_PROTECTED) {
13795                         // if (aip->targeted_subsys != NULL)
13796                         //      ; //nprintf(("AI", "subsys hits = %7.3f\n", aip->targeted_subsys->current_hits));
13797
13798                         if ((aip->targeted_subsys == NULL) || (aip->targeted_subsys->current_hits <= 0.0f)) {
13799                                 target_objnum = -1;
13800                                 aip->target_objnum = -1;
13801                         }
13802                 }
13803 */
13804
13805
13806         //      Find an enemy if don't already have one.
13807         En_objp = NULL;
13808         if ( ai_need_new_target(Pl_objp, target_objnum) ) {
13809                 if ((aip->mode != AIM_EVADE_WEAPON) && (aip->active_goal == AI_ACTIVE_GOAL_DYNAMIC)) {
13810                         aip->resume_goal_time = -1;
13811                         aip->active_goal = AI_GOAL_NONE;
13812                 } else if (aip->resume_goal_time == -1) {
13813                         // AL 12-9-97: Don't allow cargo and navbuoys to set their aip->target_objnum
13814                         if ( !(Ship_info[shipp->ship_info_index].flags & SIF_HARMLESS) ) {
13815                                 target_objnum = find_enemy(objnum, MAX_ENEMY_DISTANCE, Skill_level_max_attackers[Game_skill_level]);            //      Attack up to 25K units away.
13816                                 if (target_objnum != -1) {
13817                                         if (aip->target_objnum != target_objnum)
13818                                                 aip->aspect_locked_time = 0.0f;
13819                                         set_target_objnum(aip, target_objnum);
13820                                         En_objp = &Objects[target_objnum];
13821                                 }
13822                         }
13823                 }
13824         } else if (target_objnum >= 0) {
13825                 En_objp = &Objects[target_objnum];
13826         }
13827
13828         // set base stealth info each frame
13829         aip->ai_flags &= ~AIF_STEALTH_PURSIUT;
13830         if (En_objp && En_objp->type == OBJ_SHIP) {
13831                 if (Ship_info[Ships[En_objp->instance].ship_info_index].flags & SIF_STEALTH) {
13832                         int stealth_state = ai_is_stealth_visible(Pl_objp, En_objp);
13833                         float dist = vm_vec_dist_quick(&En_objp->pos, &Pl_objp->pos);
13834
13835                         if (stealth_state != STEALTH_FULLY_TARGETABLE) {
13836                                 aip->ai_flags |= AIF_STEALTH_PURSIUT;
13837                         }
13838
13839                         if ( (stealth_state == STEALTH_FULLY_TARGETABLE) || (stealth_state == STEALTH_VISIBLE) ) {
13840                                 aip->stealth_last_visible_stamp = timestamp();
13841                                 aip->stealth_last_cheat_visible_stamp = aip->stealth_last_visible_stamp;
13842                                 aip->stealth_last_pos = En_objp->pos;
13843                                 aip->stealth_velocity = En_objp->phys_info.vel;
13844                         } else if (dist < 100) {
13845                                 // get cheat timestamp
13846                                 aip->stealth_last_cheat_visible_stamp = timestamp();
13847
13848                                 // set approximate pos and vel, with increasing error as time from last_visible_stamp increases
13849                                 update_ai_stealth_info_with_error(aip/*, 0*/);
13850                         }
13851                 }
13852         }
13853
13854         /*      if ((Pl_objp != NULL) && (En_objp != NULL)) {
13855                 slide_face_ship();
13856                 return;
13857         }
13858 */
13859         // AL 12-10-97: ensure that cargo and navbuoys aip->target_objnum is always -1.
13860         if ( Ship_info[shipp->ship_info_index].flags & SIF_HARMLESS ) {
13861                 aip->target_objnum = -1;
13862         }
13863
13864         if ((En_objp != NULL) && (En_objp->pos.xyz.x == Pl_objp->pos.xyz.x) && (En_objp->pos.xyz.y == Pl_objp->pos.xyz.y) && (En_objp->pos.xyz.z == Pl_objp->pos.xyz.z)) {
13865                 mprintf(("Warning: Object and its enemy have same position.  Object #%i\n", Pl_objp-Objects));
13866                 En_objp = NULL;
13867         }
13868
13869         if (aip->mode == AIM_CHASE) {
13870                 if (En_objp == NULL) {
13871                         aip->active_goal = -1;
13872                 }
13873         }
13874
13875         //      If there is a goal to resume and enough time has elapsed, resume the goal.
13876         if ((aip->resume_goal_time > 0) && (aip->resume_goal_time < Missiontime)) {
13877                 aip->active_goal = AI_GOAL_NONE;
13878                 aip->resume_goal_time = -1;
13879                 target_objnum = find_enemy(objnum, 2000.0f, Skill_level_max_attackers[Game_skill_level]);
13880                 if (target_objnum != -1) {
13881                         if (aip->target_objnum != target_objnum) {
13882                                 aip->aspect_locked_time = 0.0f;
13883                         }
13884                         set_target_objnum(aip, target_objnum);
13885                 }
13886         }
13887
13888         // check if targeted subsystem has been destroyed, if so, move onto another subsystem
13889         // if trying to disable or disarm the target
13890         if ((En_objp != NULL) && ( aip->targeted_subsys != NULL )) {
13891                 SDL_assert(En_objp->type == OBJ_SHIP);
13892                 if ( aip->targeted_subsys->current_hits <= 0.0f ) {
13893                         int subsys_type;
13894
13895                         if ( aip->goals[0].ai_mode == AI_GOAL_DISABLE_SHIP ) {
13896                                 subsys_type = SUBSYSTEM_ENGINE;
13897                         } else if ( aip->goals[0].ai_mode == AI_GOAL_DISARM_SHIP ) {
13898                                 subsys_type = SUBSYSTEM_TURRET;
13899                         } else {
13900                                 subsys_type = -1;
13901                         }
13902
13903                         if ( subsys_type != -1 ) {
13904                                 ship_subsys *new_subsys;
13905                                 new_subsys = ship_return_next_subsys(&Ships[En_objp->instance], subsys_type, &Pl_objp->pos);
13906                                 if ( new_subsys != NULL ) {
13907                                         set_targeted_subsys(aip, new_subsys, aip->target_objnum);
13908                                 } else {
13909                                         // AL 12-16-97: no more subsystems to attack... reset targeting info
13910                                         aip->target_objnum = -1;
13911                                         set_targeted_subsys(aip, NULL, -1);
13912                                 }
13913                         } else {
13914                                 // targeted subsys is destroyed, so stop attacking it
13915                                 set_targeted_subsys(aip, NULL, -1);
13916                         }
13917                 }
13918         }
13919
13920         ai_maybe_launch_cmeasure(Pl_objp, aip);
13921         ai_maybe_evade_locked_missile(Pl_objp, aip);
13922
13923         aip->target_time += flFrametime;
13924
13925         int in_formation = 0;
13926         if (aip->ai_flags & AIF_FORMATION) {
13927                 in_formation = !ai_formation();
13928         }
13929
13930         if ( !in_formation ) {
13931                 ai_execute_behavior(aip);
13932         }
13933
13934         process_subobjects(objnum);
13935         maybe_resume_previous_mode(Pl_objp, aip);
13936         
13937         if (Pl_objp->phys_info.flags & PF_AFTERBURNER_ON ) {
13938                 if (Missiontime > aip->afterburner_stop_time) {
13939                         //nprintf(("AI", "Frame %i, turning off afterburner.\n", AI_FrameCount));
13940                         afterburners_stop(Pl_objp);
13941                 }
13942         }
13943 //      validate_mode_submode(aip);
13944 }
13945
13946 int Waypoints_created = 0;
13947
13948 //      Find the ship with the name *name in the Ship_info array.
13949 int find_ship_name(char *name)
13950 {
13951         int     i;
13952
13953         for (i=0; i<Num_ship_types; i++)
13954                 if (!strcmp(Ship_info[i].name, name))
13955                         return i;
13956
13957         return -1;
13958 }
13959
13960 void create_waypoints()
13961 {
13962         int     i, j;
13963
13964         // Waypoints_created = 1;
13965
13966         if (Waypoints_created)
13967                 return;
13968
13969         for (j=0; j<Num_waypoint_lists; j++)
13970                 for (i=0; i<Waypoint_lists[j].count; i++) {
13971                         obj_create(OBJ_WAYPOINT, 0, j * 65536 + i, NULL,
13972                                 &Waypoint_lists[j].waypoints[i], 0.0f, OF_RENDERS);
13973                 }
13974
13975         Waypoints_created = 1;
13976 }
13977
13978 int Last_ai_obj = -1;
13979
13980 void ai_process( object * obj, int ai_index, float frametime )
13981 {
13982 //      if (Ships[obj->instance].flags & SF_DYING)
13983 //              nprintf(("AI", "Frame: %i Ship %s is dying!\n", Framecount, Ships[obj->instance].ship_name));
13984
13985         if (obj->flags & OF_SHOULD_BE_DEAD)
13986                 return;
13987
13988         // return if ship is dead, unless it's a big ship...then its turrets still fire, like I was quoted in a magazine.  -- MK, 5/15/98.
13989         if ((Ships[obj->instance].flags & SF_DYING ) && !(Ship_info[Ships[obj->instance].ship_info_index].flags & (SIF_HUGE_SHIP | SIF_BIG_SHIP))){
13990                 return;
13991         }
13992
13993         int rfc = 1;            //      Assume will be Reading Flying Controls.
13994
13995         SDL_assert( obj->type == OBJ_SHIP );
13996         SDL_assert( ai_index >= 0 );
13997
13998         init_ship_info();
13999
14000         create_waypoints();
14001
14002         AI_frametime = frametime;
14003         if (obj-Objects <= Last_ai_obj) {
14004                 AI_FrameCount++;
14005         }
14006
14007         memset( &AI_ci, 0, sizeof(AI_ci) );
14008
14009         ai_frame(obj-Objects);
14010
14011         AI_ci.pitch = 0.0f;
14012         AI_ci.bank = 0.0f;
14013         AI_ci.heading = 0.0f;
14014
14015         // the ships maximum velocity now depends on the energy flowing to engines
14016         obj->phys_info.max_vel.xyz.z = Ships[obj->instance].current_max_speed;
14017         ai_info *aip = &Ai_info[Ships[obj->instance].ai_index];
14018
14019         //      In certain circumstances, the AI says don't fly in the normal way.
14020         //      One circumstance is in docking and undocking, when the ship is moving
14021         //      under thruster control.
14022         switch (aip->mode) {
14023         case AIM_DOCK:
14024                 if ((aip->submode >= AIS_DOCK_2) && (aip->submode != AIS_UNDOCK_3))
14025                         rfc = 0;
14026                 break;
14027         case AIM_WARP_OUT:
14028                 if (aip->submode >= AIS_WARP_3)
14029                         rfc = 0;
14030                 break;
14031 //      case AIM_NONE:
14032 //              if (aip->submode == AIS_NONE_FORMATION)
14033 //                      rfc = 0;
14034 //              break;
14035         default:
14036                 break;
14037         }
14038
14039         if (rfc == 1) {
14040                 vector copy_desired_rotvel = obj->phys_info.rotvel;
14041                 physics_read_flying_controls( &obj->orient, &obj->phys_info, &AI_ci, frametime);
14042                 // if obj is in formation and not flight leader, don't update rotvel
14043                 if (aip->ai_flags & AIF_FORMATION) {
14044                         if (&Objects[aip->goal_objnum] != obj) {
14045                                 obj->phys_info.desired_rotvel = copy_desired_rotvel;
14046                                 obj->phys_info.rotvel = copy_desired_rotvel;
14047                         }
14048                 }
14049         }
14050
14051         Last_ai_obj = obj-Objects;
14052 }
14053
14054 //      Initialize ai_info struct of object objnum.
14055 void init_ai_object(int objnum)
14056 {
14057         int     ship_index, ai_index;
14058         ai_info *aip;
14059         int ship_type;
14060         object  *objp;
14061         vector  near_vec;                       //      A vector nearby and mainly in front of this object.
14062
14063         objp = &Objects[objnum];
14064         ship_index = objp->instance;
14065         ai_index = Ships[ship_index].ai_index;
14066         SDL_assert((ai_index >= 0) && (ai_index < MAX_AI_INFO));
14067
14068         aip = &Ai_info[ai_index];
14069
14070         ship_type = Ships[ship_index].ship_info_index;
14071
14072         vm_vec_scale_add(&near_vec, &objp->pos, &objp->orient.v.fvec, 100.0f);
14073         vm_vec_scale_add2(&near_vec, &objp->orient.v.rvec, 10.0f);
14074
14075         // Things that shouldn't have to get initialized, but initialize them just in case!
14076         aip->ai_flags = 0;
14077         aip->previous_mode = AIM_NONE;
14078         aip->mode_time = -1;
14079         aip->target_objnum = -1;
14080         aip->target_signature = -1;
14081         aip->previous_target_objnum = -1;
14082         aip->target_time = 0.0f;
14083         aip->enemy_wing = -1;
14084         aip->attacker_objnum = -1;
14085         aip->goal_objnum = -1;
14086         aip->goal_signature = -1;
14087         aip->guard_objnum = -1;
14088         aip->guard_signature = -1;
14089         aip->guard_wingnum = -1;
14090         aip->dock_signature = -1;
14091         aip->submode = 0;
14092         aip->previous_submode = 0;
14093         aip->best_dot_to_enemy = -1.0f;
14094         aip->best_dot_from_enemy = -1.0f;
14095         aip->best_dot_to_time = 0;
14096         aip->best_dot_from_time = 0;
14097         aip->submode_start_time = 0;
14098         aip->submode_parm0 = 0;
14099         aip->active_goal = -1;
14100         aip->goal_check_time = timestamp(0);
14101         aip->last_predicted_enemy_pos = near_vec;
14102         aip->prev_goal_point = near_vec;
14103         aip->goal_point = near_vec;
14104         aip->time_enemy_in_range = 0.0f;
14105         aip->last_attack_time = 0;
14106         aip->last_hit_time = 0;
14107         aip->last_hit_quadrant = 0;
14108         aip->hitter_objnum = -1;
14109         aip->hitter_signature = -1;
14110         aip->resume_goal_time = -1;
14111         aip->prev_accel = 0.0f;
14112         aip->prev_dot_to_goal = 0.0f;
14113
14114         aip->ignore_objnum = UNUSED_OBJNUM;
14115         aip->ignore_signature = -1;
14116
14117         // aip->mode = AIM_NONE;
14118
14119         // End of Things that shouldn't have to get initialized, but initialize them just in case!
14120
14121         aip->ai_courage = Ai_classes[Ship_info[ship_type].ai_class].ai_courage[Game_skill_level];
14122         aip->ai_patience = Ai_classes[Ship_info[ship_type].ai_class].ai_patience[Game_skill_level];
14123         aip->ai_evasion = Ai_classes[Ship_info[ship_type].ai_class].ai_evasion[Game_skill_level];
14124         aip->ai_accuracy = Ai_classes[Ship_info[ship_type].ai_class].ai_accuracy[Game_skill_level];
14125
14126         if (Num_waypoint_lists > 0) {
14127                 aip->wp_index = -1;
14128                 aip->wp_list = -1;
14129         } else {
14130                 aip->wp_index = -1;
14131                 aip->wp_list = -1;
14132         }
14133
14134         aip->attacker_objnum = -1;
14135         aip->goal_signature = -1;
14136
14137         Objects[objnum].phys_info.prev_fvec = Objects[objnum].orient.v.fvec;
14138
14139         aip->last_predicted_enemy_pos.xyz.x = 0.0f;     //      Says this value needs to be recomputed!
14140         aip->time_enemy_in_range = 0.0f;
14141
14142         aip->resume_goal_time = -1;                                     //      Say there is no goal to resume.
14143
14144         aip->active_goal = -1;
14145         aip->path_start = -1;
14146         aip->path_goal_dist = -1;
14147         aip->path_length = 0;
14148         aip->path_subsystem_next_check = 1;
14149         aip->dock_path_index = -1;
14150         aip->dock_index = -1;
14151         aip->dock_objnum = -1;
14152
14153         aip->danger_weapon_objnum = -1;
14154         aip->danger_weapon_signature = -1;
14155
14156         aip->lead_scale = 0.0f;
14157         aip->last_hit_target_time = Missiontime;
14158
14159         aip->nearest_locked_object = -1;
14160         aip->nearest_locked_distance = 99999.0f;
14161
14162         aip->targeted_subsys = NULL;
14163         aip->last_subsys_target = NULL;
14164         aip->targeted_subsys_parent = -1;
14165
14166         // The next two fields are used to time the rearming to allow useful sound effects for missile rearming
14167         aip->rearm_first_missile = TRUE;                //      flag to indicate that next missile to load is the first missile
14168         aip->rearm_release_delay = 0;                   //      timestamp to delay the separation of docked ships after rearm
14169
14170         aip->next_predict_pos_time = 0;
14171
14172         aip->afterburner_stop_time = 0;
14173         aip->last_objsig_hit = -1;                              // object signature of the ship most recently hit by aip
14174
14175         aip->path_next_create_time = timestamp(1);
14176         aip->path_create_pos = Objects[objnum].pos;
14177         aip->path_create_orient = Objects[objnum].orient;
14178
14179         aip->ignore_expire_timestamp = timestamp(1);
14180         aip->warp_out_timestamp = 0;
14181         aip->next_rearm_request_timestamp = timestamp(1);
14182         aip->primary_select_timestamp = timestamp(1);
14183         aip->secondary_select_timestamp = timestamp(1);
14184         aip->scan_for_enemy_timestamp = timestamp(1);
14185
14186         aip->choose_enemy_timestamp = timestamp(3*(NUM_SKILL_LEVELS-Game_skill_level) * ((rand_alt() % 500) + 500));
14187
14188         aip->shockwave_object = -1;
14189         aip->shield_manage_timestamp = timestamp(1);
14190         aip->self_destruct_timestamp = -1;      //      This is a flag that we have not yet set this.
14191         aip->ok_to_target_timestamp = timestamp(1);
14192         aip->pick_big_attack_point_timestamp = timestamp(1);
14193         vm_vec_zero(&aip->big_attack_point);
14194
14195         aip->avoid_check_timestamp = timestamp(1);
14196
14197         aip->abort_rearm_timestamp = -1;
14198
14199         // artillery stuff
14200         aip->artillery_objnum = -1;
14201         aip->artillery_sig = -1;        
14202
14203         // waypoint speed cap
14204         aip->waypoint_speed_cap = -1;
14205
14206         // set lethality to enemy team
14207         aip->lethality = 0.0f;
14208 }
14209
14210 void init_ai_objects()
14211 {
14212         int     i;
14213
14214         for (i=0; i<num_objects; i++){
14215                 if (Objects[i].type == OBJ_SHIP){
14216                         init_ai_object(i);
14217                 }
14218         }
14219 }
14220
14221 void init_ai_system()
14222 {
14223         // MWA -- removed next line of code on 11/12/97.  When a ship is created
14224         // it calls init_ai_object() on it's objnum.  Doing this init at the point where
14225         // this function gets called messes things up.
14226         //init_ai_objects();
14227
14228         Ppfp = Path_points;
14229         Waypoints_created = 0;
14230
14231         Dock_path_warning_given = 0;
14232
14233 /*      for (int i=0; i<MAX_IGNORE_OBJECTS; i++) {
14234                 Ignore_objects[i].objnum = -1;
14235                 Ignore_objects[i].signature = -1;
14236         }
14237 */
14238
14239 }
14240
14241 void ai_set_default_behavior(object *obj, int classnum)
14242 {
14243         ai_info *aip;
14244
14245         SDL_assert(obj != NULL);
14246         SDL_assert(obj->instance != -1);
14247         SDL_assert(Ships[obj->instance].ai_index != -1);
14248
14249         aip = &Ai_info[Ships[obj->instance].ai_index];
14250
14251         aip->behavior = classnum;
14252
14253 }
14254
14255 void ai_do_default_behavior(object *obj)
14256 {
14257         ai_info *aip;
14258         int             ship_flags;
14259
14260         SDL_assert(obj != NULL);
14261         SDL_assert(obj->instance != -1);
14262         SDL_assert(Ships[obj->instance].ai_index != -1);
14263
14264         aip = &Ai_info[Ships[obj->instance].ai_index];
14265
14266         ship_flags = Ship_info[Ships[obj->instance].ship_info_index].flags;
14267         if (!is_instructor(obj) && (ship_flags & (SIF_FIGHTER | SIF_BOMBER))) {
14268                 int enemy_objnum = find_enemy(OBJ_INDEX(obj), 1000.0f, Skill_level_max_attackers[Game_skill_level]);
14269                 set_target_objnum(aip, enemy_objnum);
14270                 aip->mode = AIM_CHASE;
14271                 aip->submode = SM_ATTACK;
14272         } else if (ship_flags & (SIF_SUPPORT)) {
14273                 aip->mode = AIM_SAFETY;
14274                 aip->submode = AISS_1;
14275                 aip->ai_flags &= ~(AIF_REPAIRING);
14276         } else if ( ship_flags & SIF_SENTRYGUN ) {
14277                 aip->mode = AIM_SENTRYGUN;
14278         } else {
14279                 aip->mode = AIM_NONE;
14280         }
14281         
14282         aip->submode_start_time = Missiontime;
14283         aip->active_goal = AI_GOAL_NONE;
14284 }
14285
14286 #define FRIENDLY_DAMAGE_THRESHOLD       50.0f           //      Display a message at this threshold.  Note, this gets scaled by Skill_level
14287
14288 // send the given message from objp.  called from the maybe_process_friendly_hit
14289 // code below when a message must get send to the player when he fires on friendlies
14290 void process_friendly_hit_message( int message, object *objp )
14291 {
14292         int index;
14293
14294         // no traitor in multiplayer
14295         if(Game_mode & GM_MULTIPLAYER){
14296                 return;
14297         }
14298
14299         // don't send this message if a player ship was hit.
14300         if ( objp->flags & OF_PLAYER_SHIP ){
14301                 return;
14302         }
14303
14304         // check if objp is a cargo contianer -- if so, then find a new ship to send the message
14305         index = objp->instance;
14306         if ( !(Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_FIGHTER|SIF_BOMBER)) ){
14307                 index = -1;
14308         }
14309
14310         // if the message is "oops" (the don't hit me message), always make come from Terran command
14311         if ( message == MESSAGE_OOPS ){
14312                 index = -1;
14313         }
14314
14315         if ( index >= 0){
14316                 message_send_builtin_to_player( message, &Ships[index], MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_ANYTIME, 0, 0, -1, -1 );
14317         } else {
14318                 message_send_builtin_to_player( message, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_ANYTIME, 0, 0, -1, -1 );
14319         }
14320 }
14321
14322 extern  void ship_set_subsystem_strength( ship *shipp, int type, float strength );
14323
14324 //      Object *objp_weapon, fired by *objp_hitter, hit object *objp_ship.
14325 void maybe_process_friendly_hit(object *objp_hitter, object *objp_hit, object *objp_weapon)
14326 {
14327         // no turning traitor in multiplayer
14328         if ( Game_mode & GM_MULTIPLAYER ) {
14329                 return;
14330         }
14331
14332         // ditto if mission says no traitors allowed
14333         if (The_mission.flags & MISSION_FLAG_NO_TRAITOR) {
14334                 return;
14335         }
14336
14337         if ((objp_hitter == Player_obj) && (Player_ship->team == TEAM_FRIENDLY)) {
14338
14339                 // AL 12-4-97: It is possible the Player is a OBJ_GHOST at this point.  If so, bail out.
14340                 if ( objp_hitter->type != OBJ_SHIP ) {
14341                         return;
14342                 }
14343
14344                 SDL_assert(objp_hitter->type == OBJ_SHIP);
14345                 SDL_assert(objp_hit->type == OBJ_SHIP);
14346                 SDL_assert(objp_weapon->type == OBJ_WEAPON);
14347
14348                 ship    *shipp_hitter = &Ships[objp_hitter->instance];
14349                 ship    *shipp_hit = &Ships[objp_hit->instance];
14350
14351                 if (shipp_hitter->team != shipp_hit->team) {
14352                         return;
14353                 }
14354
14355                 // get the player
14356                 player *pp = &Players[Player_num];
14357
14358                 // wacky stuff here
14359                 if (pp->friendly_hits != 0) {
14360                         float   time_since_last_hit = f2fl(Missiontime - pp->friendly_last_hit_time);
14361                         if ((time_since_last_hit >= 0.0f) && (time_since_last_hit < 10000.0f)) {
14362                                 if (time_since_last_hit > 60.0f) {
14363                                         pp->friendly_hits = 0;
14364                                         pp->friendly_damage = 0.0f;
14365                                 } else if (time_since_last_hit > 2.0f) {
14366                                         pp->friendly_hits -= (int) time_since_last_hit/2;
14367                                         pp->friendly_damage -= time_since_last_hit;
14368                                 }
14369
14370                                 if (pp->friendly_damage < 0.0f) {
14371                                         pp->friendly_damage = 0.0f;
14372                                 }
14373
14374                                 if (pp->friendly_hits < 0) {
14375                                         pp->friendly_hits = 0;
14376                                 }
14377                         }
14378                 }
14379
14380                 float   damage;         //      Damage done by weapon.  Gets scaled down based on size of ship.
14381
14382                 damage = Weapon_info[Weapons[objp_weapon->instance].weapon_info_index].damage;
14383                 
14384                 // wacky stuff here
14385                 ship_info *sip = &Ship_info[Ships[objp_hit->instance].ship_info_index];
14386                 if (sip->initial_hull_strength > 1000.0f) {
14387                         float factor = sip->initial_hull_strength / 1000.0f;
14388                         factor = SDL_min(100.0f, factor);
14389                         damage /= factor;
14390                 }
14391
14392                 //      Don't penalize much at all for hitting cargo
14393                 if (sip->flags & (SIF_CARGO | SIF_SENTRYGUN)) {
14394                         damage /= 10.0f;
14395                 }
14396
14397                 //      Hit ship, but not targeting it, so it's not so heinous, maybe an accident.
14398                 if (Ai_info[shipp_hitter->ai_index].target_objnum != OBJ_INDEX(objp_hit)) {
14399                         damage /= 5.0f;
14400                 }
14401
14402                 pp->friendly_last_hit_time = Missiontime;
14403                 pp->friendly_hits++;
14404
14405                 // cap damage and number of hits done this frame
14406                 float accredited_damage = SDL_min(MAX_BURST_DAMAGE, pp->damage_this_burst + damage) - pp->damage_this_burst;
14407                 pp->friendly_damage += accredited_damage;
14408                 pp->damage_this_burst += accredited_damage;
14409
14410                 // Done with adjustments to damage.  Evaluate based on current friendly_damage
14411                 nprintf(("AI", "Friendly damage: %.1f, threshold: %.1f, inc damage: %.1f, max burst: %d\n", pp->friendly_damage, FRIENDLY_DAMAGE_THRESHOLD * (1.0f + (float) (NUM_SKILL_LEVELS + 1 - Game_skill_level)/3.0f), pp->damage_this_burst, MAX_BURST_DAMAGE ));
14412                 
14413                 if (is_instructor(objp_hit)) {
14414                         // it's not nice to hit your instructor
14415                         if (pp->friendly_damage > FRIENDLY_DAMAGE_THRESHOLD) {
14416                                 message_send_builtin_to_player( MESSAGE_INSTRUCTOR_ATTACK, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_IMMEDIATE, 0, 0, -1, -1);
14417                                 pp->last_warning_message_time = Missiontime;
14418                                 ship_set_subsystem_strength( Player_ship, SUBSYSTEM_WEAPONS, 0.0f);
14419
14420                                 training_fail();
14421
14422                                 //      Instructor warp out.
14423                                 ai_set_mode_warp_out(objp_hit, &Ai_info[Ships[objp_hit->instance].ai_index]);
14424                                 gameseq_post_event( GS_EVENT_PLAYER_WARPOUT_START_FORCED );     //      Force player to warp out.
14425
14426                                 //ship_apply_global_damage( objp_hitter, objp_hit, NULL, 2*(get_shield_strength(objp_hitter) + Ship_info[shipp_hitter->ship_info_index].initial_hull_strength) );
14427                                 //ship_apply_global_damage( objp_hitter, objp_hit, NULL, 1.0f );
14428                         } else if (Missiontime - pp->last_warning_message_time > F1_0*4) {
14429                                 // warning every 4 sec
14430                                 // use NULL as the message sender here since it is the Terran Command persona
14431                                 message_send_builtin_to_player( MESSAGE_INSTRUCTOR_HIT, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_IMMEDIATE, 0, 0, -1, -1);
14432                                 pp->last_warning_message_time = Missiontime;
14433                         }
14434
14435                 // not nice to hit your friends
14436                 } else if (pp->friendly_damage > FRIENDLY_DAMAGE_THRESHOLD * (1.0f + (float) (NUM_SKILL_LEVELS + 1 - Game_skill_level)/3.0f)) {
14437                         process_friendly_hit_message( MESSAGE_HAMMER_SWINE, objp_hit );
14438                         mission_goal_fail_all();
14439                         ai_abort_rearm_request( Player_obj );
14440
14441                         Player_ship->team = TEAM_TRAITOR;
14442
14443                 } else if ((damage > frand()) && (Missiontime - pp->last_warning_message_time > F1_0*4) && (pp->friendly_damage > FRIENDLY_DAMAGE_THRESHOLD)) {
14444                         // no closer than 4 sec intervals
14445                         //      Note: (damage > frand()) added on 12/9/97 by MK.  Since damage is now scaled down for big ships, we could get too
14446                         //      many warnings.  Kind of tedious.  frand() returns a value in 0..1, so this won't affect legit hits.
14447                         process_friendly_hit_message( MESSAGE_OOPS, objp_hit );
14448                         pp->last_warning_message_time = Missiontime;
14449                 }
14450         }
14451 }
14452
14453 //      Maybe make ship with ai_info *aip attack hitter_objnum as a dynamic goal
14454 void maybe_set_dynamic_chase(ai_info *aip, int hitter_objnum)
14455 {
14456         SDL_assert(Ship_info[Ships[aip->shipnum].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER));
14457
14458         // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
14459         if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
14460                 return;
14461         }
14462
14463         // only set as target if can be targeted.
14464         if (awacs_get_level(&Objects[hitter_objnum], &Ships[aip->shipnum], 1) < 1) {
14465                 return;
14466         }
14467
14468         if (aip->target_objnum != hitter_objnum)
14469                 aip->aspect_locked_time = 0.0f;
14470         set_target_objnum(aip, hitter_objnum);
14471         aip->resume_goal_time = Missiontime + i2f(20);  //      Only chase up to 20 seconds.
14472         aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
14473
14474         set_targeted_subsys(aip, NULL, -1);             //      Say not attacking any particular subsystem.
14475
14476         aip->previous_submode = aip->mode;
14477         aip->mode = AIM_CHASE;
14478         aip->submode = SM_ATTACK;
14479 }
14480
14481
14482 //      Return true if *objp has armed an aspect seeking bomb.
14483 //      This function written so a ship with an important bomb to fire will willingly take hits in the face to fire its bomb.
14484 int firing_aspect_seeking_bomb(object *objp)
14485 {
14486         ship    *shipp;
14487         int     bank_index;
14488         ship_weapon     *swp;
14489
14490         shipp = &Ships[objp->instance];
14491
14492         swp = &shipp->weapons;
14493
14494         bank_index = swp->current_secondary_bank;
14495
14496         if (bank_index != -1)
14497                 if (swp->secondary_bank_ammo[bank_index] > 0) {
14498                         if (Weapon_info[swp->secondary_bank_weapons[bank_index]].wi_flags & WIF_BOMB) {
14499                                 if (Weapon_info[swp->secondary_bank_weapons[bank_index]].wi_flags & WIF_HOMING_ASPECT) {
14500                                         return 1;
14501                                 }
14502                         }
14503                 }
14504
14505         return 0;
14506 }
14507
14508 //      *objp collided with big ship *big_objp at global point *collide_pos
14509 //      Make it fly away from the collision point.
14510 // collision_normal is NULL, when a collision is imminent and we just want to bug out.
14511 void big_ship_collide_recover_start(object *objp, object *big_objp, vector *collide_pos, vector *collision_normal)
14512 {
14513         ai_info *aip;
14514
14515         SDL_assert(objp->type == OBJ_SHIP);
14516
14517         aip = &Ai_info[Ships[objp->instance].ai_index];
14518
14519         if (!timestamp_elapsed(aip->big_recover_timestamp) && (aip->ai_flags & AIF_BIG_SHIP_COLLIDE_RECOVER_1))
14520                 return;
14521
14522         //nprintf(("AI", "Ship %s beginning to avoid ship %s at time %7.3f", Ships[objp->instance].ship_name, Ships[big_objp->instance].ship_name, f2fl(Missiontime)));
14523         if (collision_normal) {
14524                 aip->big_recover_timestamp = timestamp(2000);
14525                 aip->big_collision_normal = *collision_normal;
14526         //      nprintf(("AI", " normal\n"));
14527         } else {
14528                 aip->big_recover_timestamp = timestamp(500);
14529         //      nprintf(("AI", " no normal\n"));
14530         }
14531
14532
14533         aip->ai_flags &= ~AIF_BIG_SHIP_COLLIDE_RECOVER_2;
14534         aip->ai_flags |= AIF_BIG_SHIP_COLLIDE_RECOVER_1;
14535
14536 //      vector  out_vec;
14537 //      vm_vec_normalized_dir(&out_vec, &objp->pos, collide_pos);
14538
14539         // big_recover_pos_1 is 100 m out along normal
14540         vector direction;
14541         if (collision_normal) {
14542                 direction = *collision_normal;
14543         } else {
14544                 vm_vec_copy_scale(&direction, &objp->orient.v.fvec, -1.0f);
14545         }
14546         vm_vec_scale_add(&aip->big_recover_pos_1, &objp->pos, &direction, 100.0f);
14547
14548         // go out 200 m from box closest box point
14549         get_world_closest_box_point_with_delta(&aip->big_recover_pos_2, big_objp, &aip->big_recover_pos_1, NULL, 300.0f);
14550
14551         accelerate_ship(aip, 0.0f);
14552 /*
14553         if (vm_vec_dot(collision_normal, &objp->orient.v.fvec) > 0.5f) {
14554 //              vm_vec_scale_add(&aip->big_recover_pos_1, &objp->pos, &out_vec, big_objp->radius/2.0f);
14555 //              vm_vec_scale_add(&aip->big_recover_pos_2, &aip->big_recover_pos_1, &objp->orient.v.uvec, big_objp->radius/2.0f);
14556 //              vm_vec_scale_add(&aip->big_recover_pos_2, &objp->pos, &out_vec, big_objp->radius*2.0f);
14557                 accelerate_ship(aip, 2.0f);
14558         } else {
14559 //              vm_vec_scale_add(&aip->big_recover_pos_1, &objp->pos, &out_vec, big_objp->radius/2.0f);
14560 //              vm_vec_scale_add(&aip->big_recover_pos_2, &aip->big_recover_pos_1, &objp->orient.v.uvec, big_objp->radius/2.0f);
14561                 accelerate_ship(aip, 0.0f);
14562         } */
14563 }
14564
14565 float max_lethality = 0.0f;
14566
14567 void ai_update_lethality(object *ship_obj, object *other_obj, float damage)
14568 {
14569         SDL_assert(ship_obj->type == OBJ_SHIP);
14570         SDL_assert(other_obj->type == OBJ_WEAPON || other_obj->type == OBJ_SHOCKWAVE);
14571         int dont_count = FALSE;
14572
14573         int parent = other_obj->parent;
14574         if (Objects[parent].type == OBJ_SHIP) {
14575                 if (Objects[parent].signature == other_obj->parent_sig) {
14576
14577                         // check damage done to enemy team
14578                         if (Ships[ship_obj->instance].team != Ships[Objects[parent].instance].team) {
14579
14580                                 // other is weapon
14581                                 if (other_obj->type == OBJ_WEAPON) {
14582                                         weapon *wp = &Weapons[other_obj->instance];
14583                                         weapon_info *wif = &Weapon_info[wp->weapon_info_index];
14584
14585                                         // if parent is BIG|HUGE, don't count beam
14586                                         if (Ship_info[Ships[Objects[parent].instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) {
14587                                                 if (wif->wi_flags & WIF_BEAM) {
14588                                                         dont_count = TRUE;
14589                                                 }
14590                                         }
14591                                 }
14592
14593                                 if (!dont_count) {
14594                                         float lethality = 0.025f * damage;      // 2 cyclops (@2000) put you at 100 lethality
14595
14596                                         // increase lethality weapon's parent ship
14597                                         ai_info *aip = &Ai_info[Ships[Objects[parent].instance].ai_index];
14598                                         aip->lethality += lethality;
14599                                         aip->lethality = SDL_min(110.0f, aip->lethality);
14600                                         // if you hit, don;t be less than 0
14601                                         aip->lethality = SDL_max(0.0f, aip->lethality);
14602
14603 //                                      if (aip->lethality > max_lethality) {
14604 //                                              max_lethality = aip->lethality;
14605 //                                              mprintf(("new lethalilty high: %.1f\n", max_lethality));
14606 //                                      }
14607
14608                                         // if parent is player, show his lethality
14609 //                                      if (Objects[parent].flags & OF_PLAYER_SHIP) {
14610 //                                              mprintf(("Player lethality: %.1f\n", aip->lethality));
14611 //                                      }
14612                                 }
14613                         }
14614                 }
14615         }
14616 }
14617
14618
14619 //      Object *objp_ship was hit by either weapon *objp_weapon or collided into by ship hit_objp at point *hitpos.
14620 void ai_ship_hit(object *objp_ship, object *hit_objp, vector *hitpos, int shield_quadrant, vector *hit_normal)
14621 {
14622         int             hitter_objnum = -2;
14623         object  *objp_hitter = NULL;
14624         ship            *shipp;
14625         ai_info *aip, *hitter_aip;
14626
14627         shipp = &Ships[objp_ship->instance];
14628         aip = &Ai_info[shipp->ai_index];
14629
14630         if (objp_ship->flags & OF_PLAYER_SHIP)
14631                 return;
14632
14633         if ((aip->mode == AIM_WARP_OUT) || (aip->mode == AIM_PLAY_DEAD))
14634                 return;
14635
14636         if (hit_objp->type == OBJ_SHIP) {
14637                 //      If the object that this ship collided with is a big ship
14638                 if (Ship_info[Ships[hit_objp->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
14639                         //      And the current object is _not_ a big ship
14640                         if (!(Ship_info[Ships[objp_ship->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
14641                                 //      Recover from hitting a big ship.  Note, if two big ships collide, they just pound away at each other.  Oh well.  Recovery looks dumb and it's very late.
14642                                 big_ship_collide_recover_start(objp_ship, hit_objp, hitpos, hit_normal);
14643                         }
14644                 }
14645         }
14646
14647         if (hit_objp->type == OBJ_WEAPON) {
14648                 //      Make sure the object that fired this weapon is still alive.  If not, abort.
14649                 // SDL_assert(hit_objp->parent >= 0);
14650                 if(hit_objp->parent < 0){
14651                         return;
14652                 }
14653                 if ( hit_objp->parent_sig != Objects[hit_objp->parent].signature ){
14654                         return;
14655                 }
14656
14657                 //      Hit by a protected ship, don't attack it.
14658                 if (Objects[hit_objp->parent].flags & OF_PROTECTED) {
14659                         if ((Ship_info[shipp->ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER)) && (aip->target_objnum == -1)) {
14660                                 if (aip->mode == AIM_CHASE) {
14661                                         if (aip->submode != SM_EVADE_WEAPON) {
14662                                                 aip->mode = AIM_CHASE;
14663                                                 aip->submode = SM_EVADE_WEAPON;
14664                                                 aip->submode_start_time = Missiontime;
14665                                         }
14666                                 } else if (aip->mode != AIM_EVADE_WEAPON) {
14667                                         aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
14668                                         aip->previous_mode = aip->mode;
14669                                         aip->previous_submode = aip->submode;
14670                                         aip->mode = AIM_EVADE_WEAPON;
14671                                         aip->submode = -1;
14672                                         aip->submode_start_time = Missiontime;
14673                                         aip->mode_time = timestamp(MAX_EVADE_TIME);     //      Evade for up to five seconds.
14674                                 }
14675
14676                         }
14677                         return;
14678                 }
14679
14680                 hitter_objnum = hit_objp->parent;
14681                 SDL_assert((hitter_objnum >= 0) && (hitter_objnum < MAX_OBJECTS));
14682                 objp_hitter = &Objects[hitter_objnum];
14683                 maybe_process_friendly_hit(objp_hitter, objp_ship, hit_objp);           //      Deal with player's friendly fire.
14684
14685                 if ( (shipp->team & TEAM_FRIENDLY) && !(Game_mode & GM_MULTIPLAYER) ) {
14686                         ship_maybe_ask_for_help(shipp);
14687                 }
14688         } else if (hit_objp->type == OBJ_SHIP) {
14689                 if (shipp->team == Ships[hit_objp->instance].team)              //      Don't have AI react to collisions between teammates.
14690                         return;
14691                 objp_hitter = hit_objp;
14692                 hitter_objnum = hit_objp-Objects;
14693         } else {
14694                 Int3(); //      Hmm, what kind of object hit this if not weapon or ship?  Get MikeK.
14695                 return;
14696         }
14697
14698         //      Collided into a protected ship, don't attack it.
14699         if (hit_objp->flags & OF_PROTECTED)
14700                 return;
14701
14702         SDL_assert(objp_hitter != NULL);
14703         hitter_aip = &Ai_info[Ships[objp_hitter->instance].ai_index];
14704         hitter_aip->last_hit_target_time = Missiontime;
14705         
14706         // store the object signature of objp_ship into ai_info, since we want to track the last ship hit by 'hitter_objnum'
14707         hitter_aip->last_objsig_hit = objp_ship->signature; 
14708
14709         aip->last_hit_time = Missiontime;
14710
14711         if (aip->ai_flags & (AIF_NO_DYNAMIC | AIF_KAMIKAZE))    //      If not allowed to pursue dynamic objectives, don't evade.  Dumb?  Maybe change. -- MK, 3/15/98
14712                 return;
14713
14714         //      If this ship is awaiting repair, abort!
14715         if (aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED)) {
14716                 ship_info       *sip = &Ship_info[shipp->ship_info_index];
14717
14718                 if (objp_ship->hull_strength/sip->initial_hull_strength < 0.3f) {
14719                         //      No, only abort if hull below a certain level.
14720                         aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP/2);  //      Might request again after 15 seconds.
14721                         if ( !(objp_ship->flags & OF_PLAYER_SHIP) )                                             // mwa -- don't abort rearm for a player
14722                                 ai_abort_rearm_request(objp_ship);
14723                 }
14724         }
14725
14726         //      If firing a bomb, ignore enemy fire so we can gain lock drop the bomb.
14727         //      Only ignore fire if aspect_locked_time > 0.5f, as this means we're in range.
14728         if (firing_aspect_seeking_bomb(objp_ship)) {
14729                 if ((aip->ai_flags & AIF_SEEK_LOCK) && (aip->aspect_locked_time > 0.1f))
14730                         return;
14731         }
14732
14733         //      If in AIM_STRAFE mode and got hit by target, maybe attack turret if appropriate
14734         if (aip->mode == AIM_STRAFE) {
14735                 SDL_assert(hitter_objnum != -2);
14736                 if (aip->target_objnum == hitter_objnum) {
14737                         if ( hit_objp->type == OBJ_WEAPON ) {
14738                                 ai_big_strafe_maybe_attack_turret(objp_ship, hit_objp);
14739                         }
14740                         return;
14741                 }
14742                 else {
14743                                 // AL 11-10-97:
14744                         ;       // do nothing here, we'll attack this hitter if it is a fighter or bomber (this is handled
14745                                 // in code later in this function
14746                 }
14747         }
14748
14749         if (objp_ship == Player_obj)
14750                 return;         //      We don't do AI for the player.
14751
14752         maybe_update_guard_object(objp_ship, objp_hitter);
14753
14754         //      Big ships don't go any further.
14755         if (!(Ship_info[shipp->ship_info_index].flags & SIF_SMALL_SHIP))
14756                 return;
14757
14758         //      If the hitter object is the ignore object, don't attack it.
14759         ship_info       *sip = &Ship_info[shipp->ship_info_index];
14760         if ((is_ignore_object(aip, objp_hitter-Objects)) && (sip->flags & (SIF_BOMBER | SIF_FIGHTER))) {
14761                 if (aip->mode == AIM_NONE) {
14762                         aip->mode = AIM_CHASE;  //      This will cause the ship to move, if not attack.
14763                         aip->submode = SM_EVADE;
14764                 }
14765                 return;
14766         }
14767
14768         //      Maybe abort based on mode.
14769         switch (aip->mode) {
14770         case AIM_CHASE:
14771                 if (aip->submode == SM_ATTACK_FOREVER)
14772                         return;
14773
14774                 if ( hit_objp->type == OBJ_WEAPON ) {
14775                         if ( ai_big_maybe_enter_strafe_mode(objp_ship, OBJ_INDEX(hit_objp), 1) )
14776                                 return;
14777                 }
14778
14779         case AIM_GUARD:
14780                 //      If in guard mode and far away from guard object, don't pursue guy that hit me.
14781                         if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
14782                                 if (vm_vec_dist_quick(&objp_ship->pos, &Objects[aip->guard_objnum].pos) > 500.0f) {
14783                                         return;
14784                                 }
14785                         }
14786         case AIM_STILL:
14787         case AIM_STAY_NEAR:
14788                 // Note: Dealt with above, at very top.  case AIM_PLAY_DEAD:
14789         case AIM_STRAFE:
14790                 break;
14791         case AIM_EVADE_WEAPON:
14792         case AIM_EVADE:
14793         case AIM_GET_BEHIND:
14794         case AIM_AVOID:
14795         case AIM_DOCK:
14796         case AIM_BIGSHIP:
14797         case AIM_PATH:
14798         case AIM_NONE:
14799         case AIM_BAY_DEPART:
14800         case AIM_SENTRYGUN:
14801                 return;
14802         case AIM_BAY_EMERGE:
14803                 // If just leaving the docking bay, don't react to enemy fire... just keep flying away from docking bay
14804                 if ( (Missiontime - aip->submode_start_time) < 5*F1_0 ) {
14805                         return;
14806                 }
14807                 break;
14808         case AIM_WAYPOINTS:
14809                 if (sip->flags & (SIF_FIGHTER | SIF_BOMBER))
14810                         break;
14811                 else
14812                         return;
14813                 break;
14814         case AIM_SAFETY:
14815                 if ((aip->submode != AISS_1) || (Missiontime - aip->submode_start_time > i2f(1))) {
14816                         aip->submode = AISS_1;
14817                         aip->submode_start_time = Missiontime;
14818                 }
14819                 return;
14820                 break;
14821         case AIM_WARP_OUT:
14822                 return;
14823                 break;
14824         default:
14825                 Int3(); //      Bogus mode!
14826         }
14827
14828         if (timestamp_elapsed(aip->ok_to_target_timestamp))
14829                 aip->ai_flags &= ~AIF_FORMATION;                        //      If flying in formation, bug out!
14830
14831         aip->hitter_objnum = hitter_objnum;
14832         aip->hitter_signature = Objects[hitter_objnum].signature;
14833
14834         //      If the hitter is not on the same team as the hittee, do some stuff.
14835         if (shipp->team != Ships[objp_hitter->instance].team) {
14836                 //nprintf(("AI", "Object %i attacking %i, who just hit him!\n", objp_ship-Objects, hitter_objnum));
14837
14838                 if ((hitter_objnum != aip->target_objnum) && (sip->flags & (SIF_FIGHTER | SIF_BOMBER))) {
14839                         maybe_set_dynamic_chase(aip, hitter_objnum);
14840                         maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14841                 } else {
14842                         if ((aip->mode == AIM_CHASE) && ((objp_ship->hull_strength/sip->initial_hull_strength > 0.9f) || (get_shield_strength(objp_ship)/sip->shields > 0.8f))) {
14843                                 switch (aip->submode) {
14844                                 case SM_ATTACK:
14845                                 case SM_SUPER_ATTACK:
14846                                 case SM_GET_AWAY:
14847                                         break;
14848                                 default:
14849                                         if (sip->flags & (SIF_FIGHTER | SIF_BOMBER)) {
14850                                                 maybe_set_dynamic_chase(aip, hitter_objnum);
14851                                         }
14852                                         maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14853                                         break;
14854                                 }
14855                         } else if (aip->mode == AIM_CHASE) {
14856                                 switch (aip->submode) {
14857                                 case SM_ATTACK:
14858                                         aip->submode = SM_EVADE;
14859                                         aip->submode_start_time = Missiontime;
14860                                         break;
14861                                 case SM_SUPER_ATTACK:
14862                                         if (Missiontime - aip->submode_start_time > i2f(1)) {
14863                                                 aip->submode = SM_EVADE;
14864                                                 aip->submode_start_time = Missiontime;
14865                                         }
14866                                         break;
14867                                 case SM_EVADE_BRAKE:
14868                                         break;
14869                                 case SM_EVADE_SQUIGGLE:
14870                                         aip->submode = SM_EVADE;
14871                                         aip->submode_start_time = Missiontime;
14872                                         break;
14873                                 default:
14874                                         if (sip->flags & (SIF_BOMBER | SIF_FIGHTER)) {
14875                                                 maybe_set_dynamic_chase(aip, hitter_objnum);
14876                                                 maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14877                                         }
14878
14879                                         break;
14880                                 }
14881                         } else {
14882                                 // AL 3-15-98: Prevent escape pods from entering chase mode
14883                                 if ( (sip->flags & (SIF_BOMBER | SIF_FIGHTER)) ) {
14884                                         maybe_set_dynamic_chase(aip, hitter_objnum);
14885                                 }
14886                                 maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14887                         }
14888                 }
14889         }
14890 }
14891
14892 //      Ship shipnum has been destroyed.
14893 //      Cleanup.
14894 // the parameter 'method' is used to tell is this ship was destroyed or it departed normally.
14895 // This function will get called in either case, and there are things that should be done if
14896 // the ship actually gets destroyed which shouldn't get done if it departed.
14897 void ai_ship_destroy(int shipnum, int method)
14898 {
14899         int             objnum;
14900         object  *other_objp;
14901         ship            *shipp;
14902         ship_obj        *so;
14903         ai_info *dead_aip;
14904
14905         SDL_assert((shipnum >= 0) && (shipnum < MAX_SHIPS));
14906         objnum = Ships[shipnum].objnum;
14907         dead_aip = &Ai_info[Ships[shipnum].ai_index];
14908
14909         // if I was getting repaired, or awaiting repair, then cleanup the repair mode.  When awaiting repair, the dock_objnum
14910         // is -1.  When the support ship is on the way, the dock_objnum >= 0 (points to support ship).
14911         if ( dead_aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED) ) {
14912                 if ( dead_aip->dock_objnum >= 0 )
14913                         ai_do_objects_repairing_stuff( &Objects[objnum], &Objects[dead_aip->dock_objnum], REPAIR_INFO_END);
14914                 else
14915                         ai_do_objects_repairing_stuff( &Objects[objnum], NULL, REPAIR_INFO_END );
14916         }
14917
14918         //      For all objects that had this ship as a target, wipe it out, forcing find of a new enemy.
14919         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
14920                 other_objp = &Objects[so->objnum];
14921                 SDL_assert(other_objp->instance != -1);
14922
14923                 shipp = &Ships[other_objp->instance];
14924                 SDL_assert(shipp->ai_index != -1);
14925
14926                 ai_info *aip = &Ai_info[shipp->ai_index];
14927
14928                 // MWA 2/11/98
14929                 // code commented out below is taken care of in ai_cleanup_dock_mode when gets called when the
14930                 // support ship starts it's death roll.
14931
14932                 //      If the destroyed ship was on its way to repair the current ship
14933                 if (aip->dock_objnum == objnum) {
14934
14935                         // clean up the flags for any kind of docking mode.  If aip was part of a goal of dock/undock
14936                         // then it will get cleaned up by the goal code.
14937                         ai_do_objects_undocked_stuff( other_objp, NULL );
14938
14939                         if ( aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED) ) {
14940                                 int abort_reason;
14941                                 if ( method == SEF_DEPARTED ) {
14942                                         abort_reason = REPAIR_INFO_ABORT;
14943                                 } else {
14944                                         abort_reason = REPAIR_INFO_KILLED;
14945                                 }
14946                                 ai_do_objects_repairing_stuff( other_objp, NULL, abort_reason );
14947                         }
14948                 }
14949
14950                 if (aip->target_objnum == objnum) {
14951                         set_target_objnum(aip, -1);
14952                         //      If this ship had a dynamic goal of chasing the dead ship, clear the dynamic goal.
14953                         if (aip->resume_goal_time != -1)
14954                                 aip->active_goal = AI_GOAL_NONE;
14955                 }
14956
14957                 if (aip->goal_objnum == objnum) {
14958                         aip->goal_objnum = -1;
14959                         aip->goal_signature = -1;
14960                 }
14961
14962                 if (aip->guard_objnum == objnum) {
14963                         aip->guard_objnum = -1;
14964                         aip->guard_signature = -1;
14965                 }
14966
14967                 if ((aip->guard_wingnum != -1) && (aip->guard_wingnum == Ai_info[Ships[Objects[objnum].instance].ai_index].wing)) {
14968                         if (aip->guard_wingnum != aip->wing)
14969                                 ai_set_guard_wing(other_objp, aip->guard_wingnum);
14970                 }
14971
14972                 if (aip->hitter_objnum == objnum)
14973                         aip->hitter_objnum = -1;
14974
14975         }
14976
14977 }
14978
14979 /*
14980 //      Interface function to goals code.
14981 //      Make object *objp fly to point *vp and warp out.
14982 void ai_warp_out(object *objp, vector *vp)
14983 {
14984         ai_info *aip;
14985
14986         aip = &Ai_info[Ships[objp->instance].ai_index];
14987
14988         if (aip->mode != AIM_WARP_OUT) {
14989                 ai_set_mode_warp_out(objp, aip);
14990         }
14991         float   dist;
14992         float   dot;
14993         vector  v2v;
14994         ai_info *aip;
14995
14996         dist = vm_vec_normalized_dir(&v2v, vp, &objp->pos);
14997
14998         if (dist < objp->radius + 5.0f) {
14999
15000                 // Start the warp out effect 
15001                 shipfx_warpout_start(objp);
15002
15003         } else {
15004                 dot = vm_vec_dot(&objp->orient.v.fvec, &v2v);
15005
15006                 aip = &Ai_info[Ships[objp->instance].ai_index];
15007
15008                 if (dist > 500.0f)
15009                         accelerate_ship(aip, 1.0f);
15010                 else
15011                         accelerate_ship(aip, (3*dot + 1.0f)/4.0f);
15012
15013                 turn_towards_point(objp, vp, NULL, 0.0f);
15014         }
15015 }
15016 */
15017
15018
15019 //      Do stuff at start of deathroll.
15020 void ai_deathroll_start(object *ship_obj)
15021 {
15022         ai_info *aip;
15023         ship            *shipp, *other_ship;
15024
15025         shipp = &Ships[ship_obj->instance];
15026         aip = &Ai_info[shipp->ai_index];
15027
15028         // mark object we are docked with so we can do damage and separate during deathroll
15029         // keep dock_objnum_when_dead from being changed if already set (only allow to be set when -1)
15030         if (Ships[ship_obj->instance].dock_objnum_when_dead == -1) {
15031                 Ships[ship_obj->instance].dock_objnum_when_dead = aip->dock_objnum;
15032                 // set other_ship dock_objnum_when_dead, if other_ship exits.
15033                 if (Ships[ship_obj->instance].dock_objnum_when_dead != -1) {
15034                         other_ship = &Ships[Objects[aip->dock_objnum].instance];
15035                         other_ship->dock_objnum_when_dead = shipp->objnum;
15036                 }
15037         }
15038
15039         ai_cleanup_dock_mode(aip, shipp);
15040
15041         aip->mode = AIM_NONE;
15042 }
15043
15044 //      Object *requester_objp tells rearm ship to abort rearm.
15045 //      Returns true if it succeeded, else false.
15046 //      To succeed means you were previously rearming.
15047 int ai_abort_rearm_request(object *requester_objp)
15048 {
15049         ship            *requester_shipp;
15050         ai_info *requester_aip;
15051
15052         SDL_assert(requester_objp->type == OBJ_SHIP);
15053         if(requester_objp->type != OBJ_SHIP){
15054                 return 0;
15055         }
15056         SDL_assert((requester_objp->instance >= 0) && (requester_objp->instance < MAX_SHIPS));  
15057         if((requester_objp->instance < 0) || (requester_objp->instance >= MAX_SHIPS)){
15058                 return 0;
15059         }
15060         requester_shipp = &Ships[requester_objp->instance];
15061         SDL_assert((requester_shipp->ai_index >= 0) && (requester_shipp->ai_index < MAX_AI_INFO));              
15062         if((requester_shipp->ai_index < 0) || (requester_shipp->ai_index >= MAX_AI_INFO)){
15063                 return 0;
15064         }       
15065         requester_aip = &Ai_info[requester_shipp->ai_index];
15066         
15067         if (requester_aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED)){
15068
15069                 // dock_objnum is always valid once a rearm repair has been requested.  It points to the
15070                 // ship that is coming to repair me.
15071                 if (requester_aip->dock_objnum != -1) {
15072                         object  *repair_objp;
15073                         ai_info *repair_aip;
15074
15075                         repair_objp = &Objects[requester_aip->dock_objnum];
15076                         repair_aip = &Ai_info[Ships[repair_objp->instance].ai_index];
15077
15078                         //      Make sure signatures match.  This prevents nasty bugs in which an object
15079                         //      that was repairing another is destroyed and is replaced by another ship
15080                         //      before this code comes around.
15081                         if (repair_objp->signature == requester_aip->dock_signature) {
15082
15083                                 SDL_assert( repair_objp->type == OBJ_SHIP );
15084
15085                                 // if support ship is in the process of undocking, don't do anything.
15086                                 if ( repair_aip->submode < AIS_UNDOCK_0 ) {
15087                                         ai_do_objects_repairing_stuff( requester_objp, repair_objp, REPAIR_INFO_ABORT );
15088
15089                                         if ( repair_aip->submode == AIS_DOCK_4 )
15090                                                 repair_aip->submode = AIS_UNDOCK_0;
15091                                         else
15092                                                 repair_aip->submode = AIS_UNDOCK_3;
15093
15094                                         repair_aip->submode_start_time = Missiontime;
15095                                 } else {
15096                                         nprintf(("AI", "Not aborting rearm since already undocking\n"));
15097                                 }
15098                         }
15099                 } else {
15100                         // setting these flags is the safe things to do.  There may not be a corresponding repair
15101                         // ship for this guys since a repair ship may be currently repairing someone else.
15102                         ai_do_objects_repairing_stuff( requester_objp, NULL, REPAIR_INFO_ABORT );
15103
15104                         // try and remove this guy from an arriving support ship.
15105                         mission_remove_scheduled_repair(requester_objp);
15106                 }
15107
15108                 return 1;
15109         } else if ( requester_aip->ai_flags & AIF_REPAIRING ) {
15110                 // a support ship can request to abort when he is told to do something else (like warp out).
15111                 // see if this support ships goal_objnum is valid.  If so, then issue this ai_abort comment
15112                 // for the ship that he is enroute to repair
15113                 if ( requester_aip->goal_objnum != -1 ) {
15114                         int val;
15115
15116                         val = ai_abort_rearm_request( &Objects[requester_aip->goal_objnum] );
15117                         return val;
15118                 }
15119         }
15120
15121         return 0;
15122 }
15123
15124 // function which gets called from ai-issue_rearm_request and from code in missionparse.cpp
15125 // to actually issue the rearm goal (support_obj to rearm requester_obj);
15126 void ai_add_rearm_goal( object *requester_objp, object *support_objp )
15127 {
15128         ship *support_shipp, *requester_shipp;
15129         ai_info *support_aip, *requester_aip;
15130
15131         support_shipp = &Ships[support_objp->instance];
15132         requester_shipp = &Ships[requester_objp->instance];
15133         requester_aip = &Ai_info[requester_shipp->ai_index];
15134
15135         SDL_assert( support_shipp->ai_index != -1 );
15136         support_aip = &Ai_info[support_shipp->ai_index];
15137
15138         // if the requester is a player object, issue the order as the squadmate messaging code does.  Doing so
15139         // ensures that the player get a higher priority!
15140         requester_aip->ai_flags |= AIF_AWAITING_REPAIR; //      Tell that I'm awaiting repair.
15141         if ( requester_objp->flags & OF_PLAYER_SHIP )
15142                 ai_add_ship_goal_player( AIG_TYPE_PLAYER_SHIP, AI_GOAL_REARM_REPAIR, -1, requester_shipp->ship_name, support_aip );
15143         else
15144                 ai_add_goal_ship_internal( support_aip, AI_GOAL_REARM_REPAIR, requester_shipp->ship_name, -1, -1 );
15145
15146 }
15147
15148 //      Object *requester_objp requests rearming.
15149 //      Returns objnum of ship coming to repair requester on success
15150 //      Success means you found someone to rearm you and you weren't previously rearming.
15151 int ai_issue_rearm_request(object *requester_objp)
15152 {
15153         object  *objp;
15154         ship            *requester_shipp;
15155         ai_info *requester_aip;
15156
15157         SDL_assert(requester_objp->type == OBJ_SHIP);
15158         SDL_assert((requester_objp->instance >= 0) && (requester_objp->instance < MAX_SHIPS));
15159         requester_shipp = &Ships[requester_objp->instance];
15160         SDL_assert((requester_shipp->ai_index >= 0) && (requester_shipp->ai_index < MAX_AI_INFO));
15161         requester_aip = &Ai_info[requester_shipp->ai_index];
15162         
15163         //      Make sure not already awaiting repair.
15164         if (requester_aip->ai_flags & AIF_AWAITING_REPAIR) {
15165                 nprintf(("AI", "Ship %s already awaiting rearm by ship %s.\n", requester_shipp->ship_name, &Ships[Objects[requester_aip->dock_objnum].instance].ship_name));    
15166                 return -1;
15167         }
15168
15169         if ( !is_support_allowed(requester_objp) )
15170                 return -1;
15171
15172         //nprintf(("AI", "Ship %s requesting rearming.\n", requester_shipp->ship_name));
15173         requester_aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP);  //      Might request again after this much time.
15174
15175         // call ship_find_repair_ship to get a support ship.  If none is found, then we will warp one in.  This
15176         // function will return the next available ship which can repair requester
15177         objp = ship_find_repair_ship( requester_objp );
15178         ai_do_objects_repairing_stuff( requester_objp, objp, REPAIR_INFO_QUEUE );
15179         if ( objp ) {
15180
15181                 // MWA 5/14/98 -- moved next item into the ai_do_objects_repairing_stuff function so that clients
15182                 // would properly update their hud support view
15183                 //ai_add_rearm_goal( requester_objp, objp );
15184                 return OBJ_INDEX(objp);
15185
15186         } else {
15187                 // call to warp in repair ship!!!!  for now, warp in any number of ships needed.  Should cap it to
15188                 // some reasonable max (or let support ships warp out).  We should assume here that ship_find_repair_ship()
15189                 // would have returned a valid object if there are too many support ships already in the mission
15190                 mission_warp_in_support_ship( requester_objp );
15191
15192                 return -1;
15193         }
15194
15195 }
15196
15197 // make objp rearm and repair goal_objp
15198 void ai_rearm_repair( object *objp, object  *goal_objp, int priority, int docker_index, int dockee_index )
15199 {
15200         ai_info *aip, *goal_aip;
15201
15202         aip = &Ai_info[Ships[objp->instance].ai_index];
15203         aip->goal_objnum = goal_objp-Objects;
15204
15205         // nprintf(("AI", "Ship %s preparing to rearm ship %s.\n", shipp->ship_name, requester_shipp->ship_name));
15206
15207         ai_dock_with_object(objp, goal_objp, priority, AIDO_DOCK, docker_index, dockee_index);
15208         aip->ai_flags |= AIF_REPAIRING;                                         //      Tell that repair guy is busy trying to repair someone.
15209
15210         goal_aip = &Ai_info[Ships[goal_objp->instance].ai_index];
15211         goal_aip->dock_objnum = objp-Objects;           //      Tell which object is coming to repair.
15212         goal_aip->dock_signature = objp->signature;
15213
15214         ai_do_objects_repairing_stuff( goal_objp, objp, REPAIR_INFO_ONWAY );
15215
15216         goal_aip->abort_rearm_timestamp = timestamp(NEXT_REARM_TIMESTAMP*3/2);
15217 }
15218
15219 // Given a dockee object and the index of the dockbay for that object (ie the dockbay index
15220 // into polymodel->dockbays[] for the model associated with the object), return the index
15221 // of a path_num associated with than dockbay (this is an index into polymodel->paths[])
15222 int ai_return_path_num_from_dockbay(object *dockee_objp, int dockbay_index)
15223 {
15224         if ( dockbay_index < 0 || dockee_objp == NULL ) {
15225                 Int3();         // should never happen
15226                 return -1;
15227         }
15228
15229         if ( dockee_objp->type == OBJ_SHIP ) {
15230                 int                     path_num;
15231                 polymodel       *pm;
15232
15233                 pm = model_get( Ships[dockee_objp->instance].modelnum );
15234
15235                 // sanity checks
15236                 SDL_assert(pm->n_docks > dockbay_index);
15237                 SDL_assert(pm->docking_bays[dockbay_index].num_spline_paths > 0);
15238                 SDL_assert(pm->docking_bays[dockbay_index].splines != NULL);
15239                 if(pm->n_docks <= dockbay_index){
15240                         return -1;
15241                 }
15242                 if(pm->docking_bays[dockbay_index].num_spline_paths <= 0){
15243                         return -1;
15244                 }
15245                 if(pm->docking_bays[dockbay_index].splines == NULL){
15246                         return -1;
15247                 }
15248
15249                 // We only need to return one path for the dockbay, so return the first
15250                 path_num = pm->docking_bays[dockbay_index].splines[0];
15251                 return path_num;
15252         } else {
15253                 return -1;
15254         }
15255 }
15256
15257 //      Actually go ahead and fire the synaptics.
15258 void cheat_fire_synaptic(object *objp, ship *shipp, ai_info *aip)
15259 {
15260         ship_weapon     *swp;
15261         swp = &shipp->weapons;
15262         int     current_bank = swp->current_secondary_bank;
15263
15264         ai_select_secondary_weapon(objp, swp, WIF_SPAWN, 0);
15265         if (timestamp_elapsed(swp->next_secondary_fire_stamp[current_bank])) {
15266                 if (ship_fire_secondary(objp)) {
15267                         nprintf(("AI", "ship %s cheat fired synaptic!\n", shipp->ship_name));
15268                         swp->next_secondary_fire_stamp[current_bank] = timestamp(2500);
15269                 }
15270         }
15271 }
15272
15273 //      For the subspace mission (sm3-09a)
15274 //              for delta wing
15275 //                      if they're sufficiently far into the mission
15276 //                              if they're near one or more enemies
15277 //                                      every so often
15278 //                                              fire a synaptic if they have one.
15279 void maybe_cheat_fire_synaptic(object *objp, ai_info *aip)
15280 {
15281         //      Only do in subspace missions.
15282         if ( The_mission.flags & MISSION_FLAG_SUBSPACE )        {
15283                 ship    *shipp;
15284                 int     num, time;
15285
15286                 shipp = &Ships[objp->instance];
15287
15288                 if (!(SDL_strncasecmp(shipp->ship_name, NOX("delta"), 5))) {
15289                         num = shipp->ship_name[6] - '1';
15290
15291                         if ((num >= 0) && (num <= 3)) {
15292                                 time = Missiontime >> 16;       //      Convert to seconds.
15293
15294                                 time -= 2*60;   //      Subtract off two minutes.
15295
15296                                 if (time > 0) {
15297                                         int modulus = 17 + num*3;
15298
15299                                         if ((time % modulus) < 2) {
15300                                                 int count = num_nearby_fighters(get_enemy_team_mask(OBJ_INDEX(objp)), &objp->pos, 1500.0f);
15301
15302                                                 if (count > 0) {
15303                                                         cheat_fire_synaptic(objp, shipp, aip);
15304                                                 }
15305                                         }
15306                                 }
15307                         }
15308                 }
15309         }
15310
15311 }
15312