]> icculus.org git repositories - taylor/freespace2.git/blob - src/ship/aicode.cpp
platform and pstypes cleanup:
[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 (int 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                 int     rval;
1112
1113                 if ((rval = setjmp(parse_abort)) != 0) {
1114                         Error(LOCATION, "Error parsing 'ai.tbl'\r\nError code = %i.\r\n", rval);
1115                 } else {                        
1116                         parse_aitbl();                  
1117                 }
1118
1119                 ai_inited = 1;
1120         }
1121
1122         init_semirand();
1123         
1124         ai_level_init();
1125 }
1126
1127 // this inits the ai.  You should be able to call this between
1128 // levels to reset everything.
1129 void ai_level_init()
1130 {
1131         int i;
1132  
1133         // Do the stuff to reset all ai stuff here
1134         for (i=0; i<MAX_AI_INFO ; i++) {
1135                 Ai_info[i].shipnum = -1;
1136         }
1137         Ai_goal_signature = 0;
1138         Ai_friendly_rearm_timestamp = timestamp(-1);
1139         Ai_hostile_rearm_timestamp = timestamp(-1);
1140         Ai_neutral_rearm_timestamp = timestamp(-1);
1141         Ai_traitor_rearm_timestamp = timestamp(-1);
1142
1143         // clear out the stuff needed for AI firing powerful secondary weapons
1144         ai_init_secondary_info();
1145
1146         Ai_last_arrive_path=0;
1147 }
1148
1149 // BEGIN STEALTH
1150 // -----------------------------------------------------------------------------
1151 // Check if object is a stealth ship
1152 int is_object_stealth_ship(object* objp)
1153 {
1154         if (objp->type == OBJ_SHIP) {
1155                 if (Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_STEALTH) {
1156                         return 1;
1157                 }
1158         }
1159
1160         // not stealth ship
1161         return 0;
1162 }
1163
1164 // -----------------------------------------------------------------------------
1165 // Init necessary ai info for new stealth target
1166 void init_ai_stealth_info(ai_info *aip, object *stealth_objp)
1167 {
1168         SDL_assert(is_object_stealth_ship(stealth_objp));
1169
1170         // set necessary ai info for new stealth target
1171         aip->stealth_last_pos = stealth_objp->pos;
1172         aip->stealth_velocity = stealth_objp->phys_info.vel;
1173         aip->stealth_last_visible_stamp = timestamp();
1174 }
1175
1176 // -----------------------------------------------------------------------------
1177 // Check whether Pl_objp can see a stealth ship object
1178 #define STEALTH_INVISIBLE                       0
1179 #define STEALTH_VISIBLE                         1
1180 #define STEALTH_FULLY_TARGETABLE        2
1181
1182 float get_skill_stealth_dist_scaler()
1183 {
1184         // return dist scaler based on skill level
1185         switch (Game_skill_level) {
1186         case 0: // very easy
1187                 return 0.65f;
1188
1189         case 1: // easy
1190                 return 0.9f;
1191
1192         case 2: // medium
1193                 return 1.0f;
1194
1195         case 3: // hard
1196                 return 1.1f;
1197
1198         case 4: // insane
1199                 return 1.3f;
1200
1201         default:
1202                 Int3();
1203         }
1204
1205         return 1.0f;
1206 }
1207
1208 float get_skill_stealth_dot_scaler()
1209 {
1210         // return multiplier on dot based on skill level
1211         switch (Game_skill_level) {
1212         case 0: // very easy
1213                 return 1.3f;
1214
1215         case 1: // easy
1216                 return 1.1f;
1217
1218         case 2: // medium
1219                 return 1.0f;
1220
1221         case 3: // hard
1222                 return 0.9f;
1223
1224         case 4: // insane
1225                 return 0.7f;
1226
1227         default:
1228                 Int3();
1229         }
1230
1231         return 1.0f;
1232 }
1233
1234 int ai_is_stealth_visible(object *viewer_objp, object *stealth_objp)
1235 {
1236         ship *shipp;
1237         vector vec_to_stealth;
1238         float dot_to_stealth, dist_to_stealth, max_stealth_dist;
1239
1240         SDL_assert(stealth_objp->type == OBJ_SHIP);
1241         shipp = &Ships[stealth_objp->instance];
1242         SDL_assert(viewer_objp->type == OBJ_SHIP);
1243
1244         // check if stealth ship
1245         SDL_assert(Ship_info[shipp->ship_info_index].flags & SIF_STEALTH);
1246
1247         // check if in neb and below awac level for visible
1248         if ( !ship_is_visible_by_team(stealth_objp->instance, Ships[viewer_objp->instance].team) ) {
1249                 vm_vec_sub(&vec_to_stealth, &stealth_objp->pos, &viewer_objp->pos);
1250                 dist_to_stealth = vm_vec_mag_quick(&vec_to_stealth);
1251                 dot_to_stealth = vm_vec_dotprod(&viewer_objp->orient.v.fvec, &vec_to_stealth) / dist_to_stealth;
1252
1253                 // get max dist at which stealth is visible
1254                 max_stealth_dist = get_skill_stealth_dist_scaler() * STEALTH_MAX_VIEW_DIST;
1255
1256                 // now check if within view frustrum
1257                 float needed_dot_to_stealth;
1258                 if (dist_to_stealth < 100) {
1259                         needed_dot_to_stealth = 0.0f;
1260                 } else {
1261                         needed_dot_to_stealth = get_skill_stealth_dot_scaler() * float(STEALTH_VIEW_CONE_DOT) * (dist_to_stealth / max_stealth_dist);
1262                 }
1263                 if (dot_to_stealth > needed_dot_to_stealth) {
1264                         if (dist_to_stealth < max_stealth_dist) {
1265                                 return STEALTH_VISIBLE;
1266                         }
1267                 }
1268
1269                 // not within frustrum
1270                 return STEALTH_INVISIBLE;
1271         }
1272
1273         // visible by awacs level
1274         return STEALTH_FULLY_TARGETABLE;
1275 }
1276
1277 // END STEALTH
1278
1279 //      Compute dot product of direction vector and forward vector.
1280 //      Direction vector is vector from one object to other object.
1281 //      Forward vector is the forward vector of the ship.
1282 //      If from_dot == NULL, don't fill it in.
1283 float compute_dots(object *objp, object *other_objp, float *to_dot, float *from_dot)
1284 {
1285         vector  v2o;
1286         float           dist;
1287
1288         dist = vm_vec_normalized_dir(&v2o, &other_objp->pos, &objp->pos);
1289
1290         *to_dot = vm_vec_dot(&objp->orient.v.fvec, &v2o);
1291
1292         if (from_dot != NULL)
1293                 *from_dot = - vm_vec_dot(&other_objp->orient.v.fvec, &v2o);
1294
1295         return dist;
1296 }
1297
1298 // -----------------------------------------------------------------------------
1299 // update estimated stealth info
1300 // this is a "cheat" update
1301 // error increases with time not seen, true distance away, dot to enemey
1302 // this is done only if we can not see the stealth target
1303 // need to infer its position either by weapon fire pos or last know pos
1304 void update_ai_stealth_info_with_error(ai_info *aip/*, int no_error*/)
1305 {
1306 //      object *ship;
1307         object *stealth_objp;
1308         /*
1309         float error_time_mult, error_dist_mult, error_dot_mult, error_mult;
1310         float pos_error, vel_error;
1311         vector error_vec, vec_to_stealth;
1312         float dist_to_stealth, dot_to_stealth;
1313         float delta_time, delta_capped;
1314         */
1315
1316         // make sure I am targeting a stealth ship
1317         SDL_assert( is_object_stealth_ship(&Objects[aip->target_objnum]) );
1318         stealth_objp = &Objects[aip->target_objnum];
1319
1320         // my_ship
1321 //      ship = &Objects[Ships[aip->shipnum].objnum];
1322
1323         // if update is due to weapon fire, get exact stealth position
1324 //      if (no_error) {
1325         aip->stealth_last_pos = stealth_objp->pos;
1326         aip->stealth_velocity = stealth_objp->phys_info.vel;
1327         aip->stealth_last_visible_stamp = timestamp();
1328 //              return;
1329 //      }
1330 /*
1331         // get time since last seen
1332         delta_time = 0.001f * (timestamp() - aip->stealth_last_visible_stamp);
1333
1334         // we don't want our "cheat" guess to more off than what we would get from extrapolating from last visible
1335         // only update if stealth info is "old"
1336         if ( (delta_time) < 0.5 ) {
1337                 return;
1338         }
1339
1340         // find vec_to_stealth and dist
1341         vm_vec_sub(&vec_to_stealth, &stealth_objp->pos, &ship->pos);
1342         dist_to_stealth = vm_vec_normalize_quick(&vec_to_stealth);
1343         dot_to_stealth = vm_vec_dotprod(&vec_to_stealth, &ship->orient.v.fvec);
1344
1345         // put cap on time
1346         delta_capped = delta_time;
1347         if (delta_time > 5.0) {
1348                 delta_capped = 5.0f;
1349         }
1350
1351         // erorr_time_mult (for 0-5) -> (1-6)
1352         error_time_mult = (1.0f + delta_capped);
1353
1354         // error_dot_mult (-1 to 1) -> (1-3)
1355         error_dot_mult = (2 - dot_to_stealth);
1356
1357         // error_dist_mult (0-1000+) -> (1-4)
1358         error_dist_mult = dist_to_stealth * 4.0f * 0.001f;
1359         if (error_dist_mult < 1) {
1360                 error_dist_mult = 1.0f;
1361         } else if (error_dist_mult > 4) {
1362                 error_dist_mult = 4.0f;
1363         }
1364
1365         // multiply error out
1366         error_mult = error_time_mult * error_dot_mult * error_dist_mult;
1367
1368         float base_pos_error = 10;
1369         float base_vel_error = 2;
1370
1371         // find the position and velocity error magnitude;
1372         pos_error = base_pos_error * error_mult;
1373         vel_error = base_vel_error * error_mult;
1374
1375         // get an error that changes slowly over time
1376         static_randvec( ((int)aip ^ (Missiontime >> 18)) & 7, &error_vec);
1377         vm_vec_zero(&error_vec);
1378
1379         // update pos and vel with error
1380         vm_vec_scale_add(&aip->stealth_velocity, &stealth_objp->phys_info.vel, &error_vec, vel_error);
1381
1382         // revise last "known" position to arrive at last pos with given error
1383         vm_vec_scale_add(&aip->stealth_last_pos, &stealth_objp->pos, &error_vec, pos_error);
1384         vm_vec_scale_add2(&aip->stealth_last_pos, &aip->stealth_velocity, -(0.001f * delta_time));
1385         */
1386 }
1387
1388 //      Update danger_weapon_objnum and signature in ai_info to say this weapon is to be avoided.
1389 void ai_update_danger_weapon(int attacked_objnum, int weapon_objnum)
1390 {
1391         object  *objp, *weapon_objp;
1392         ai_info *aip;
1393         float           old_dist, new_dist;
1394         float           old_dot, new_dot;
1395         object  *old_weapon_objp = NULL;
1396
1397         if ((attacked_objnum == -1) || (weapon_objnum == -1)) {
1398                 return;
1399         }
1400
1401         objp = &Objects[attacked_objnum];
1402
1403         // AL 2-24-98: If this isn't a ship, we don't need to worry about updating weapon_objnum (ie it would be
1404         //                                      an asteroid or bomb).
1405         if ( objp->type != OBJ_SHIP ) {
1406                 return;
1407         }
1408
1409         weapon_objp = &Objects[weapon_objnum];
1410
1411         aip = &Ai_info[Ships[objp->instance].ai_index];
1412
1413         // if my taraget is a stealth ship and is not visible
1414         if (aip->target_objnum >= 0) {
1415                 if ( is_object_stealth_ship(&Objects[aip->target_objnum]) ) {
1416                         if ( ai_is_stealth_visible(objp, &Objects[aip->target_objnum]) == STEALTH_INVISIBLE ) {
1417                                 // and the weapon is coming from that stealth ship
1418                                 if (weapon_objp->parent == aip->target_objnum) {
1419                                         // update my position estimate for stealth ship
1420                                         update_ai_stealth_info_with_error(aip/*, 1*/);
1421                                 }
1422                         }
1423                 }
1424         }
1425
1426         if (aip->danger_weapon_objnum != -1) {
1427                 old_weapon_objp = &Objects[aip->danger_weapon_objnum];
1428                 if ((old_weapon_objp->type == OBJ_WEAPON) && (old_weapon_objp->signature == aip->danger_weapon_signature)) {
1429                         ;
1430                 } else {
1431                         aip->danger_weapon_objnum = -1;
1432                 }
1433         }
1434
1435         new_dist = compute_dots(weapon_objp, objp, &new_dot, NULL);
1436
1437         if (aip->danger_weapon_objnum == -1) {
1438                 if (new_dist < 1500.0f) {
1439                         if (new_dot > 0.5f) {
1440                                 aip->danger_weapon_objnum = weapon_objnum;
1441                                 aip->danger_weapon_signature = weapon_objp->signature;
1442                         }
1443                 }
1444         } else {
1445                 SDL_assert(old_weapon_objp != NULL);
1446                 old_dist = compute_dots(old_weapon_objp, objp, &old_dot, NULL);
1447         
1448                 if (old_dot < 0.5f) {
1449                         aip->danger_weapon_objnum = -1;
1450                         old_dist = 9999.9f;
1451                 }
1452
1453                 if ((new_dot > 0.5f) && (new_dot > old_dot-0.01f)) {
1454                         if (new_dist < old_dist) {
1455                                 aip->danger_weapon_objnum = weapon_objnum;
1456                                 aip->danger_weapon_signature = weapon_objp->signature;
1457                         }
1458                 }
1459         }
1460 }
1461
1462 //      If rvec != NULL, use it to match bank by calling vm_matrix_interpolate.
1463 //      (rvec defaults to NULL)
1464 void ai_turn_towards_vector(vector *dest, object *objp, 
1465                                                                          float frametime, float turn_time, vector *slide_vec, vector *rel_pos, float bank_override, int flags, vector *rvec)
1466 {
1467         //matrix        goal_orient;
1468         matrix  curr_orient;
1469         vector  vel_in, vel_out, desired_fvec, src;
1470         float           delta_time;
1471         physics_info    *pip;
1472         vector  vel_limit, acc_limit;
1473         float           delta_bank;
1474
1475         //      Don't allow a ship to turn if it has no engine strength.
1476         // AL 3-12-98: objp may not always be a ship!
1477         if ( objp->type == OBJ_SHIP ) {
1478                 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f)
1479                         return;
1480         }
1481                         
1482         //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));
1483         pip = &objp->phys_info;
1484
1485         vel_in = pip->rotvel;
1486         curr_orient = objp->orient;
1487         delta_time = flFrametime;
1488
1489         SDL_assert(turn_time > 0.0f);
1490         
1491         //      Scale turn_time based on skill level and team.
1492         if (!(flags & AITTV_FAST)){
1493                 if (objp->type == OBJ_SHIP){
1494                         if (Ships[objp->instance].team != Ships[Player_obj->instance].team){
1495                                 turn_time *= Turn_time_skill_level_scale[Game_skill_level];
1496                         }
1497                 }
1498         }
1499
1500         //      Set max turn rate.
1501         vel_limit.xyz.x = 2*PI/turn_time;
1502         vel_limit.xyz.y = 2*PI/turn_time;
1503         vel_limit.xyz.z = 2*PI/turn_time;
1504
1505         //      Set rate at which ship can accelerate to its rotational velocity.
1506         //      For now, weapons just go much faster.
1507         acc_limit = vel_limit;
1508         if (objp->type == OBJ_WEAPON)
1509                 vm_vec_scale(&acc_limit, 8.0f);
1510
1511         src = objp->pos;
1512
1513         if (rel_pos != NULL) {
1514                 vector  gun_point;
1515                 vm_vec_unrotate(&gun_point, rel_pos, &objp->orient);
1516                 vm_vec_add2(&src, &gun_point);
1517         }
1518
1519         vm_vec_normalized_dir(&desired_fvec, dest, &src);
1520
1521         //      Since ship isn't necessarily moving in the direction it's pointing, sometimes it's better
1522         //      to be moving towards goal rather than just pointing.  So, if slide_vec is !NULL, try to
1523         //      make ship move towards goal, not point at goal.
1524         if (slide_vec != NULL) {
1525                 vm_vec_add2(&desired_fvec, slide_vec);
1526                 vm_vec_normalize(&desired_fvec);
1527         }
1528
1529         //      Should be more general case here.  Currently, anything that is not a weapon will bank when it turns.
1530         if (objp->type == OBJ_WEAPON)
1531                 delta_bank = 0.0f;
1532         else if ((bank_override) && (Ships[objp->instance].team & opposing_team_mask(Player_ship->team))) {     //      Theoretically, this will only happen for Shivans.
1533                 delta_bank = bank_override;
1534                 //nprintf(("AI", "%i: %7.3f\n", Framecount, bank_override));
1535         } else {
1536                 delta_bank = vm_vec_dot(&curr_orient.v.rvec, &objp->last_orient.v.rvec);
1537                 delta_bank = 100.0f * (1.0f - delta_bank);
1538                 if (vm_vec_dot(&objp->last_orient.v.fvec, &objp->orient.v.rvec) < 0.0f)
1539                         delta_bank = -delta_bank;
1540
1541                 //nprintf(("AI", "%s: Frame %i: delta bank = %7.3f\n", Ships[objp->instance].ship_name, Framecount, delta_bank));
1542         }
1543
1544         //      Dave Andsager: The non-indented lines here are debug code to help you track down the problem in the physics
1545         //      that is causing ships to inexplicably rotate very far.  If you hit the Int3(), set the next statement to be
1546         //      the one marked "HERE".  (Do this clicking the cursor there, then right clicking.  Choose the right option.)
1547         //      This will allow you to rerun vm_forward_interpolate() with the values that caused the error.
1548         //      Note, you'll need to enable the Int3() about ten lines below.
1549 #ifndef NDEBUG
1550 vector tvec = objp->orient.v.fvec;
1551 vector  vel_in_copy;
1552 matrix  objp_orient_copy;
1553
1554 vel_in_copy = vel_in;
1555 objp_orient_copy = objp->orient;
1556
1557 vel_in = vel_in_copy;   //      HERE
1558 objp->orient = objp_orient_copy;
1559 #endif
1560         if (rvec != NULL) {
1561                 matrix  out_orient, goal_orient;
1562
1563                 vm_vector_2_matrix(&goal_orient, &desired_fvec, NULL, rvec);
1564                 vm_matrix_interpolate(&goal_orient, &curr_orient, &vel_in, delta_time, &out_orient, &vel_out, &vel_limit, &acc_limit);
1565                 objp->orient = out_orient;
1566         } else {
1567                 vm_forward_interpolate(&desired_fvec, &curr_orient, &vel_in, delta_time, delta_bank, &objp->orient, &vel_out, &vel_limit, &acc_limit);
1568         }
1569 #ifndef NDEBUG
1570 if (!((objp->type == OBJ_WEAPON) && (Weapon_info[Weapons[objp->instance].weapon_info_index].subtype == WP_MISSILE))) {
1571         if (delta_time < 0.25f && vm_vec_dot(&objp->orient.v.fvec, &tvec) < 0.1f)
1572                 Int3(); //      Get Andsager.  A ship has turned too far in one frame.
1573 }
1574 #endif
1575
1576         pip->rotvel = vel_out;
1577 }
1578
1579 void init_ship_info()
1580 {
1581         int     i;
1582
1583         if (Ship_info_inited)
1584                 return;
1585
1586         for (i=0; i<MAX_SHIP_TYPES; i++) {
1587                 Ship_info[i].min_speed = - Ship_info[i].max_rear_vel;
1588                 Ship_info[i].max_accel = Ship_info[i].max_vel.xyz.z;
1589         }
1590
1591         Ship_info_inited = 1;
1592
1593 }
1594
1595 //      Set aip->target_objnum to objnum
1596 //      Update aip->previous_target_objnum.
1597 //      If new target (objnum) is different than old target, reset target_time.
1598 int set_target_objnum(ai_info *aip, int objnum)
1599 {
1600 /*
1601         char    old_name[32], new_name[32];
1602
1603         if (!timestamp_elapsed(aip->ok_to_target_timestamp))
1604                 return aip->target_objnum;
1605
1606         if (Player_ship && (Ships[aip->shipnum].team == Player_ship->team)) {
1607                 if (aip->target_objnum == -1)
1608                         strcpy(old_name, "none");
1609                 else
1610                         strcpy(old_name, Ships[Objects[aip->target_objnum].instance].ship_name);
1611
1612                 if (objnum == -1)
1613                         strcpy(new_name, "none");
1614                 else
1615                         strcpy(new_name, Ships[Objects[objnum].instance].ship_name);
1616
1617                 nprintf(("AI", "Ship %s changing target from %s to %s\n", Ships[aip->shipnum].ship_name, old_name, new_name));
1618         }
1619 */
1620
1621         // AL 2-25-97: Ensure that a protected ship isn't being set as a target (for non-players only)
1622         /*
1623         if ( objnum >= 0 ) {
1624                 if ( !(Objects[Ships[aip->shipnum].objnum].flags & OF_PLAYER_SHIP) ) {
1625                         if ( Objects[objnum].flags & OF_PROTECTED ) {
1626                                 // AL 2-26-97: removing Int3() until issue with setting OF_PROTECTED in ai_set_attack_subsystem()
1627                                 //Int3();                                                               // this should not happen
1628                                 return aip->target_objnum;              // don't change targets
1629                         }
1630                 }
1631         }
1632         */
1633
1634         if ((aip != Player_ai) && (!timestamp_elapsed(aip->ok_to_target_timestamp))) {
1635                 return aip->target_objnum;
1636         }
1637
1638         if (aip->target_objnum == objnum) {
1639                 aip->previous_target_objnum = aip->target_objnum;
1640         } else {
1641                 aip->previous_target_objnum = aip->target_objnum;
1642
1643                 // ignore this assert if a multiplayer observer
1644                 if((Game_mode & GM_MULTIPLAYER) && (aip == Player_ai) && (Player_obj->type == OBJ_OBSERVER)){
1645                 } else {
1646                         SDL_assert(objnum != Ships[aip->shipnum].objnum);       //      make sure not targeting self
1647                 }
1648
1649                 // if stealth target, init ai_info for stealth
1650                 if ( (objnum > 0) && is_object_stealth_ship(&Objects[objnum]) ) {
1651                         init_ai_stealth_info(aip, &Objects[objnum]);
1652                 }
1653
1654                 aip->target_objnum = objnum;
1655                 aip->target_time = 0.0f;
1656                 aip->target_signature = Objects[objnum].signature;
1657                 // clear targeted subsystem
1658                 set_targeted_subsys(aip, NULL, -1);
1659         }
1660         
1661         return aip->target_objnum;
1662 }
1663
1664 int ai_select_primary_weapon(object *objp, object *other_objp, int flags);
1665
1666 //      Make new_subsys the targeted subsystem of ship *aip.
1667 ship_subsys *set_targeted_subsys(ai_info *aip, ship_subsys *new_subsys, int parent_objnum)
1668 {
1669         SDL_assert(aip != NULL);
1670
1671         aip->last_subsys_target = aip->targeted_subsys;
1672         aip->targeted_subsys = new_subsys;
1673         aip->targeted_subsys_parent = parent_objnum;
1674
1675         if ( new_subsys ) {
1676                 // Make new_subsys target
1677                 if (new_subsys->system_info->type == SUBSYSTEM_ENGINE) {
1678                         if ( aip != Player_ai ) {
1679                                 ai_select_primary_weapon(&Objects[Ships[aip->shipnum].objnum], &Objects[parent_objnum], WIF_PUNCTURE);
1680                                 ship_primary_changed(&Ships[aip->shipnum]);     // AL: maybe send multiplayer information when AI ship changes primaries
1681                         }
1682                 }
1683
1684                 if ( aip == Player_ai ) {
1685                         hud_lock_reset(0.5f);
1686                 }
1687
1688         } else {
1689                 // Cleanup any subsys path information if it exists
1690                 ai_big_subsys_path_cleanup(aip);
1691         }
1692         
1693         return aip->targeted_subsys;
1694 }                                                                                         
1695
1696 // called to init the data for single ai object.  At this point,
1697 // the ship and the object and the ai_info are are correctly
1698 // linked together. Ai_info[ai_index].shipnum is the only valid field 
1699 // in ai_info.
1700 //      This is called right when the object is parsed, so you can't assume much
1701 //      has been initialized.  For example, wings, waypoints, goals are probably
1702 //      not yet loaded. --MK, 10/8/96
1703 void ai_object_init(object * obj, int ai_index)
1704 {
1705         ai_info *aip;
1706         SDL_assert(ai_index >= 0 && ai_index < MAX_AI_INFO);
1707
1708         aip = &Ai_info[ai_index];
1709
1710         aip->type = 0;          //      0 means not in use.
1711         aip->wing = -1;         //      Member of what wing? -1 means none.
1712         aip->ai_class = Ship_info[Ships[obj->instance].ship_info_index].ai_class;
1713         aip->behavior = AIM_NONE;
1714 }
1715
1716 //      If *aip is docked, set max acceleration to A->mass/(A->mass + B->mass) where A is *aip and B is dock object
1717 void adjust_accel_for_docking(ai_info *aip)
1718 {
1719         if (aip->dock_objnum != -1) {
1720                 object  *obj2p = &Objects[aip->dock_objnum];
1721                 object  *obj1p;
1722
1723                 obj1p = &Objects[Ships[aip->shipnum].objnum];
1724
1725                 if (obj2p->signature == aip->dock_signature) {
1726                         float   ratio;
1727
1728                         ratio = obj1p->phys_info.mass / (obj1p->phys_info.mass + obj2p->phys_info.mass);
1729
1730                         // put cap on how much ship can slow down
1731 #ifdef MAKE_FS1
1732                         // FS1 can go slower, perhaps down to 0, but I'll cap it at .25 just in case
1733                         if (ratio < 0.25f) {
1734                                 ratio = 0.25f;
1735                         }
1736 #else
1737                         if (ratio < 0.8) {
1738                                 ratio = 0.8f;
1739                         }
1740 #endif
1741
1742                         if (AI_ci.forward > ratio) {
1743                                 AI_ci.forward = ratio;
1744                         }
1745                 }
1746         }
1747 }
1748
1749 // -------------------------------------------------------------------
1750 void accelerate_ship(ai_info *aip, float accel)
1751 {
1752         aip->prev_accel = accel;
1753         AI_ci.forward = accel;
1754         adjust_accel_for_docking(aip);
1755 }
1756
1757 //      --------------------------------------------------------------------------
1758 void change_acceleration(ai_info *aip, float delta_accel)
1759 {
1760         float   new_accel;
1761
1762         if (delta_accel < 0.0f) {
1763                 if (aip->prev_accel > 0.0f)
1764                         aip->prev_accel = 0.0f;
1765         } else if (aip->prev_accel < 0.0f)
1766                 aip->prev_accel = 0.0f;
1767
1768         new_accel = aip->prev_accel + delta_accel * flFrametime;
1769
1770         if (new_accel > 1.0f)
1771                 new_accel = 1.0f;
1772         else if (new_accel < -1.0f)
1773                 new_accel = -1.0f;
1774         
1775         aip->prev_accel = new_accel;
1776
1777         AI_ci.forward = new_accel;
1778         adjust_accel_for_docking(aip);
1779 }
1780
1781 void set_accel_for_target_speed(object *objp, float tspeed)
1782 {
1783         float   max_speed;
1784         ai_info *aip;
1785
1786         aip = &Ai_info[Ships[objp->instance].ai_index];
1787
1788         max_speed = Ships[objp->instance].current_max_speed;
1789
1790         AI_ci.forward = tspeed/max_speed;
1791         aip->prev_accel = AI_ci.forward;
1792
1793         adjust_accel_for_docking(aip);
1794 }
1795
1796 //      Stuff perim_point with a point on the perimeter of the sphere defined by object *objp
1797 //      on the vector from the center of *objp through the point *vp.
1798 void project_point_to_perimeter(vector *perim_point, vector *pos, float radius, vector *vp)
1799 {
1800         vector  v1;
1801         float           mag;
1802
1803         vm_vec_sub(&v1, vp, pos);
1804         mag = vm_vec_mag(&v1);
1805
1806         if (mag == 0.0f) {
1807                 Warning(LOCATION, "projectable point is at center of sphere.");
1808                 (void) vm_vec_make(&v1, 0.0f, radius, 0.0f);
1809         } else {
1810                 vm_vec_normalize(&v1);
1811                 vm_vec_scale(&v1, 1.1f * radius + 10.0f);
1812         }
1813
1814         vm_vec_add2(&v1, pos);
1815         *perim_point = v1;
1816 }
1817
1818 //      Stuff tan1 with tangent point on sphere.  tan1 is point nearer to *p1
1819 //      *p0 is point through which tangents pass.
1820 //      *centerp is center of sphere.
1821 //      *p1 is another point in space to define the plane in which tan1, tan2 reside.
1822 //      radius is the radius of the sphere.
1823 //      Note, this is a very approximate function just for AI.
1824 //      Note also: On 12/26/96, p1 is used to define the plane perpendicular to that which
1825 //      contains the tangent point.
1826 void get_tangent_point(vector *tan1, vector *p0, vector *centerp, vector *p1, float radius)
1827 {
1828         vector  dest_vec, v2c, perp_vec, temp_vec, v2;
1829         float           dist, ratio;
1830
1831         //      Detect condition of point inside sphere.
1832         if (vm_vec_dist(p0, centerp) < radius)
1833                 project_point_to_perimeter(tan1, centerp, radius, p0);
1834         else {
1835                 vm_vec_normalized_dir(&v2c, centerp, p0);
1836
1837                 //      Compute perpendicular vector using p0, centerp, p1
1838                 vm_vec_normal(&temp_vec, p0, centerp, p1);
1839                 vm_vec_sub(&v2, centerp, p0);
1840                 vm_vec_cross(&perp_vec, &temp_vec, &v2);
1841
1842                 vm_vec_normalize(&perp_vec);
1843
1844                 dist = vm_vec_dist_quick(p0, centerp);
1845                 ratio = dist / radius;
1846
1847                 if (ratio < 2.0f)
1848                         vm_vec_scale_add(&dest_vec, &perp_vec, &v2c, ratio-1.0f);
1849                 else
1850                         vm_vec_scale_add(&dest_vec, &v2c, &perp_vec, (1.0f + 1.0f/ratio));
1851
1852                 vm_vec_scale_add(tan1, p0, &dest_vec, dist + radius);
1853         }
1854 }
1855
1856 //      --------------------------------------------------------------------------
1857 //      Given an object and a point, turn towards the point, resulting in
1858 // approach behavior.
1859 void turn_towards_point(object *objp, vector *point, vector *slide_vec, float bank_override)
1860 {
1861         ai_info *aip;
1862         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
1863         
1864         // check if in formation and if not leader, don't change rotvel.xyz.z (bank to match leader elsewhere)
1865         if (aip->ai_flags & AIF_FORMATION) {
1866                 if (&Objects[aip->goal_objnum] != objp) {
1867                         float rotvel_z = objp->phys_info.rotvel.xyz.z;
1868                         ai_turn_towards_vector(point, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, slide_vec, NULL, bank_override, 0);
1869                         objp->phys_info.rotvel.xyz.z = rotvel_z;
1870                 }
1871         } else {
1872                 // normal turn
1873                 ai_turn_towards_vector(point, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, slide_vec, NULL, bank_override, 0);
1874         }
1875 }
1876
1877 //      --------------------------------------------------------------------------
1878 //      Given an object and a point, turn away from the point, resulting in avoidance behavior.
1879 //      Note: Turn away at full speed, not scaled down by skill level.
1880 void turn_away_from_point(object *objp, vector *point, float bank_override)
1881 {
1882         vector  opposite_point;
1883
1884         vm_vec_sub(&opposite_point, &objp->pos, point);
1885         vm_vec_add2(&opposite_point, &objp->pos);
1886
1887         ai_turn_towards_vector(&opposite_point, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, NULL, NULL, bank_override, AITTV_FAST);
1888 }
1889
1890
1891 //      --------------------------------------------------------------------------
1892 //      Given an object and a point, turn tangent to the point, resulting in
1893 // a circling behavior.
1894 //      Make object *objp turn around the point *point with a radius of radius.
1895 //      Note that this isn't the same as following a circle of radius radius with
1896 //      center *point, but it should be adequate.
1897 //      Note that if you want to circle an object without hitting it, you should use
1898 //      about twice that object's radius for radius, else you'll certainly bump into it.
1899 //      Return dot product to goal point.
1900 float turn_towards_tangent(object *objp, vector *point, float radius)
1901 {
1902         vector  vec_to_point;
1903         vector  goal_point;
1904         vector  perp_point;                             //      point radius away from *point on vector to objp->pos
1905         vector  up_vec, perp_vec;
1906
1907         vm_vec_normalized_dir(&vec_to_point, point, &objp->pos);
1908         vm_vec_crossprod(&up_vec, &vec_to_point, &objp->orient.v.fvec);
1909         vm_vec_crossprod(&perp_vec, &vec_to_point, &up_vec);
1910
1911         vm_vec_scale_add(&perp_point, point, &vec_to_point, -radius);
1912         if (vm_vec_dot(&objp->orient.v.fvec, &perp_vec) > 0.0f) {
1913                 vm_vec_scale_add(&goal_point, &perp_point, &perp_vec, radius);
1914         } else {
1915                 vm_vec_scale_add(&goal_point, &perp_point, &perp_vec, -radius);
1916         }
1917
1918 //      Ai_info[Ships[objp->instance].ai_index].goal_point = goal_point;
1919         turn_towards_point(objp, &goal_point, NULL, 0.0f);
1920
1921         vector  v2g;
1922
1923         vm_vec_normalized_dir(&v2g, &goal_point, &objp->pos);
1924         return vm_vec_dot(&objp->orient.v.fvec, &v2g);
1925 }
1926
1927 float turn_toward_tangent_with_axis(object *objp, object *center_objp, float radius)
1928 {
1929         vector r_vec, theta_vec;
1930         vector center_vec, vec_on_cylinder, sph_r_vec;
1931         float center_obj_z;
1932
1933         // find closest z of center objp
1934         vm_vec_sub(&sph_r_vec, &objp->pos, &center_objp->pos);
1935         center_obj_z = vm_vec_dotprod(&sph_r_vec, &center_objp->orient.v.fvec);
1936
1937         // find pt on axis with closest z
1938         vm_vec_scale_add(&center_vec, &center_objp->pos, &center_objp->orient.v.fvec, center_obj_z);
1939
1940         // get r_vec
1941         vm_vec_sub(&r_vec, &objp->pos, &center_vec);
1942 //      float r_mag = vm_vec_normalize_quick(&r_vec);
1943 //      mprintf(("cur_r: %.1f, desired_r: %.1f\n", r_mag, radius));
1944         SDL_assert( (vm_vec_dotprod(&r_vec, &center_objp->orient.v.fvec) < 0.0001));
1945
1946         // get theta vec - perp to r_vec and z_vec
1947         vm_vec_crossprod(&theta_vec, &center_objp->orient.v.fvec, &r_vec);
1948
1949 #ifndef NDEBUG
1950         float mag = vm_vec_normalize(&theta_vec);
1951         SDL_assert(mag > 0.9999 && mag < 1.0001);
1952 #endif
1953
1954         vector temp;
1955         vm_vec_crossprod(&temp, &r_vec, &theta_vec);
1956
1957 #ifndef NDEBUG
1958         float dot = vm_vec_dotprod(&temp, &center_objp->orient.v.fvec);
1959         SDL_assert( dot >0.9999 && dot < 1.0001);
1960 #endif
1961
1962         // find pt on clylinder with closest z
1963         vm_vec_scale_add(&vec_on_cylinder, &center_vec, &r_vec, radius);
1964
1965         vector goal_pt, v2g;
1966         vm_vec_scale_add(&goal_pt, &vec_on_cylinder, &theta_vec, radius);
1967
1968 //      Ai_info[Ships[objp->instance].ai_index].goal_point = goal_pt;
1969         turn_towards_point(objp, &goal_pt, NULL, 0.0f);
1970
1971         vm_vec_normalized_dir(&v2g, &goal_pt, &objp->pos);
1972         return vm_vec_dot(&objp->orient.v.fvec, &v2g);
1973 }
1974
1975 //      Returns a point radius units away from *point that *objp should turn towards to orbit *point
1976 void get_tangent_point(vector *goal_point, object *objp, vector *point, float radius)
1977 {
1978         vector  vec_to_point;
1979         vector  perp_point;                             //      point radius away from *point on vector to objp->pos
1980         vector  up_vec, perp_vec;
1981
1982         vm_vec_normalized_dir(&vec_to_point, point, &objp->pos);
1983         vm_vec_crossprod(&up_vec, &vec_to_point, &objp->orient.v.fvec);
1984         vm_vec_crossprod(&perp_vec, &vec_to_point, &up_vec);
1985         vm_vec_normalize(&perp_vec);
1986
1987         vm_vec_scale_add(&perp_point, point, &vec_to_point, -radius);
1988
1989         if (vm_vec_dot(&objp->orient.v.fvec, &perp_vec) > 0.0f) {
1990                 vm_vec_scale_add(goal_point, &perp_point, &perp_vec, radius);
1991         } else {
1992                 vm_vec_scale_add(goal_point, &perp_point, &perp_vec, -radius);
1993         }
1994 }
1995
1996 int     Player_attacking_enabled = 1;
1997
1998 // -----------------------------------------------------------------------------
1999 // Determine whether an object is targetable within a nebula
2000 int object_is_targetable(object *target, ship *viewer)
2001 {
2002         int stealth_ship = 0;
2003
2004         // if target is ship, check if visible by team
2005         if (target->type == OBJ_SHIP) {
2006                 stealth_ship = (Ship_info[Ships[target->instance].ship_info_index].flags & SIF_STEALTH);
2007                 if ( ship_is_visible_by_team(target->instance, viewer->team) == 1) {
2008                         return 1;
2009                 }
2010         }
2011
2012         // for AI partially targetable works as fully targetable, except for stealth ship
2013         if (stealth_ship) {
2014                 // if not team targetable, check if within frustrum
2015                 if ( ai_is_stealth_visible(&Objects[viewer->objnum], target) == STEALTH_VISIBLE ) {
2016                         return 1;
2017                 } else {
2018                         return 0;
2019                 }
2020         }
2021
2022         // if not fully targetable by team, check awacs level with viewer
2023         // allow targeting even if only only partially targetable to player
2024         float radar_return = awacs_get_level(target, viewer);
2025         if ( radar_return > 0.4 ) {
2026                 return 1;
2027         } else {
2028                 return 0;
2029         }
2030 }
2031
2032 //      Return number of enemies attacking object objnum
2033 //
2034 // AL 10.26.97: Also include turrets on large ships when couting enemies attacking
2035 int num_enemies_attacking(int objnum)
2036 {
2037         object          *objp;
2038         ship                    *sp;
2039         ship_subsys     *ssp;
2040         ship_obj                *so;
2041         int                     count;
2042
2043         count = 0;
2044
2045         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2046                 objp = &Objects[so->objnum];
2047                 SDL_assert(objp->instance != -1);
2048                 sp = &Ships[objp->instance];
2049
2050                 if (Ai_info[sp->ai_index].target_objnum == objnum)
2051                         count++;
2052
2053                 // consider turrets that may be attacking objnum (but only turrets on SIF_BIG_SHIP ships)
2054                 if ( Ship_info[sp->ship_info_index].flags & SIF_BIG_SHIP ) {
2055
2056                         // loop through all the subsystems, check if turret has objnum as a target
2057                         ssp = GET_FIRST(&sp->subsys_list);
2058                         while ( ssp != END_OF_LIST( &sp->subsys_list ) ) {
2059
2060                                 if ( ssp->system_info->type == SUBSYSTEM_TURRET ) {
2061                                         if ( (ssp->turret_enemy_objnum == objnum) && (ssp->current_hits > 0) ) {
2062                                                 count++;
2063                                         }
2064                                 }
2065                                 ssp = GET_NEXT( ssp );
2066                         } // end while
2067                 }
2068         }
2069
2070         return count;
2071 }
2072
2073 //      Get the team to fire on given an object.
2074 int get_enemy_team_mask(int objnum)
2075 {
2076         int     my_team, enemy_team_mask;
2077
2078         my_team = Ships[Objects[objnum].instance].team;
2079
2080         if (Mission_all_attack) {
2081                 //      All teams attack all teams.
2082                 switch (my_team) {
2083                 case TEAM_FRIENDLY:
2084                         enemy_team_mask = TEAM_HOSTILE | TEAM_NEUTRAL | TEAM_TRAITOR;
2085                         break;
2086                 case TEAM_HOSTILE:
2087                         enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_TRAITOR;
2088                         break;
2089                 case TEAM_NEUTRAL:
2090                         enemy_team_mask = TEAM_FRIENDLY | TEAM_HOSTILE | TEAM_TRAITOR;
2091                         break;
2092                 case TEAM_UNKNOWN:
2093                         enemy_team_mask = TEAM_HOSTILE;
2094                         break;
2095                 case TEAM_TRAITOR:
2096                         enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_HOSTILE | TEAM_TRAITOR;
2097                         break;
2098                 default:
2099                         enemy_team_mask = TEAM_HOSTILE;
2100                         Int3();                 //      Illegal value for team!
2101                         break;
2102                 }
2103         } else {
2104                 switch (my_team) {
2105                 case TEAM_FRIENDLY:
2106                         enemy_team_mask = TEAM_HOSTILE | TEAM_NEUTRAL | TEAM_TRAITOR;
2107                         break;
2108                 case TEAM_HOSTILE:
2109                         enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_TRAITOR;
2110                         break;
2111                 case TEAM_NEUTRAL:
2112                         enemy_team_mask = TEAM_FRIENDLY | TEAM_TRAITOR;
2113                         break;
2114                 case TEAM_UNKNOWN:
2115                         enemy_team_mask = TEAM_HOSTILE;
2116                         break;
2117                 case TEAM_TRAITOR:
2118                         enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_HOSTILE | TEAM_TRAITOR;
2119                         break;
2120                 default:
2121                         enemy_team_mask = TEAM_HOSTILE;
2122                         Int3();                 //      Illegal value for team!
2123                         break;
2124                 }
2125         }
2126
2127         return enemy_team_mask;
2128 }
2129
2130 //      Scan all the ships in *objp's wing.
2131 //      Return the lowest maximum speed of a ship in the wing.
2132 //      Current maximum speed (based on energy settings) is shipp->current_max_speed
2133 float get_wing_lowest_max_speed(object *objp)
2134 {
2135         ship            *shipp;
2136         ai_info *aip;
2137         float           lowest_max_speed;
2138         int             wingnum;
2139         object  *o;
2140         ship_obj        *so;
2141
2142         SDL_assert(objp->type == OBJ_SHIP);
2143         SDL_assert((objp->instance >= 0) && (objp->instance < MAX_OBJECTS));
2144         shipp = &Ships[objp->instance];
2145         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
2146         aip = &Ai_info[shipp->ai_index];
2147
2148         wingnum = aip->wing;
2149
2150         lowest_max_speed = shipp->current_max_speed;
2151
2152         if ( wingnum == -1 )
2153                 return lowest_max_speed;
2154
2155         SDL_assert(wingnum >= 0);
2156
2157         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2158                 o = &Objects[so->objnum];
2159                 ship    *oshipp = &Ships[o->instance];
2160                 ai_info *oaip = &Ai_info[oshipp->ai_index];
2161
2162                 if ((oaip->mode == AIM_WAYPOINTS) && (oaip->wing == wingnum)) {
2163                         //      Note: If a ship in the wing has a super low max speed, probably its engines are disabled.  So, fly along and
2164                         //      ignore the poor guy.
2165                         float   cur_max = oshipp->current_max_speed;
2166
2167                         if (oaip->ai_flags & AIF_DOCKED) {
2168                                 if (oaip->dock_objnum > -1)
2169                                         if (Objects[oaip->dock_objnum].type == OBJ_SHIP) 
2170                                                 cur_max *= o->phys_info.mass/(o->phys_info.mass + Objects[oaip->dock_objnum].phys_info.mass);
2171                         }
2172                                                         
2173                         if ((oshipp->current_max_speed > 5.0f) && (cur_max < lowest_max_speed)) {
2174                                 lowest_max_speed = cur_max;
2175                         }
2176                 }
2177         }
2178
2179         return lowest_max_speed;
2180 }
2181
2182 /*
2183 //      Tell everyone to ignore object objnum.
2184 void set_global_ignore_object(int objnum)
2185 {
2186         int     i;
2187
2188         SDL_assert(Objects[objnum].type == OBJ_SHIP);
2189
2190         nprintf(("AI", "Telling everyone to ignore object %s\n", Ships[Objects[objnum].instance].ship_name));
2191
2192         for (i=0; i<MAX_IGNORE_OBJECTS; i++) {
2193                 if (Ignore_objects[i].objnum == -1) {
2194                         Ignore_objects[i].objnum = objnum;
2195                         Ignore_objects[i].signature = Objects[objnum].signature;
2196                         break;
2197                 }
2198         }
2199
2200         if (i == MAX_IGNORE_OBJECTS) {
2201                 //      Couldn't find a free slot, but maybe one of these objects has died.
2202                 for (i=0; i<MAX_IGNORE_OBJECTS; i++) {
2203                         int     o = Ignore_objects[i].objnum;
2204                         if (Objects[o].type != OBJ_SHIP)
2205                                 break;          //      Not a ship, so use this slot.
2206                         if (Objects[o].signature != Ignore_objects[i].signature)
2207                                 break;          //      Signatures don't match, so use this slot.
2208                 }
2209
2210                 if (i != MAX_IGNORE_OBJECTS) {
2211                         Ignore_objects[i].objnum = objnum;
2212                         Ignore_objects[i].signature = Objects[objnum].signature;
2213                 } else {
2214                         nprintf(("Warning", "Ignore_objects buffer full.  Stealing a slot to ignore object #%i\n"));
2215                         Int3();
2216
2217                         int     r;
2218
2219                         r = objnum % MAX_IGNORE_OBJECTS;
2220
2221                         Ignore_objects[r].objnum = objnum;
2222                         Ignore_objects[r].signature = Objects[objnum].signature;
2223                 }
2224         }
2225 }
2226
2227 */
2228
2229 //      Determine if object objnum is supposed to be ignored by object with ai_info *aip.
2230 //      Return:
2231 //              TRUE    if objnum is aip->ignore_objnum (and signatures match)
2232 //                              or objnum is in ignore wing
2233 //              FALSE   otherwise
2234 int is_ignore_object(ai_info *aip, int objnum)
2235 {
2236
2237 /*      //      First, scan all objects in global array of objects to be ignored.
2238         for (int i=0; i<MAX_IGNORE_OBJECTS; i++)
2239                 if (Ignore_objects[i].objnum != -1)
2240                         if (objnum == Ignore_objects[i].objnum)
2241                                 if (Objects[Ignore_objects[i].objnum].signature == Ignore_objects[i].signature)
2242                                         return 1;
2243 */
2244
2245         //      Didn't find in global list.  Now check 
2246         if (aip->ignore_objnum == UNUSED_OBJNUM)
2247                 return 0;                                                                       //      Not ignoring anything.
2248         else if (aip->ignore_objnum >= 0) {             //      This means it's ignoring an object, not a wing.
2249                 if (aip->ignore_objnum == objnum) {
2250                         if (Objects[aip->ignore_objnum].signature == aip->ignore_signature) {
2251                                 return 1;
2252                         } else {
2253                                 aip->ignore_objnum = UNUSED_OBJNUM;
2254                                 return 0;
2255                         }
2256                 } else {
2257                         return 0;
2258                 }
2259         } else {                                                                                        //      Ignoring a wing.
2260                 Int3(); // Should never happen.  I thought I removed this behavior! -- MK, 5/17/98
2261                 return 0;
2262 /*              int     ignore_wingnum = -(aip->ignore_objnum + 1);
2263
2264                 SDL_assert(ignore_wingnum < MAX_WINGS);
2265                 SDL_assert(aip->shipnum >= 0);
2266                 return (Ships[Objects[objnum].instance].wingnum == ignore_wingnum);
2267 */      }
2268 }
2269
2270 // -----------------------------------------------------------------------------
2271
2272 // given a ship with bounding box and a point, find the closest point on the bbox
2273 int get_nearest_bbox_point(object *ship_obj, vector *start, vector *box_pt)
2274 {
2275         vector temp, rf_start;
2276         polymodel *pm;
2277         pm = model_get(Ship_info[Ships[ship_obj->instance].ship_info_index].modelnum);
2278
2279         // get start in ship rf
2280         vm_vec_sub(&temp, start, &ship_obj->pos);
2281         vm_vec_rotate(&rf_start, &temp, &ship_obj->orient);
2282
2283         // find box_pt
2284         int inside = project_point_onto_bbox(&pm->mins, &pm->maxs, &rf_start, &temp);
2285
2286         // get box_pt in world rf
2287         vm_vec_unrotate(box_pt, &temp, &ship_obj->orient);
2288         vm_vec_add2(box_pt, &ship_obj->pos);
2289
2290         return inside;
2291 }
2292
2293
2294 typedef struct eval_nearest_objnum {
2295         int     objnum;
2296         object *trial_objp;
2297         int     enemy_team_mask;
2298         int     enemy_wing;
2299         float   range;
2300         int     max_attackers;
2301         int     nearest_objnum;
2302         float   nearest_dist;
2303         int     check_danger_weapon_objnum;
2304 } eval_nearest_objnum;
2305
2306
2307 void evaluate_object_as_nearest_objnum(eval_nearest_objnum *eno)
2308 {
2309         ai_info *aip;
2310         ship_subsys     *attacking_subsystem;
2311
2312         aip = &Ai_info[Ships[Objects[eno->objnum].instance].ai_index];
2313
2314         attacking_subsystem = aip->targeted_subsys;
2315
2316         if ((attacking_subsystem != NULL) || !(eno->trial_objp->flags & OF_PROTECTED)) {
2317                 if ( OBJ_INDEX(eno->trial_objp) != eno->objnum ) {
2318 #ifndef NDEBUG
2319                         if (!Player_attacking_enabled && (eno->trial_objp == Player_obj))
2320                                 return;
2321 #endif
2322                         //      If only supposed to attack ship in a specific wing, don't attack other ships.
2323                         if ((eno->enemy_wing != -1) && (Ships[eno->trial_objp->instance].wingnum != eno->enemy_wing))
2324                                 return;
2325
2326                         //      Don't keep firing at a ship that is in its death throes.
2327                         if (Ships[eno->trial_objp->instance].flags & SF_DYING)
2328                                 return;
2329
2330                         if (is_ignore_object(aip, ((eno->trial_objp)-Objects)))
2331                                 return;
2332
2333                         if (eno->trial_objp->flags & OF_PROTECTED)
2334                                 return;
2335
2336                         if (Ships[eno->trial_objp->instance].flags & SF_ARRIVING)
2337                                 return;
2338
2339                         ship_info *sip = &Ship_info[Ships[eno->trial_objp->instance].ship_info_index];
2340
2341                         if (sip->flags & (SIF_NO_SHIP_TYPE | SIF_NAVBUOY))
2342                                 return;
2343
2344                         if (Ships[eno->trial_objp->instance].team & eno->enemy_team_mask) {
2345                                 float   dist;
2346                                 int     num_attacking;
2347
2348                                 // Allow targeting of stealth in nebula by his firing at me
2349                                 // This is done for a specific ship, not generally.
2350                                 if ( !eno->check_danger_weapon_objnum ) {
2351                                         // check if can be targeted if inside nebula
2352                                         if ( !object_is_targetable(eno->trial_objp, &Ships[Objects[eno->objnum].instance]) ) {
2353                                                 // check if stealth ship is visible, but not "targetable"
2354                                                 if ( !((sip->flags & SIF_STEALTH) && ai_is_stealth_visible(&Objects[eno->objnum], eno->trial_objp)) ) {
2355                                                         return;
2356                                                 }
2357                                         }
2358                                 }
2359
2360                                 // if objnum is BIG or HUGE, find distance to bbox
2361                                 if (sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
2362                                         vector box_pt;
2363                                         // check if inside bbox
2364                                         int inside = get_nearest_bbox_point(eno->trial_objp, &Objects[eno->objnum].pos, &box_pt);
2365                                         if (inside) {
2366                                                 dist = 10.0f;
2367                                                 // on the box
2368                                         } else {
2369                                                 dist = vm_vec_dist_quick(&Objects[eno->objnum].pos, &box_pt);
2370                                         }
2371                                 } else {
2372                                         dist = vm_vec_dist_quick(&Objects[eno->objnum].pos, &eno->trial_objp->pos);
2373                                 }
2374                                 
2375                                 //      Make it more likely that fighters (or bombers) will be picked as an enemy by scaling up distance for other types.
2376                                 if ((Ship_info[Ships[eno->trial_objp->instance].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER))) {
2377                                         dist = dist * 0.5f;
2378                                 }
2379
2380                                 num_attacking = num_enemies_attacking(eno->trial_objp-Objects);
2381                                 if ((sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) || (num_attacking < eno->max_attackers)) {
2382                                         if (!(sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))){
2383                                                 dist *= (float) (num_attacking+2)/2.0f;                         //      prevents lots of ships from attacking same target
2384                                         }
2385
2386                                         if (eno->trial_objp->flags & OF_PLAYER_SHIP){
2387                                                 dist *= 1.0f + (NUM_SKILL_LEVELS - Game_skill_level - 1)/NUM_SKILL_LEVELS;      //      Favor attacking non-players based on skill level.
2388                                         }
2389
2390                                         if (dist < eno->nearest_dist) {
2391                                                 eno->nearest_dist = dist;
2392                                                 eno->nearest_objnum = eno->trial_objp-Objects;
2393                                         }
2394                                 }
2395                         }
2396                 }
2397         }
2398
2399 }
2400
2401
2402 //      Given an object and an enemy team, return the index of the nearest enemy object.
2403 //      Unless aip->targeted_subsys != NULL, don't allow to attack objects
2404 //      with OF_PROTECTED bit set.
2405 //      Ship must be within range "range".
2406 //      Don't attack a ship that already has at least max_attackers attacking it.
2407 int get_nearest_objnum(int objnum, int enemy_team_mask, int enemy_wing, float range, int max_attackers)
2408 {
2409         object  *danger_weapon_objp;
2410         ai_info *aip;
2411         ship_obj        *so;
2412
2413         // initialize eno struct
2414         eval_nearest_objnum eno;
2415         eno.enemy_team_mask = enemy_team_mask;
2416         eno.enemy_wing = enemy_wing;
2417         eno.max_attackers = max_attackers;
2418         eno.objnum = objnum;
2419         eno.range = range;
2420         eno.nearest_dist = range;
2421         eno.nearest_objnum = -1;
2422         eno.check_danger_weapon_objnum = 0;
2423
2424         // go through the list of all ships and evaluate as potential targets
2425         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2426                 eno.trial_objp = &Objects[so->objnum];
2427                 evaluate_object_as_nearest_objnum(&eno);
2428
2429         }
2430
2431         // check if danger_weapon_objnum has will show a stealth ship
2432         aip = &Ai_info[Ships[Objects[objnum].instance].ai_index];
2433         if (aip->danger_weapon_objnum >= 0) {
2434                 danger_weapon_objp = &Objects[aip->danger_weapon_objnum];
2435                 // validate weapon
2436                 if (danger_weapon_objp->signature == aip->danger_weapon_signature) {
2437                         SDL_assert(danger_weapon_objp->type == OBJ_WEAPON);
2438                         // check if parent is a ship
2439                         if (danger_weapon_objp->parent >= 0) {
2440                                 if ( is_object_stealth_ship(&Objects[danger_weapon_objp->parent]) ) {
2441                                         // check if stealthy
2442                                         if ( ai_is_stealth_visible(&Objects[objnum], &Objects[danger_weapon_objp->parent]) != STEALTH_FULLY_TARGETABLE ) {
2443                                                 // check if weapon is laser
2444                                                 if (Weapon_info[Weapons[danger_weapon_objp->instance].weapon_info_index].subtype == WP_LASER) {
2445                                                         // check stealth ship by its laser fire
2446                                                         eno.check_danger_weapon_objnum = 1;
2447                                                         eno.trial_objp = &Objects[danger_weapon_objp->parent];
2448                                                         evaluate_object_as_nearest_objnum(&eno);
2449                                                 }
2450                                         }
2451                                 }
2452                         }
2453                 }
2454         }
2455
2456         //      If only looking for target in certain wing and couldn't find anything in
2457         //      that wing, look for any object.
2458         if ((eno.nearest_objnum == -1) && (enemy_wing != -1)) {
2459                 return get_nearest_objnum(objnum, enemy_team_mask, -1, range, max_attackers);
2460         }
2461
2462         return eno.nearest_objnum;
2463 }
2464
2465 //      Given an object and an enemy team, return the index of the nearest enemy object.
2466 //      Unlike find_enemy or find_nearest_objnum, this doesn't care about things like the protected flag or number
2467 //      of enemies attacking.
2468 //      It is used to find the nearest enemy to determine things like whether to rearm.
2469 int find_nearby_hostile(int objnum, int enemy_team_mask, float range, int *count)
2470 {
2471         int             nearest_objnum;
2472         float           nearest_dist;
2473         object  *objp;
2474         ship_obj        *so;
2475
2476         nearest_objnum = -1;
2477         nearest_dist = range;
2478
2479         *count = 0;
2480
2481         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2482                 objp = &Objects[so->objnum];
2483
2484                 if ( OBJ_INDEX(objp) != objnum ) {
2485                         if (Ships[objp->instance].flags & SF_DYING)
2486                                 continue;
2487
2488                         if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_NO_SHIP_TYPE | SIF_NAVBUOY))
2489                                 continue;
2490
2491                         if (Ships[objp->instance].team & enemy_team_mask) {
2492                                 float   dist;
2493
2494                                 dist = vm_vec_dist_quick(&Objects[objnum].pos, &objp->pos) - objp->radius*0.75f;
2495                                 
2496                                 if (dist < range) {
2497                                         (*count)++;
2498
2499                                         if (dist < nearest_dist) {
2500                                                 nearest_dist = dist;
2501                                                 nearest_objnum = objp-Objects;
2502                                         }
2503                                 }
2504                         }
2505                 }
2506         }
2507
2508         return nearest_objnum;
2509 }
2510
2511 // return !0 if objp can be considered for a turret target, 0 otherwise
2512 // input:       objp                            =>      object that turret is considering as an enemy
2513 //                              turret_parent   =>      object index for ship that turret sits on
2514 int valid_turret_enemy(object *objp, object *turret_parent)
2515 {
2516         if ( objp == turret_parent ) {
2517                 return 0;
2518         }
2519
2520         if ( objp->type == OBJ_ASTEROID ) {
2521                 return 1;
2522         }
2523
2524         if ( objp->type == OBJ_SHIP ) {
2525                 ship *shipp;
2526                 shipp = &Ships[objp->instance];
2527
2528                 // don't fire at ships with protected bit set!!!
2529                 if ( objp->flags & OF_PROTECTED ) {
2530                         return 0;
2531                 }
2532
2533                 if ( !(Ship_info[shipp->ship_info_index].flags & SIF_DO_COLLISION_CHECK)) {
2534                         return 0;
2535                 }
2536
2537                 if (shipp->flags & SF_ARRIVING) {
2538                         return 0;
2539                 }
2540
2541                 return 1;
2542         }
2543
2544         if ( objp->type == OBJ_WEAPON ) {
2545                 if ( Weapon_info[Weapons[objp->instance].weapon_info_index].wi_flags & WIF_BOMB ) {
2546                         if ( obj_team(turret_parent) != Weapons[objp->instance].team ) {
2547                                 return 1;
2548                         }
2549                 }
2550         }
2551
2552         return 0;
2553 }
2554
2555 // return 1 if objp is in fov of the specified turret, tp.  Otherwise return 0.
2556 //      dist = distance from turret to center point of object
2557 int object_in_turret_fov(object *objp, model_subsystem *tp, vector *tvec, vector *tpos, float dist)
2558 {
2559         vector  v2e;
2560         float           dot;
2561         vm_vec_normalized_dir(&v2e, &objp->pos, tpos);
2562         dot = vm_vec_dot(&v2e, tvec);
2563
2564         dot += objp->radius / (dist + objp->radius);
2565
2566         if ( dot >= tp->turret_fov ) {
2567                 return 1;
2568         }
2569
2570         return 0;
2571 }
2572
2573 // return 1 if bomb_objp is headed towards ship_objp
2574 int bomb_headed_towards_ship(object *bomb_objp, object *ship_objp)
2575 {
2576         float           dot;
2577         vector  bomb_to_ship_vector;
2578
2579         vm_vec_normalized_dir(&bomb_to_ship_vector, &ship_objp->pos, &bomb_objp->pos);
2580         dot = vm_vec_dot(&bomb_objp->orient.v.fvec, &bomb_to_ship_vector);
2581
2582         if ( dot > 0 ) {
2583                 return 1;
2584         }
2585
2586         return 0;
2587 }
2588
2589 // nubmer of live turrets with target_objnum 
2590 int num_turrets_attacking(object *turret_parent, int target_objnum) 
2591 {
2592         ship_subsys *ss;
2593         ship *shipp;
2594         int count = 0;
2595         shipp = &Ships[turret_parent->instance];
2596
2597         SDL_assert(turret_parent->type == OBJ_SHIP);
2598         SDL_assert(Objects[target_objnum].type == OBJ_SHIP);
2599
2600         for (ss=GET_FIRST(&shipp->subsys_list); ss!=END_OF_LIST(&shipp->subsys_list); ss=GET_NEXT(ss)) {
2601                 // check if subsys is alive
2602                 if (ss->current_hits <= 0.0f) {
2603                         continue;
2604                 }
2605
2606                 // check if it's a turret
2607                 if (ss->system_info->type != SUBSYSTEM_TURRET) {
2608                         continue;
2609                 }
2610
2611                 // if the turret is locked
2612                 if(ss->weapons.flags & SW_FLAG_TURRET_LOCK){
2613                         continue;
2614                 }               
2615
2616                 // check if turret is targeting target_objnum
2617                 if (ss->turret_enemy_objnum == target_objnum) {
2618                         count++;
2619                 }
2620         }
2621
2622         return count;
2623 }
2624
2625 float Lethality_range_const = 2.0f;
2626 DCF(lethality_range, "N for modifying range: 1 / (1+N) at 100")
2627 {
2628         dc_get_arg(ARG_FLOAT);
2629         Lethality_range_const = Dc_arg_float;
2630 }
2631
2632 float Player_lethality_bump[NUM_SKILL_LEVELS] = {
2633         // 0.0f, 5.0f, 10.0f, 25.0f, 40.0f
2634         0.0f, 0.0f, 0.0f, 0.0f, 0.0f
2635 };
2636
2637 // evaluate obj as posssible target for turret
2638 void evaluate_obj_as_target(object *objp, eval_enemy_obj_struct *eeo)
2639 {
2640         object  *turret_parent_obj = &Objects[eeo->turret_parent_objnum];
2641         ship            *shipp;
2642         model_subsystem *tp = eeo->turret_subsys->system_info;
2643         float dist;
2644
2645         // Don't look for bombs when weapon system is not ok
2646         if (objp->type == OBJ_WEAPON && !eeo->weapon_system_ok) {
2647                 return;
2648         }
2649
2650         if ( !valid_turret_enemy(objp, turret_parent_obj) ) {
2651                 return;
2652         }
2653
2654 #ifndef NDEBUG
2655         if (!Player_attacking_enabled && (objp == Player_obj)) {
2656                 return;
2657         }
2658 #endif
2659
2660         if ( objp->type == OBJ_SHIP ) {
2661                 shipp = &Ships[objp->instance];
2662
2663                 // check on enemy team
2664                 if ( !(shipp->team & eeo->enemy_team_mask) ) {
2665                         return;
2666                 }
2667
2668                 // check if protected
2669                 if (objp->flags & OF_PROTECTED) {
2670                         return;
2671                 }
2672
2673                 // check if beam protected
2674                 if (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM) {
2675                         if (objp->flags & OF_BEAM_PROTECTED) {
2676                                 return;
2677                         }
2678                 }
2679
2680                 if (eeo->big_only_flag) {
2681                         if (!(Ship_info[shipp->ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
2682                                 return;
2683                         }
2684                 }
2685
2686                 // check if     turret flagged to only target tagged ships
2687                 if ( (eeo->turret_subsys->weapons.flags & SW_FLAG_TAGGED_ONLY) && !ship_is_tagged(objp) ) {
2688                         return;
2689                 }
2690
2691                 // check if valid target in nebula
2692                 if ( !object_is_targetable(objp, &Ships[Objects[eeo->turret_parent_objnum].instance]) ) {
2693                         // BYPASS ocassionally for stealth
2694                         int try_anyway = FALSE;
2695                         if ( is_object_stealth_ship(objp) ) {
2696                                 float turret_stealth_find_chance = 0.5f;
2697                                 float speed_mod = -0.1f + vm_vec_mag_quick(&objp->phys_info.vel) / 70.0f;
2698                                 if (frand() > (turret_stealth_find_chance + speed_mod)) {
2699                                         try_anyway = TRUE;
2700                                 }
2701                         }
2702
2703                         if (!try_anyway) {
2704                                 return;
2705                         }
2706                 }
2707
2708         } else {
2709                 shipp = NULL;
2710         }
2711
2712         // modify dist for BIG|HUGE, getting closest point on bbox, if not inside
2713         dist = vm_vec_dist_quick(eeo->tpos, &objp->pos) - objp->radius;
2714         if (dist < 0.0f) {
2715                 dist = 0.0f;
2716         }
2717
2718         // check if object is a bomb attacking the turret parent
2719         // check if bomb is homing on the turret parent ship
2720         if (objp->type == OBJ_WEAPON) {
2721                 if ( Weapons[objp->instance].homing_object == &Objects[eeo->turret_parent_objnum] ) {
2722                         if ( dist < eeo->nearest_homing_bomb_dist ) {
2723                                 if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2724                                         eeo->nearest_homing_bomb_dist = dist;
2725                                         eeo->nearest_homing_bomb_objnum = OBJ_INDEX(objp);
2726                                 }
2727                         }
2728                 // if not homing, check if bomb is flying towards ship
2729                 } else if ( bomb_headed_towards_ship(objp, &Objects[eeo->turret_parent_objnum]) ) {
2730                         if ( dist < eeo->nearest_bomb_dist ) {
2731                                 if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2732                                         eeo->nearest_bomb_dist = dist;
2733                                         eeo->nearest_bomb_objnum = OBJ_INDEX(objp);
2734                                 }
2735                         }
2736                 }
2737         } // end weapon section
2738
2739         // maybe recalculate dist for big or huge ship
2740 //      if (shipp && (Ship_info[shipp->ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
2741 //              fvi_ray_boundingbox(min, max, start, direction, hit);
2742 //              dist = vm_vec_dist_quick(hit, tvec);
2743 //      }
2744
2745         // check for nearest attcker
2746         if ( (shipp) && (dist < eeo->weapon_travel_dist) ) {
2747                 ai_info *aip = &Ai_info[shipp->ai_index];
2748
2749                 // modify distance based on number of turrets from my ship attacking enemy (add 10% per turret)
2750                 // dist *= (num_enemies_attacking(OBJ_INDEX(objp))+2)/2;        //      prevents lots of ships from attacking same target
2751                 int num_att_turrets = num_turrets_attacking(turret_parent_obj, OBJ_INDEX(objp));
2752                 dist *= (1.0f + 0.1f*num_att_turrets);
2753
2754                 // return if we're over the cap
2755                 int max_turrets = 3 + Game_skill_level * Game_skill_level;
2756                 if (num_att_turrets > max_turrets) {
2757                         return;
2758                 }
2759
2760                 // modify distance based on lethality of objp to my ship
2761                 float active_lethality = aip->lethality;
2762                 if (objp->flags & OF_PLAYER_SHIP) {
2763                         active_lethality += Player_lethality_bump[Game_skill_level];
2764                 }
2765
2766                 dist /= (1.0f + 0.01f*Lethality_range_const*active_lethality);
2767
2768                 // Make level 2 tagged ships more likely to be targeted
2769                 if (shipp->level2_tag_left > 0.0f) {
2770                         dist *= 0.3f;
2771                 }
2772
2773                 // check if objp is targeting the turret's ship, or if objp has just hit the turret's ship
2774                 if ( aip->target_objnum == eeo->turret_parent_objnum || aip->last_objsig_hit == Objects[eeo->turret_parent_objnum].signature ) {
2775                         // A turret will always target a ship that is attacking itself... self-preservation!
2776                         if ( aip->targeted_subsys == eeo->turret_subsys ) {
2777                                 dist *= 0.5f;   // highest priority
2778                         }
2779                 }
2780
2781                 // maybe update nearest attacker
2782                 if ( dist < eeo->nearest_attacker_dist ) {
2783                         if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2784                                 // 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));
2785                                 eeo->nearest_attacker_dist = dist;
2786                                 eeo->nearest_attacker_objnum = OBJ_INDEX(objp);
2787                         }
2788                 }
2789         } // end ship section
2790
2791 #ifdef MAKE_FS1
2792         // check if object is an asteroid attacking the turret parent - taylor
2793         if (objp->type == OBJ_ASTEROID) {
2794                 if ( eeo->turret_parent_objnum == asteroid_collide_objnum(objp) ) {
2795                         // give priority to the closest asteroid *impact* (ms intervals)
2796                         dist *= 0.9f + (0.01f * asteroid_time_to_impact(objp));
2797
2798                         if (dist < eeo->nearest_dist ) {
2799                                 if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2800                                         eeo->nearest_dist = dist;
2801                                         eeo->nearest_objnum = OBJ_INDEX(objp);
2802                                 }
2803                         }
2804                 }
2805         } // end asteroid selection
2806 #endif
2807 }
2808
2809 // return 0 only if objnum is beam protected and turret is beam turret
2810 int is_target_beam_valid(ship_subsys *turret_subsys, int objnum)
2811 {
2812         // check if turret has beam weapon
2813         model_subsystem *tp = turret_subsys->system_info;
2814
2815         if (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM) {
2816                 if (Objects[objnum].flags & OF_BEAM_PROTECTED) {
2817                         return 0;
2818                 }
2819
2820                 if (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_HUGE) {
2821                         if (Objects[objnum].type == OBJ_SHIP && !(Ship_info[Ships[Objects[objnum].instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) ) {
2822                                 return 0;
2823                         }
2824                 }
2825         }
2826
2827         return 1;
2828 }
2829
2830
2831 //      Given an object and an enemy team, return the index of the nearest enemy object.
2832 //
2833 // input:
2834 //                              turret_parent_objnum    => parent objnum for the turret
2835 //                              turret_subsys                   => pointer to system_info for the turret subsystem
2836 //                              enemy_team_mask         => OR'ed TEAM_ flags for the enemy of the turret parent ship
2837 //                              tpos                                            => position of turret (world coords)
2838 //                              tvec                                            => forward vector of turret (world coords)
2839 //                              current_enemy                   =>      objnum of current turret target
2840 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)
2841 {
2842         float                                   weapon_travel_dist;
2843         int                                     weapon_system_ok;
2844         object                          *objp;
2845         model_subsystem *tp;
2846         eval_enemy_obj_struct eeo;
2847
2848         // list of stuff to go thru
2849         ship_obj                *so;
2850         missile_obj *mo;
2851
2852         tp = turret_subsys->system_info;
2853         weapon_travel_dist = min(Weapon_info[tp->turret_weapon_type].lifetime * Weapon_info[tp->turret_weapon_type].max_speed, Weapon_info[tp->turret_weapon_type].weapon_range);
2854
2855         // Set flag based on strength of weapons subsystem.  If weapons subsystem is destroyed, don't let turrets fire at bombs
2856         weapon_system_ok = 0;
2857         if ( ship_get_subsystem_strength( &Ships[Objects[turret_parent_objnum].instance], SUBSYSTEM_WEAPONS ) > 0 ) {
2858                 weapon_system_ok = 1;
2859         }
2860
2861         // Initialize eeo struct.
2862         eeo.turret_parent_objnum = turret_parent_objnum;
2863         eeo.weapon_system_ok = weapon_system_ok;
2864         eeo.weapon_travel_dist = weapon_travel_dist;
2865         eeo.big_only_flag = big_only_flag;
2866         eeo.enemy_team_mask = enemy_team_mask;
2867         eeo.current_enemy = current_enemy;
2868         eeo.tpos = tpos;
2869         eeo.tvec = tvec;
2870         eeo.turret_subsys = turret_subsys;
2871
2872         eeo.nearest_attacker_dist = 99999.0f;
2873         eeo.nearest_attacker_objnum = -1;
2874
2875         eeo.nearest_homing_bomb_dist = 99999.0f;
2876         eeo.nearest_homing_bomb_objnum = -1;
2877
2878         eeo.nearest_bomb_dist = 99999.0f;
2879         eeo.nearest_bomb_objnum = -1;
2880
2881         eeo.nearest_dist = 99999.0f;
2882         eeo.nearest_objnum = -1;
2883
2884
2885         // Missile_obj_list
2886         for( mo = GET_FIRST(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
2887                 objp = &Objects[mo->objnum];
2888                 evaluate_obj_as_target(objp, &eeo);
2889         }
2890         // highest priority
2891         if ( eeo.nearest_homing_bomb_objnum != -1 ) {                                   // highest priority is an incoming homing bomb
2892                 return eeo.nearest_homing_bomb_objnum;
2893         } else if ( eeo.nearest_bomb_objnum != -1 ) {                                   // next highest priority is an incoming dumbfire bomb
2894                 return eeo.nearest_bomb_objnum;
2895         }
2896
2897
2898         // Ship_used_list
2899         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2900                 objp = &Objects[so->objnum];
2901                 evaluate_obj_as_target(objp, &eeo);
2902         }
2903
2904         SDL_assert(eeo.nearest_attacker_objnum < 0 || is_target_beam_valid(turret_subsys, eeo.nearest_attacker_objnum));
2905                 // next highest priority is attacking ship
2906         if ( eeo.nearest_attacker_objnum != -1 ) {                      // next highest priority is an attacking ship
2907                 return eeo.nearest_attacker_objnum;
2908          }
2909
2910
2911 #if !(defined(FS2_DEMO) || defined(FS1_DEMO))
2912                 asteroid_obj *ao;
2913         // Asteroid_obj_list
2914         for( ao = GET_FIRST(&Asteroid_obj_list); ao != END_OF_LIST(&Asteroid_obj_list); ao = GET_NEXT(ao) ) {
2915                 objp = &Objects[ao->objnum];
2916                 evaluate_obj_as_target(objp, &eeo);
2917         }
2918 #endif
2919
2920         return eeo.nearest_objnum;                                                                              // lowest priority is the closest enemy objnum
2921 }
2922
2923 //      Return timestamp until a ship can find an enemy.
2924 //      Yes, no parameters.  Based solely on skill level.
2925 int get_enemy_timestamp()
2926 {
2927         return (NUM_SKILL_LEVELS - Game_skill_level) * ( (myrand() % 500) + 500);
2928 }
2929
2930 // -------------------------------------------------------------------
2931 //      Return objnum if enemy found, else return -1;
2932 //      Don't attack a ship that already has at least max_attackers attacking it.
2933 int find_enemy(int objnum, float range, int max_attackers)
2934 {
2935         int     enemy_team_mask;
2936
2937         enemy_team_mask = get_enemy_team_mask(objnum);
2938
2939         //      if target_objnum != -1, use that as goal.
2940         ai_info *aip = &Ai_info[Ships[Objects[objnum].instance].ai_index];
2941         if (timestamp_elapsed(aip->choose_enemy_timestamp)) {
2942                 aip->choose_enemy_timestamp = timestamp(get_enemy_timestamp());
2943                 if (aip->target_objnum != -1) {
2944                         int     target_objnum = aip->target_objnum;
2945
2946                         // DKA don't undo object as target in nebula missions.
2947                         // This could cause attack on ship on fringe on nebula to stop if attackee moves our of nebula range.  (BAD)
2948                         if (Objects[target_objnum].signature == aip->target_signature) {
2949                                 if (Ships[Objects[target_objnum].instance].team & enemy_team_mask) {
2950                                         if (!(Objects[target_objnum].flags & OF_PROTECTED)) {
2951                                                 // nprintf(("AI", "Frame %i: Object %i resuming goal of object %i\n", AI_FrameCount, objnum, target_objnum));
2952                                                 return target_objnum;
2953                                         }
2954                                 }
2955                         } else {
2956                                 aip->target_objnum = -1;
2957                                 aip->target_signature = -1;
2958                         }
2959                 }
2960                 return get_nearest_objnum(objnum, enemy_team_mask, aip->enemy_wing, range, max_attackers);
2961         } else {
2962                 aip->target_objnum = -1;
2963                 aip->target_signature = -1;
2964                 return -1;
2965         }
2966
2967 }
2968
2969 int Use_parent_target = 0;
2970 DCF_BOOL(use_parent_target, Use_parent_target)
2971
2972 // -------------------------------------------------------------------
2973 //      Return objnum if enemy found, else return -1;
2974 //
2975 // input:
2976 //                              turret_subsys   => pointer to turret subsystem
2977 //                              objnum                  => parent objnum for the turret
2978 //                              tpos                            => position of turret (world coords)
2979 //                              tvec                            => forward vector of turret (world coords)
2980 //                              current_enemy   =>      objnum of current turret target
2981 int find_turret_enemy(ship_subsys *turret_subsys, int objnum, vector *tpos, vector *tvec, int current_enemy, float fov, int big_only_flag = 0)
2982 {
2983         int                                     enemy_team_mask, enemy_objnum;
2984         model_subsystem *tp;
2985         ship_info                       *sip;
2986
2987         tp = turret_subsys->system_info;
2988         enemy_team_mask = get_enemy_team_mask(objnum);
2989
2990         //      If a small ship and target_objnum != -1, use that as goal.
2991         ai_info *aip = &Ai_info[Ships[Objects[objnum].instance].ai_index];
2992         sip = &Ship_info[Ships[Objects[objnum].instance].ship_info_index];
2993
2994         if ((sip->flags & SIF_SMALL_SHIP) && (aip->target_objnum != -1)) {
2995                 int target_objnum = aip->target_objnum;
2996
2997                 if (Objects[target_objnum].signature == aip->target_signature) {
2998                         if (Ships[Objects[target_objnum].instance].team & enemy_team_mask) {
2999                                 if ( !(Objects[target_objnum].flags & OF_PROTECTED) ) {         // check this flag as well.
3000                                         // nprintf(("AI", "Frame %i: Object %i resuming goal of object %i\n", AI_FrameCount, objnum, target_objnum));
3001                                         return target_objnum;
3002                                 }
3003                         }
3004                 } else {
3005                         aip->target_objnum = -1;
3006                         aip->target_signature = -1;
3007                 }
3008         // Not small or small with target objnum
3009         } else {
3010                 // maybe use aip->target_objnum as next target
3011                 if ((frand() < 0.8f) && (aip->target_objnum != -1) && Use_parent_target) {
3012
3013                         //check if aip->target_objnum is valid target
3014                         int target_flags = Objects[aip->target_objnum].flags;
3015                         if ( target_flags & OF_PROTECTED ) {
3016                                 // AL 2-27-98: why is a protected ship being targeted?
3017                                 set_target_objnum(aip, -1);
3018                                 return -1;
3019                         }
3020
3021                         // maybe use ship target_objnum if valid for turret
3022                         // check for beam weapon and beam protected
3023                         if ( !((target_flags & OF_BEAM_PROTECTED) && (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM)) ) {
3024                                 if ( Objects[aip->target_objnum].type == OBJ_SHIP ) {
3025                                         // check for huge weapon and huge ship
3026                                         if ( !big_only_flag || (Ship_info[Ships[Objects[aip->target_objnum].instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) ) {
3027                                                 // check for tagged only and tagged ship
3028                                                 if ( (turret_subsys->weapons.flags & SW_FLAG_TAGGED_ONLY) && ship_is_tagged(&Objects[aip->target_objnum]) ) {
3029                                                         // select new target if aip->target_objnum is out of field of view
3030                                                         vector v2e;
3031                                                         float dot;//, dist;
3032                                                         /*dist =*/ vm_vec_normalized_dir(&v2e, &Objects[aip->target_objnum].pos, tpos);
3033                                                         dot = vm_vec_dot(&v2e, tvec);
3034                                                         //      MODIFY FOR ATTACKING BIG SHIP
3035                                                         // dot += (0.5f * Objects[aip->target_objnum].radius / dist);
3036                                                         if (dot > fov) {
3037                                                                 return aip->target_objnum;
3038                                                         }
3039                                                 }
3040                                         }
3041                                 }
3042                         }
3043                 }
3044         }
3045
3046         enemy_objnum = get_nearest_turret_objnum(objnum, turret_subsys, enemy_team_mask, tpos, tvec, current_enemy, big_only_flag);
3047         if ( enemy_objnum >= 0 ) {
3048                 SDL_assert( !((Objects[enemy_objnum].flags & OF_BEAM_PROTECTED) && (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM)) );
3049                 if ( Objects[enemy_objnum].flags & OF_PROTECTED ) {
3050                         Int3();
3051                         enemy_objnum = aip->target_objnum;
3052                 }
3053         }
3054
3055         return enemy_objnum;
3056 }
3057
3058 //      If issued an order to a ship that's awaiting repair, abort that process.
3059 //      However, do not abort process for an object that is currently being repaired -- let it finish.
3060 void ai_set_goal_maybe_abort_dock(object *objp, ai_info *aip)
3061 {
3062         if (aip->ai_flags & AIF_AWAITING_REPAIR) {
3063                 object  *repair_obj;
3064
3065                 if (aip->dock_objnum == -1) {
3066                         repair_obj = NULL;
3067                 } else {
3068                         repair_obj = &Objects[aip->dock_objnum];
3069                 }
3070                 ai_do_objects_repairing_stuff( objp, repair_obj, REPAIR_INFO_ABORT );
3071         }
3072         aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP);    //      Might request again after 30 seconds.
3073 }
3074
3075 void force_avoid_player_check(object *objp, ai_info *aip)
3076 {
3077         if (Ships[objp->instance].team == Player_ship->team){
3078                 aip->avoid_check_timestamp = timestamp(0);              //      Force a check for collision next frame.
3079         }
3080 }
3081
3082 //      --------------------------------------------------------------------------
3083 //      Set *attacked as object to attack for object *attacker
3084 //      If attacked == NULL, then attack any enemy object.
3085 //      Attack point *rel_pos on object.  This is for supporting attacking subsystems.
3086 void ai_attack_object(object *attacker, object *attacked, int priority, ship_subsys *ssp)
3087 {
3088         ai_info *aip;
3089
3090         SDL_assert(attacker != NULL);
3091         SDL_assert(attacker->instance != -1);
3092         SDL_assert(Ships[attacker->instance].ai_index != -1);
3093
3094         aip = &Ai_info[Ships[attacker->instance].ai_index];
3095         force_avoid_player_check(attacker, aip);
3096
3097         aip->ok_to_target_timestamp = timestamp(0);             //      Guarantee we can target.
3098
3099 //      if (!SDL_strncasecmp(Ships[attacker->instance].ship_name, NOX("Kami"), 4)) {
3100 //              aip->ai_flags |= AIF_KAMIKAZE;
3101 //              aip->ai_flags |= AIF_NO_DYNAMIC;
3102 //      }
3103
3104         if (attacker == attacked) {
3105                 Int3();         //      Bogus!  Who tried to get me to attack myself!  Trace out and fix!
3106                 return;
3107         }
3108
3109         //      Only set to chase if a fighter or bomber, otherwise just return.
3110         if (!(Ship_info[Ships[attacker->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
3111 //              nprintf(("AI","Note: AI ship %s refusing to set AI mode to AIM_CHASE\n", Ships[attacker->instance].ship_name));
3112 //              return;
3113                 nprintf(("AI", "AI ship %s is large ship ordered to attack %s\n", Ships[attacker->instance].ship_name, Ships[attacked->instance].ship_name));
3114         }
3115
3116         //      This is how "engage enemy" gets processed
3117         if (attacked == NULL) {
3118                 aip->choose_enemy_timestamp = timestamp(0);
3119                 // nebula safe
3120                 set_target_objnum(aip, find_enemy(attacker-Objects, 99999.9f, 4));
3121         } else {
3122                 // check if we can see atacked in nebula
3123                 if (aip->target_objnum != attacked - Objects) {
3124                         aip->aspect_locked_time = 0.0f;
3125                 }
3126                 set_target_objnum(aip, attacked - Objects);
3127         }
3128
3129         ai_set_goal_maybe_abort_dock(attacker, aip);
3130         aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);     //      No dynamic targeting for 7 seconds.
3131
3132         if (is_ignore_object(aip, aip->target_objnum)) {
3133                 aip->ignore_objnum = UNUSED_OBJNUM;
3134         }
3135
3136         aip->mode = AIM_CHASE;
3137         aip->submode = SM_ATTACK;       // AL 12-15-97: need to set submode?  I got an assert() where submode was bogus
3138                                                                                 //                                       for AIM_CHASE... it may have been not set correctly here
3139         if (ssp == NULL) {
3140                 set_targeted_subsys(aip, NULL, -1);
3141                 if (aip->target_objnum != -1) {
3142                         //nprintf(("AI", "Unprotecting ship %s\n", Ships[Objects[aip->target_objnum].instance].ship_name));
3143                         Objects[aip->target_objnum].flags &= ~OF_PROTECTED;     //      If ship had been protected, unprotect it.
3144                 }
3145         } else {
3146                 Int3(); //      Not supported yet!
3147         }
3148 }
3149
3150 //      --------------------------------------------------------------------------
3151 //      Set *attacked as object to attack for object *attacker
3152 //      Attack point *rel_pos on object.  This is for supporting attacking subsystems.
3153 void ai_attack_wing(object *attacker, int wingnum, int priority)
3154 {
3155         ai_info *aip;
3156
3157         SDL_assert(attacker != NULL);
3158         SDL_assert(attacker->instance != -1);
3159         SDL_assert(Ships[attacker->instance].ai_index != -1);
3160
3161         aip = &Ai_info[Ships[attacker->instance].ai_index];
3162
3163         aip->enemy_wing = wingnum;
3164         aip->mode = AIM_CHASE;
3165         aip->submode = SM_ATTACK;       // AL 12-15-97: need to set submode?  I got an assert() where submode was bogus
3166                                                                                 //                                       for AIM_CHASE... it may have been not set correctly here
3167
3168         aip->ok_to_target_timestamp = timestamp(0);             //      Guarantee we can target.
3169
3170         int count = Wings[wingnum].current_count;
3171         if (count > 0) {
3172                 int     index;
3173
3174                 index = (int) (frand() * count);
3175
3176                 if (index >= count)
3177                         index = 0;
3178
3179                 set_target_objnum(aip, Ships[Wings[wingnum].ship_index[index]].objnum);
3180
3181                 ai_set_goal_maybe_abort_dock(attacker, aip);
3182                 aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);     //      No dynamic targeting for 7 seconds.
3183         }
3184 }
3185
3186 //      --------------------------------------------------------------------------
3187 //      Set *evaded as object for *evader to evade.
3188 void ai_evade_object(object *evader, object *evaded, int priority)
3189 {
3190         ai_info *aip;
3191
3192         SDL_assert(evader != NULL);
3193         SDL_assert(evaded != NULL);
3194         SDL_assert(evader->instance != -1);
3195         SDL_assert(Ships[evader->instance].ai_index != -1);
3196
3197         if (evaded == evader) {
3198                 Int3(); //      Bogus!  Who tried to get me to evade myself!  Trace out and fix!
3199                 return;
3200         }
3201
3202         aip = &Ai_info[Ships[evader->instance].ai_index];
3203
3204         set_target_objnum(aip, evaded - Objects);
3205         aip->mode = AIM_EVADE;
3206
3207 }
3208
3209 //      Ignore some object without changing mode.
3210 void ai_ignore_object(object *ignorer, object *ignored, int priority)
3211 {
3212         ai_info *aip;
3213
3214         SDL_assert(ignorer != NULL);
3215         SDL_assert(ignored != NULL);
3216         SDL_assert(ignorer->instance != -1);
3217         SDL_assert(Ships[ignorer->instance].ai_index != -1);
3218         SDL_assert(ignorer != ignored);
3219
3220         aip = &Ai_info[Ships[ignorer->instance].ai_index];
3221
3222         //      MK, 5/17/98, removing ignoring of wings.
3223         //      It's too confusing.  It often causes mysterious behavior in which fighters unexpectedly refuse to attack anything.
3224 /*      if (Ships[ignored->instance].wingnum > -1) {
3225                 int wingnum, i;
3226
3227                 wingnum = Ships[ignored->instance].wingnum;
3228                 aip->ignore_objnum = -(wingnum+1);
3229                 // set protected bit for each ship in a wing
3230                 //      MK, 4/23/98: Only set for fighters if they are the original "ignored" object
3231                 for (i = 0; i < Wings[wingnum].current_count; i++ ) {
3232                         object  *objp;
3233
3234                         objp = &Objects[Ships[Wings[wingnum].ship_index[i]].objnum];
3235                         if (objp != ignored) {
3236                                 if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER))
3237                                         continue;
3238                         }
3239
3240                         Objects[Ships[Wings[wingnum].ship_index[i]].objnum].flags |= OF_PROTECTED;
3241                 }
3242
3243         } else {
3244         */ {
3245                 aip->ignore_objnum = ignored - Objects;
3246                 aip->ignore_signature = ignored->signature;
3247                 aip->ai_flags &= ~AIF_TEMPORARY_IGNORE;
3248                 ignored->flags |= OF_PROTECTED;                                 // set protected bit of ignored ship.
3249         }
3250
3251 }
3252
3253 //      Ignore some object without changing mode.
3254 void ai_ignore_wing(object *ignorer, int wingnum, int priority)
3255 {
3256         ai_info *aip;
3257
3258         SDL_assert(ignorer != NULL);
3259         SDL_assert(ignorer->instance != -1);
3260         SDL_assert(Ships[ignorer->instance].ai_index != -1);
3261         SDL_assert((wingnum >= 0) && (wingnum < MAX_WINGS));
3262
3263         aip = &Ai_info[Ships[ignorer->instance].ai_index];
3264
3265         aip->ignore_objnum = -(wingnum +1);
3266         aip->ai_flags &= ~AIF_TEMPORARY_IGNORE;
3267 }
3268
3269
3270 //      Add a path point in the global buffer Path_points.
3271 //      modify_index = index in Path_points at which to store path point.
3272 //      If modify_index == -1, then create a new point.
3273 //      If a new point is created (ie, modify_index == -1), then Ppfp is updated.
3274 void add_path_point(vector *pos, int path_num, int path_index, int modify_index)
3275 {
3276         pnode   *pnp;
3277
3278         if (modify_index == -1) {
3279                 SDL_assert(Ppfp-Path_points < MAX_PATH_POINTS-1);
3280                 pnp = Ppfp;
3281                 Ppfp++;
3282         } else {
3283                 SDL_assert((modify_index >= 0) && (modify_index < MAX_PATH_POINTS-1));
3284                 pnp = &Path_points[modify_index];
3285         }
3286
3287         pnp->pos = *pos;
3288         pnp->path_num = path_num;
3289         pnp->path_index = path_index;
3290 }
3291
3292 //      Given two points on a sphere, the center of the sphere and the radius, return a
3293 //      point on the vector through the midpoint of the chord on the sphere.
3294 void bisect_chord(vector *p0, vector *p1, vector *centerp, float radius)
3295 {
3296         vector  tvec;
3297         vector  new_pnt;
3298
3299         vm_vec_add(&tvec, p0, p1);
3300         vm_vec_sub2(&tvec, centerp);
3301         vm_vec_sub2(&tvec, centerp);
3302         if (vm_vec_mag_quick(&tvec) < 0.1f) {
3303                 vm_vec_sub(&tvec, p0, p1);
3304                 if (fl_abs(tvec.xyz.x) <= fl_abs(tvec.xyz.z)){
3305                         tvec.xyz.x = -tvec.xyz.z;
3306                 } else {
3307                         tvec.xyz.y = -tvec.xyz.x;
3308                 }
3309         }
3310
3311         vm_vec_normalize(&tvec);
3312         vm_vec_scale(&tvec, radius);
3313         vm_vec_add(&new_pnt, centerp, &tvec);
3314
3315         add_path_point(&new_pnt, -1, -1, -1);
3316 }
3317                         
3318 //      Create a path from the current position to a goal position.
3319 //      The current position is in the current object and the goal position is
3320 //      in the goal object.
3321 //      It is ok to intersect the current object, but not the goal object.
3322 //      This function is useful for creating a path to an initial point near a large
3323 //      object.
3324 //
3325 // input:       subsys_path:    optional param (default 0), indicates this is a path to a subsystem
3326 void create_path_to_point(vector *curpos, vector *goalpos, object *curobjp, object *goalobjp, int subsys_path)
3327 {
3328         //      If can't cast vector to goalpos, then create an intermediate point.
3329         if (pp_collide(curpos, goalpos, goalobjp, curobjp->radius)) {
3330                 vector  tan1;
3331                 float           radius;
3332
3333                 // If this is a path to a subsystem, use SUBSYS_PATH_DIST as the radius for the object you are
3334                 // trying to avoid.  This is needed since subsystem paths extend out to SUBSYS_PATH_DIST, and we
3335                 // want ships to reach their path destination without flying to points that sit on the radius of
3336                 // a small ship
3337                 radius = goalobjp->radius;
3338                 if (subsys_path) {
3339                         if ( SUBSYS_PATH_DIST > goalobjp->radius ) {
3340                                 radius = SUBSYS_PATH_DIST;
3341                         }
3342                 }
3343
3344                 //      The intermediate point is at the intersection of:
3345                 //              tangent to *goalobjp sphere at point *goalpos
3346                 //              tangent to *goalobjp sphere through point *curpos in plane defined by *curpos, *goalpos, goalobjp->pos
3347                 //      Note, there are two tangents through *curpos, unless *curpos is on the
3348                 //      sphere.  The tangent that causes the nearer intersection (to *goalpos) is chosen.
3349                 get_tangent_point(&tan1, curpos, &goalobjp->pos, goalpos, radius);
3350
3351                 //      If we can't reach tan1 from curpos, insert a new point.
3352                 if (pp_collide(&tan1, curpos, goalobjp, curobjp->radius))
3353                         bisect_chord(curpos, &tan1, &goalobjp->pos, radius);
3354
3355                 add_path_point(&tan1, -1, -1, -1);
3356
3357                 //      If we can't reach goalpos from tan1, insert a new point.
3358                 if (pp_collide(goalpos, &tan1, goalobjp, curobjp->radius))
3359                         bisect_chord(goalpos, &tan1, &goalobjp->pos, radius);
3360         }
3361
3362 }
3363
3364 //      Given an object and a model path, globalize the points on the model
3365 //      and copy into the global path list.
3366 //      If pnp != NULL, then modify, in place, the path points.  This is used to create new
3367 //      globalized points when the base object has moved.
3368 // input:       randomize_pnt   => optional parameter (default value -1), add random vector in sphere to this path point
3369 void copy_xlate_model_path_points(object *objp, model_path *mp, int dir, int count, int path_num, pnode *pnp, int randomize_pnt)
3370 {
3371         matrix  m;
3372         int             i;
3373         vector  v1;
3374         int             pp_index;               //      index in Path_points at which to store point, if this is a modify-in-place (pnp ! NULL)
3375         int             start_index, finish_index;
3376         
3377         // nprintf(("AI", "Creating path for object %s in frame #%i\n", Ships[objp->instance].ship_name, AI_FrameCount));
3378         
3379         //      Initialize pp_index.
3380         //      If pnp == NULL, that means we're creating new points.  If not NULL, then modify in place.
3381         if (pnp == NULL)
3382                 pp_index = -1;                  //      This tells add_path_point to create a new point.
3383         else
3384                 pp_index = 0;                   //      pp_index will get assigned to index in Path_points to reuse.
3385
3386         vm_copy_transpose_matrix(&m, &objp->orient);
3387
3388         if (dir == 1) {
3389                 start_index = 0;
3390                 finish_index = min(count, mp->nverts);
3391         } else {
3392                 SDL_assert(dir == -1);  //      direction must be up by 1 or down by 1 and it's neither!
3393                 start_index = mp->nverts-1;
3394                 finish_index = max(-1, mp->nverts-1-count);
3395         }
3396
3397         int offset = 0;
3398         for (i=start_index; i != finish_index; i += dir) {
3399                 //      Globalize the point.
3400                 vm_vec_rotate(&v1, &mp->verts[i].pos, &m);
3401                 vm_vec_add2(&v1, &objp->pos);
3402
3403                 if ( randomize_pnt == i ) {
3404                         vector v_rand;
3405                         static_randvec(OBJ_INDEX(objp), &v_rand);
3406                         vm_vec_scale(&v_rand, 30.0f);
3407                         vm_vec_add2(&v1, &v_rand);
3408                 }
3409
3410                 if (pp_index != -1)
3411                         pp_index = pnp-Path_points + offset;
3412
3413                 add_path_point(&v1, path_num, i, pp_index);
3414                 offset++;
3415         }
3416 }
3417
3418
3419 //      For pl_objp, create a path along path path_num into mobjp.
3420 //      The tricky part of this problem is creating the entry to the first point on the
3421 //      predefined path.  The points on this entry path are based on the location of Pl_objp
3422 //      relative to the start of the path.
3423 //
3424 // input:
3425 //                              subsys_path:    optional param (default 0), indicating this is a path to a subsystem
3426 void create_model_path(object *pl_objp, object *mobjp, int path_num, int subsys_path)
3427 {       
3428         ship                    *shipp = &Ships[pl_objp->instance];
3429         ai_info         *aip = &Ai_info[shipp->ai_index];
3430
3431         ship_info       *osip = &Ship_info[Ships[mobjp->instance].ship_info_index];
3432         polymodel       *pm = model_get(osip->modelnum);
3433         int                     num_points;
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         num_points = mp->nverts;
3452
3453         SDL_assert(Ppfp-Path_points + num_points + 4 < MAX_PATH_POINTS);
3454
3455         vm_copy_transpose_matrix(&m, &mobjp->orient);
3456         vm_vec_rotate(&gp0, &mp->verts[0].pos, &m);
3457         vm_vec_add2(&gp0, &mobjp->pos);
3458
3459         if (pp_collide(&pl_objp->pos, &gp0, mobjp, pl_objp->radius)) {
3460                 vector  perim_point1;
3461                 vector  perim_point2;
3462
3463                 perim_point2 = pl_objp->pos;
3464                 
3465                 //      If object that wants to dock is inside bounding sphere of object it wants to dock with, make it fly out.
3466                 //      Assume it can fly "straight" out to the bounding sphere.
3467                 if (vm_vec_dist_quick(&pl_objp->pos, &mobjp->pos) < mobjp->radius) {
3468                         project_point_to_perimeter(&perim_point2, &mobjp->pos, mobjp->radius, &pl_objp->pos);
3469                         add_path_point(&perim_point2, path_num, -1, -1);
3470                 }
3471
3472                 //      If last point on pre-defined path is inside bounding sphere, create a new point on the surface of the sphere.
3473                 if (vm_vec_dist_quick(&mobjp->pos, &gp0) < mobjp->radius) {
3474                         project_point_to_perimeter(&perim_point1, &mobjp->pos, mobjp->radius, &gp0);
3475                         create_path_to_point(&perim_point2, &perim_point1, pl_objp, mobjp, subsys_path);
3476                         add_path_point(&perim_point1, path_num, -1, -1);
3477                 } else {                //      The predefined path extends outside the sphere.  Create path to that point.
3478                         create_path_to_point(&perim_point2, &gp0, pl_objp, mobjp, subsys_path);
3479                 }
3480         }
3481
3482         // AL 12-31-97: If following a subsystem path, add random vector to second last path point
3483         if ( subsys_path ) {
3484                 copy_xlate_model_path_points(mobjp, mp, 1, mp->nverts, path_num, NULL, mp->nverts-2);
3485         } else {
3486                 copy_xlate_model_path_points(mobjp, mp, 1, mp->nverts, path_num, NULL);
3487         }
3488
3489         aip->path_cur = aip->path_start;
3490         aip->path_dir = PD_FORWARD;
3491         aip->path_objnum = mobjp-Objects;
3492         aip->mp_index = path_num;
3493         aip->path_length = Ppfp - ppfp_start;
3494         aip->path_next_check_time = timestamp(1);
3495
3496         aip->path_goal_obj_hash = create_object_hash(&Objects[aip->path_objnum]);
3497
3498         aip->path_next_create_time = timestamp(1000);   //      OK to try to create one second later
3499         aip->path_create_pos = pl_objp->pos;
3500         aip->path_create_orient = pl_objp->orient;
3501
3502         aip->ai_flags &= ~AIF_USE_EXIT_PATH;                    // ensure this flag is cleared
3503 }
3504
3505 //      For pl_objp, create a path along path path_num into mobjp.
3506 //      The tricky part of this problem is creating the entry to the first point on the
3507 //      predefined path.  The points on this entry path are based on the location of pl_objp
3508 //      relative to the start of the path.
3509 void create_model_exit_path(object *pl_objp, object *mobjp, int path_num, int count)
3510 {       
3511         ship                    *shipp = &Ships[pl_objp->instance];
3512         ai_info         *aip = &Ai_info[shipp->ai_index];
3513
3514         ship_info       *osip = &Ship_info[Ships[mobjp->instance].ship_info_index];
3515         polymodel       *pm = model_get(osip->modelnum);
3516         int                     num_points;
3517         model_path      *mp;
3518         pnode                   *ppfp_start = Ppfp;
3519
3520         aip->path_start = Ppfp - Path_points;
3521         SDL_assert(path_num < pm->n_paths);
3522         
3523         mp = &pm->paths[path_num];
3524         num_points = mp->nverts;
3525
3526         SDL_assert(Ppfp-Path_points + num_points + 4 < MAX_PATH_POINTS);
3527
3528         copy_xlate_model_path_points(mobjp, mp, -1, count, path_num, NULL);
3529
3530         aip->path_cur = aip->path_start;
3531         aip->path_dir = PD_FORWARD;
3532         aip->path_objnum = mobjp-Objects;
3533         aip->mp_index = path_num;
3534         aip->path_length = Ppfp - ppfp_start;
3535         aip->path_next_check_time = timestamp(1);
3536
3537         aip->ai_flags |= AIF_USE_EXIT_PATH;             // mark as exit path, referenced in maybe
3538 }
3539
3540 //      Return true if the vector from curpos to goalpos intersects with any ship other than the ignore objects.
3541 //      Calls pp_collide
3542 int pp_collide_any(vector *curpos, vector *goalpos, float radius, object *ignore_objp1, object *ignore_objp2, int big_only_flag)
3543 {
3544         ship_obj        *so;    
3545
3546         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
3547                 object *objp = &Objects[so->objnum];
3548
3549                 if (big_only_flag) {
3550                         if (!(Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)))
3551                                 continue;
3552                 }
3553
3554                 if ((objp != ignore_objp1) && (objp != ignore_objp2)) {
3555                         if (pp_collide(curpos, goalpos, objp, radius))
3556                                 return OBJ_INDEX(objp);
3557                 }
3558         }
3559
3560         return -1;
3561 }
3562
3563 //      Used to create docking paths and other pre-defined paths through ships.
3564 //      Creates a path in absolute space.
3565 //      Create a path into the object objnum.
3566 //
3567 // input:
3568 //      pl_objp:                        object that will use the path
3569 //      objnum:                 Object to find path to.
3570 //      path_num:               model path index to use
3571 //      exit_flag:              true means this is an exit path in the model
3572 // subsys_path: optional param (default 0) that indicates this is a path to a subsystem
3573 //      Exit:
3574 //      ai_info struct in Pl_objp gets stuffed with information to enable Pl_objp to fly the path.
3575 void ai_find_path(object *pl_objp, int objnum, int path_num, int exit_flag, int subsys_path)
3576 {
3577         ai_info *aip = &Ai_info[Ships[pl_objp->instance].ai_index];
3578
3579         SDL_assert(path_num >= 0);
3580
3581         //      This is test code, find an object with paths.
3582         if (objnum != -1) {
3583                 object  *objp = &Objects[objnum];
3584
3585                 if (objp->type == OBJ_SHIP) {
3586                         polymodel *pm;
3587
3588                         ship    *shipp = &Ships[objp->instance];
3589                         pm = model_get( shipp->modelnum );
3590                         SDL_assert(pm->n_paths > path_num);
3591                         aip->goal_objnum = objp-Objects;
3592                         aip->goal_signature = objp->signature;
3593                         if (exit_flag)
3594                                 create_model_exit_path(pl_objp, objp, path_num);
3595                         else
3596                                 create_model_path(pl_objp, objp, path_num, subsys_path);
3597                         return;
3598                 }
3599
3600         }
3601 }
3602
3603 extern int vector_object_collision(vector *start_pos, vector *end_pos, object *objp, float radius_scale);
3604
3605 //      Maybe make *objp avoid a player object.
3606 //      For now, 4/6/98, only check Player_obj.
3607 //      If player collision would occur, set AIF_AVOIDING_SMALL_SHIP bit in ai_flags.
3608 //      Set aip->avoid_goal_point
3609 int maybe_avoid_player(object *objp, vector *goal_pos)
3610 {
3611         ai_info *aip;
3612         vector  cur_pos, new_goal_pos;
3613         object  *player_objp;
3614         vector  n_vec_to_goal, n_vec_to_player;
3615
3616         aip = &Ai_info[Ships[objp->instance].ai_index];
3617
3618         if (!timestamp_elapsed(aip->avoid_check_timestamp))
3619                 return 0;
3620
3621         player_objp = Player_obj;
3622
3623         float   speed_time;
3624
3625         //      How far two ships could be apart and still collide within one second.
3626         speed_time = player_objp->phys_info.speed + objp->phys_info.speed;
3627
3628         float   obj_obj_dist;
3629
3630         obj_obj_dist = vm_vec_dist_quick(&player_objp->pos, &objp->pos);
3631
3632         if (obj_obj_dist > speed_time*2.0f)
3633                 return 0;
3634
3635         cur_pos = objp->pos;
3636
3637         new_goal_pos = *goal_pos;
3638
3639         float dist = vm_vec_normalized_dir(&n_vec_to_goal, goal_pos, &objp->pos);
3640         vm_vec_normalized_dir(&n_vec_to_player, &player_objp->pos, &objp->pos);
3641
3642         if (dist > speed_time*2.0f) {
3643                 vm_vec_scale_add(&new_goal_pos, &objp->pos, &n_vec_to_goal, 200.0f);
3644         }
3645
3646         if (vector_object_collision(&objp->pos, &new_goal_pos, player_objp, 1.5f)) {
3647                 aip->ai_flags |= AIF_AVOIDING_SMALL_SHIP;
3648
3649                 vector  avoid_vec;
3650
3651                 vm_vec_sub(&avoid_vec, &n_vec_to_goal, &n_vec_to_player);
3652                 if (vm_vec_mag_quick(&avoid_vec) < 0.01f) {
3653                         vm_vec_copy_scale(&avoid_vec, &objp->orient.v.rvec, frand()-0.5f);
3654                         vm_vec_scale_add2(&avoid_vec, &objp->orient.v.uvec, frand()-0.5f);
3655                         vm_vec_normalize(&avoid_vec);
3656                 } else {
3657                         vector  tvec1;
3658                         vm_vec_normalize(&avoid_vec);
3659                         vm_vec_crossprod(&tvec1, &n_vec_to_goal, &avoid_vec);
3660                         vm_vec_crossprod(&avoid_vec, &tvec1, &n_vec_to_player);
3661                 }
3662
3663                 //      Now, avoid_vec is a vector perpendicular to the vector to the player and the direction *objp
3664                 //      should fly in to avoid the player while still approaching its goal.
3665                 vm_vec_scale_add(&aip->avoid_goal_point, &player_objp->pos, &avoid_vec, 400.0f);
3666
3667                 aip->avoid_check_timestamp = timestamp(1000);
3668
3669                 return 1;
3670         } else {
3671                 aip->ai_flags &= ~AIF_AVOIDING_SMALL_SHIP;
3672                 aip->avoid_check_timestamp = timestamp((int) (obj_obj_dist/200.0f) + 500);
3673
3674                 return 0;
3675         }
3676 }
3677
3678 //      Make object *still_objp enter AIM_STILL mode.
3679 //      Make it point at view_pos.
3680 void ai_stay_still(object *still_objp, vector *view_pos)
3681 {
3682         ship    *shipp;
3683         ai_info *aip;
3684
3685         SDL_assert(still_objp->type == OBJ_SHIP);
3686         SDL_assert((still_objp->instance >= 0) && (still_objp->instance < MAX_OBJECTS));
3687
3688         shipp = &Ships[still_objp->instance];
3689         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
3690
3691         aip = &Ai_info[shipp->ai_index];
3692
3693         aip->mode = AIM_STILL;
3694
3695         //      If view_pos not NULL, point at that point.  Else, point at a point directly in front of ship.  Ie, don't turn.
3696         if (view_pos != NULL)
3697                 aip->goal_point = *view_pos;
3698         else
3699                 vm_vec_scale_add(&aip->goal_point, &still_objp->pos, &still_objp->orient.v.fvec, 100.0f);
3700 }
3701
3702 // code which is called from ai_dock_with_object and ai_dock to set flags and apprioriate variable
3703 // when two objects have completed docking.  used because we can dock object initially at misison load
3704 // time (meaning that ai_dock() might never get called).  docker has docked with dockee (i.e. docker
3705 // would be a freighter and dockee would be a cargo).
3706 void ai_do_objects_docked_stuff(object *docker, object *dockee)
3707 {
3708         ai_info *aip, *other_aip;
3709
3710         aip = &Ai_info[Ships[docker->instance].ai_index];
3711         other_aip = &Ai_info[Ships[dockee->instance].ai_index];
3712
3713         // set the flags and dock_objnum for both objects
3714         aip->ai_flags |= AIF_DOCKED;
3715         aip->dock_objnum = OBJ_INDEX(dockee);
3716         other_aip->ai_flags |= AIF_DOCKED;
3717         other_aip->dock_objnum = OBJ_INDEX(docker);
3718         aip->dock_signature = dockee->signature;
3719         other_aip->dock_signature = docker->signature;
3720
3721         // add multiplayer hook here to deal with docked objects.  We need to only send information
3722         // about the object that is docking.  Both flags will get updated.
3723         if ( MULTIPLAYER_MASTER )
3724                 send_ai_info_update_packet( docker, AI_UPDATE_DOCK );
3725
3726 }
3727
3728 // code which is called when objects become undocked. Equivalent of above function.
3729 // dockee might not be valid since this code can get called to cleanup after a ship
3730 // has blown up!
3731 void ai_do_objects_undocked_stuff( object *docker, object *dockee )
3732 {
3733         ai_info *aip, *other_aip;
3734
3735         // add multiplayer hook here to deal with undocked objects.  Do it before we
3736         // do anything else.  We don't need to send info for both objects, since we can find
3737         // it be dock_objnum
3738         if ( MULTIPLAYER_MASTER )
3739                 send_ai_info_update_packet( docker, AI_UPDATE_UNDOCK );
3740
3741         aip = &Ai_info[Ships[docker->instance].ai_index];
3742
3743         // set the flags and dock_objnum for both objects
3744         aip->ai_flags &= ~(AIF_DOCKED | AIF_BEING_REPAIRED);
3745         aip->dock_objnum = -1;
3746         
3747         if ( dockee != NULL ) {
3748                 other_aip = &Ai_info[Ships[dockee->instance].ai_index];
3749                 other_aip->ai_flags &= ~(AIF_DOCKED | AIF_BEING_REPAIRED);
3750                 other_aip->dock_objnum = -1;
3751         }
3752
3753 }
3754
3755
3756 //      --------------------------------------------------------------------------
3757 //      Interface from goals code to AI.
3758 //      Cause *docker to dock with *dockee.
3759 //      priority is priority of goal from goals code.
3760 //      dock_type is:
3761 //              AIDO_DOCK               set goal of docking
3762 //              AIDO_DOCK_NOW   immediately dock, used for ships that need to be docked at mission start
3763 //              AIDO_UNDOCK             set goal of undocking
3764 void ai_dock_with_object(object *docker, object *dockee, int priority, int dock_type, int docker_index, int dockee_index)
3765 {
3766         ai_info         *aip;
3767         polymodel       *pm;
3768         ai_info         *dockee_aip;
3769
3770         SDL_assert(docker != NULL);
3771         SDL_assert(dockee != NULL);
3772         SDL_assert(docker->instance != -1);
3773         SDL_assert(Ships[docker->instance].ai_index != -1);
3774         SDL_assert(Ships[dockee->instance].ai_index != -1);
3775         SDL_assert( docker_index != -1 );
3776         SDL_assert( dockee_index != -1 );
3777
3778         aip = &Ai_info[Ships[docker->instance].ai_index];
3779
3780         if ((aip->ai_flags & AIF_DOCKED) && (dock_type == AIDO_DOCK)) {
3781         //      object  *dockee2;
3782         //      int             docker_index2, dockee_index2;
3783
3784                 SDL_assert(aip->dock_objnum > -1);
3785         //      dockee2 = &Objects[aip->dock_objnum];
3786         //      docker_index2 = aip->dock_index;
3787         //      dockee_index2 = aip->dockee_index;
3788                 // MWA -- 2/9/98.  use the goal code to undock the ships since goals might need to get removed
3789                 // and that code will do it properly.  I'd actually be surprised if we got into this code anymore
3790                 // since the outer layer goal code should deal with this issue....but who knows...
3791                 ai_add_goal_ship_internal( aip, AI_GOAL_UNDOCK, NULL, -1, -1, 0 );
3792
3793                 // old code below
3794                 //ai_dock_with_object(docker, dockee2, priority, AIDO_UNDOCK, docker_index2, dockee_index2);
3795                 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));
3796                 nprintf(("AI", "...so ship %s will now undock.\n", Ships[docker->instance].ship_name));
3797                 return;
3798         }
3799
3800         dockee_aip = &Ai_info[Ships[dockee->instance].ai_index];
3801
3802         aip->goal_objnum = dockee - Objects;
3803         aip->goal_signature = dockee->signature;
3804
3805         aip->mode = AIM_DOCK;
3806
3807         switch (dock_type) {
3808         case AIDO_DOCK:
3809                 aip->submode = AIS_DOCK_0;
3810                 break;
3811         case AIDO_DOCK_NOW:
3812                 aip->submode = AIS_DOCK_3A;
3813                 break;
3814         case AIDO_UNDOCK:
3815                 aip->submode = AIS_UNDOCK_0;
3816                 break;
3817         default:
3818                 Int3();         //      Bogus dock_type.
3819         }
3820
3821         aip->submode_start_time = Missiontime;
3822         aip->dock_index = docker_index;
3823         aip->dockee_index = dockee_index;
3824
3825         dockee_aip->dock_index = dockee_index;
3826         dockee_aip->dockee_index = docker_index;
3827
3828         // get the path number to the docking point on the dockee.  Each docking point contains a list
3829         // of paths that the point can be reached by.  Pick the first path in the path list for now.
3830         // We only want to do this stuff if we are docking!!!  Be sure to set the path index
3831         if ((dock_type == AIDO_DOCK) || (dock_type == AIDO_DOCK_NOW)) {
3832                 pm = model_get( Ships[dockee->instance].modelnum );
3833                 SDL_assert( pm->docking_bays[dockee_index].num_spline_paths > 0 );
3834
3835                 // only set the dock path index if we are docking.  undocking will assume that dock_path_index
3836                 // already set from some other docking command
3837                 aip->dock_path_index = dockee_index;
3838                 dockee_aip->dock_path_index = docker_index;
3839         }
3840
3841         if (dock_type != AIDO_DOCK_NOW) {
3842                 int path_num;
3843                 //      Note: Second parameter is dock path index.  This should be specified as an
3844                 //      _input_ to this function and passed through.  The path index should be already
3845                 // set for the undock function
3846                 path_num = ai_return_path_num_from_dockbay(dockee, dockee_index);
3847                 ai_find_path(docker, dockee-Objects, path_num, 0);
3848 //              ai_find_path(dockee-Objects, dockee_index, 0);
3849         } else {
3850                 dock_orient_and_approach(docker, dockee, DOA_DOCK_STAY);
3851                 //aip->dock_objnum = OBJ_INDEX(dockee);
3852                 ai_do_objects_docked_stuff( docker, dockee );
3853         }
3854
3855 }
3856
3857 //      Cause a ship to fly its waypoints.
3858 //      flags tells:
3859 //              WPF_REPEAT      Set -> repeat waypoints.
3860 void ai_start_waypoints(object *objp, int waypoint_list_index, int wp_flags)
3861 {
3862         ai_info *aip;
3863
3864         SDL_assert(waypoint_list_index < Num_waypoint_lists);
3865
3866         //nprintf(("AI", "Frame %i: Ship %s instructed to fly waypoint list #%i\n", AI_FrameCount, Ships[objp->instance].ship_name, waypoint_list_index));
3867         aip = &Ai_info[Ships[objp->instance].ai_index];
3868
3869         if ( (aip->mode == AIM_WAYPOINTS) && (aip->wp_index == waypoint_list_index) )
3870                 return;
3871
3872         aip->ai_flags |= AIF_FORMATION_WING;
3873         aip->ai_flags &= ~AIF_FORMATION_OBJECT;
3874         aip->wp_list = waypoint_list_index;
3875         aip->wp_index = 0;
3876         aip->wp_flags = wp_flags;
3877         aip->mode = AIM_WAYPOINTS;
3878
3879         SDL_assert(aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC);
3880 }
3881
3882 //      Make *objp stay within dist units of *other_objp
3883 void ai_do_stay_near(object *objp, object *other_objp, float dist)
3884 {
3885         ai_info *aip;
3886
3887         SDL_assert(objp != other_objp);         //      Bogus!  Told to stay near self.
3888         SDL_assert(objp->type == OBJ_SHIP);
3889         SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
3890
3891         aip = &Ai_info[Ships[objp->instance].ai_index];
3892
3893         aip->mode = AIM_STAY_NEAR;
3894         aip->submode = -1;
3895         aip->stay_near_distance = dist;
3896         aip->goal_objnum = other_objp-Objects;
3897         aip->goal_signature = other_objp->signature;
3898
3899 }
3900
3901 //      Make object *objp form on wing of object *goal_objp
3902 void ai_form_on_wing(object *objp, object *goal_objp)
3903 {
3904         ai_info *aip;
3905         ship                    *shipp;
3906         ship_info       *sip;
3907
3908         // objp == goal_objp sometimes in multiplayer when someone leaves a game -- make a simple
3909         // out for this case.
3910         if ( Game_mode & GM_MULTIPLAYER ) {
3911                 if ( objp == goal_objp ) {
3912                         return;
3913                 }
3914         }
3915
3916         SDL_assert(objp != goal_objp);          //      Bogus!  Told to form on own's wing!
3917
3918         shipp = &Ships[objp->instance];
3919         sip = &Ship_info[shipp->ship_info_index];
3920
3921         //      Only fighters or bombers allowed to form on wing.
3922         if (!(sip->flags & (SIF_FIGHTER | SIF_BOMBER))) {
3923                 nprintf(("AI", "Warning: Ship %s tried to form on player's wing, but not fighter or bomber.\n", shipp->ship_name));
3924                 return;
3925         }
3926
3927         aip = &Ai_info[Ships[objp->instance].ai_index];
3928
3929         aip->ai_flags &= ~AIF_FORMATION_WING;
3930         aip->ai_flags |= AIF_FORMATION_OBJECT;
3931
3932         aip->goal_objnum = goal_objp-Objects;
3933         ai_set_goal_maybe_abort_dock(objp, aip);
3934         aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME*4);           //      Super extra long time until can target another ship.
3935
3936 }
3937
3938 //      Given an object and an object on whose wing to form, return slot to use.
3939 //      Optimize:
3940 //              This function is called per object in formation per frame.  Should store slot in ai_info struct.
3941 int ai_formation_object_get_slotnum(int objnum, object *objp)
3942 {
3943         int     slotnum = 1;                    //      Note: Slot #0 means leader, which isn't someone who was told to form-on-wing.
3944         object *o;
3945
3946         for ( o = GET_FIRST(&obj_used_list); o != END_OF_LIST(&obj_used_list); o = GET_NEXT(o) ) {
3947                 if (objp == o)
3948                         break;
3949                 else if (o->type == OBJ_SHIP)
3950                         if (Ai_info[Ships[o->instance].ai_index].ai_flags & AIF_FORMATION_OBJECT)
3951                                 if (Ai_info[Ships[o->instance].ai_index].goal_objnum == objnum)
3952                                         slotnum++;
3953         }
3954
3955         SDL_assert(o != END_OF_LIST(&obj_used_list));   //      Didn't find objp in list of used ships.  Impossible!
3956
3957         return slotnum;
3958 }
3959
3960 #define BIGNUM  100000.0f
3961
3962 int Debug_k = 0;
3963
3964 //      Given an attacker's position and a target's position and velocity, compute the time of
3965 //      intersection of a weapon fired by the attacker with speed weapon_speed.
3966 //      Return this value.  Return value of 0.0f means no collision is possible.
3967 float compute_collision_time(vector *targpos, vector *targvel, vector *attackpos, float weapon_speed)
3968 {
3969         vector  vec_to_target;
3970         float           pos_dot_vel;
3971         float           vel_sqr;
3972         float           discrim;
3973
3974         vm_vec_sub(&vec_to_target, targpos, attackpos);
3975         pos_dot_vel = vm_vec_dot(&vec_to_target, targvel);
3976         vel_sqr = vm_vec_dot(targvel, targvel) - weapon_speed*weapon_speed;
3977         discrim = pos_dot_vel*pos_dot_vel - vel_sqr*vm_vec_dot(&vec_to_target, &vec_to_target);
3978
3979         if (discrim > 0.0f) {
3980                 float   t1, t2, t_solve;
3981
3982                 t1 = (-pos_dot_vel + fl_sqrt(discrim)) / vel_sqr;
3983                 t2 = (-pos_dot_vel - fl_sqrt(discrim)) / vel_sqr;
3984
3985                 t_solve = BIGNUM;
3986
3987                 if (t1 > 0.0f)
3988                         t_solve = t1;
3989                 if ((t2 > 0.0f) && (t2 < t_solve))
3990                         t_solve = t2;
3991
3992                 if (t_solve < BIGNUM-1.0f) {
3993                         return t_solve + Debug_k * flFrametime;
3994                 }
3995         }
3996
3997         return 0.0f;
3998 }
3999
4000
4001 //      --------------------------------------------------------------------------
4002 //      If far away, use player's speed.
4003 //      If in between, lerp between player and laser speed
4004 //      If close, use laser speed.
4005 // Want to know how much time it will take to get to the enemy.
4006 // This function doesn't account for the fact that by the time the player
4007 // (or his laser) gets to the current enemy position, the enemy will have moved.
4008 // This is dealt with in polish_predicted_enemy_pos.
4009 float compute_time_to_enemy(float dist_to_enemy, object *pobjp, object *eobjp)
4010 {
4011         float   time_to_enemy;
4012         float   pl_speed = pobjp->phys_info.speed;
4013         float   max_laser_distance, max_laser_speed;
4014         int     bank_num, weapon_num;
4015         ship    *shipp = &Ships[pobjp->instance];
4016
4017         bank_num = shipp->weapons.current_primary_bank;
4018         weapon_num = shipp->weapons.primary_bank_weapons[bank_num];
4019         max_laser_speed = Weapon_info[weapon_num].max_speed;
4020         max_laser_distance = max_laser_speed * Weapon_info[weapon_num].lifetime;
4021
4022         //      If pretty far away, use player's speed to predict position, else
4023         //      use laser's speed because when close, we care more about hitting
4024         //      with a laser than about causing ship:ship rendezvous.
4025         if (dist_to_enemy > 1.5 * max_laser_distance) {
4026                 if (pl_speed > 0.0f)
4027                         time_to_enemy = dist_to_enemy/pl_speed;
4028                 else
4029                         time_to_enemy = 1.0f;
4030         } else if (dist_to_enemy > 1.1*max_laser_distance) {
4031                 if (pl_speed > 0.1f) {
4032                         float   scale;
4033
4034                         scale = (float) ((dist_to_enemy - max_laser_distance) / max_laser_distance);
4035                 
4036                         time_to_enemy = (float) (dist_to_enemy/(pl_speed * scale + max_laser_speed * (1.0f - scale)));
4037                 } else
4038                         time_to_enemy = 2.0f;
4039         } else
4040                 time_to_enemy = (float) (dist_to_enemy/max_laser_speed);
4041
4042         // return time_to_enemy * (1.0f + Ai_info[Ships[pobjp->instance].ai_index].lead_scale);
4043         return time_to_enemy + flFrametime;
4044 }
4045
4046 //      Stuff *dot and *tts.
4047 //      *dot is always computed.  If dot is less than zero, the magnitude is
4048 //      incorrect, not having been divided by distance.
4049 //      If *dot is > 0.0f, then tts is computed.  This is the time it will take object
4050 //      *objp to get to *pos, assuming it moves right at it.
4051 void fds_aux(float *dot, float *tts, vector *pos, float dtime, object *objp)
4052 {
4053         vector  v2s;
4054
4055         vm_vec_sub(&v2s, pos, &objp->pos);
4056         *dot = vm_vec_dot(&v2s, &objp->orient.v.fvec);
4057
4058         if (*dot > 0.0f) {
4059                 float   dist;
4060
4061                 dist = vm_vec_dist(&objp->pos, pos);
4062
4063                 if (dist > 0.1f)
4064                         *dot /= dist;
4065                 else
4066                         *dot = 1.0f;
4067
4068                 if (objp->phys_info.speed > 0.1f)
4069                         *tts = dist / objp->phys_info.speed;
4070                 else
4071                         *tts = dist * 100.0f;
4072         }
4073 }
4074
4075 /*
4076 //      Return index of weapon that could hit object *sobjp within dtime seconds.
4077 //      Actual time until impact returned in *atime.
4078 int find_danger_weapon(object *sobjp, float dtime, float *atime, float dot_threshhold)
4079 {
4080         object  *objp, *best_objp = NULL;
4081         float           best_tts = 1000.0f;
4082
4083         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
4084                 if ((objp->type == OBJ_WEAPON) && (sobjp-Objects != objp->parent)) {
4085                         float           dot, tts;
4086                         // vector       psp;            //      Predicted ship position.
4087
4088                         //      Get dot and time to current ship position.
4089                         fds_aux(&dot, &tts, &sobjp->pos, dtime, objp);
4090
4091                         //      If dot and tts are in plausible range, do more expensive stuff.
4092                         if (dot > 0.98f) {
4093 //                              float   dot_from_sobjp;
4094                                 vector  v2e;
4095
4096                                 vm_vec_normalized_dir(&v2e, &objp->pos, &sobjp->pos);
4097 //                              dot_from_sobjp = vm_vec_dot(&sobjp->orient.v.fvec, &v2e);
4098 //                              if (dot_from_sobjp >= dot_threshhold)
4099                                         if (tts < dtime) {
4100                                                 if (tts < best_tts) {
4101                                                         best_tts = tts;
4102                                                         best_objp = objp;
4103                                                 }
4104                                         }
4105                         }
4106                 }
4107         }
4108
4109         *atime = best_tts;
4110
4111         if (best_objp != NULL)
4112                 return best_objp-Objects;
4113         else
4114                 return -1;
4115 }
4116 */
4117
4118 //      --------------------------------------------------------------------------
4119 void ai_set_positions(object *pl_objp, object *en_objp, ai_info *aip, vector *player_pos, vector *enemy_pos)
4120 {
4121         *player_pos = pl_objp->pos;
4122
4123         if (aip->next_predict_pos_time > Missiontime) {
4124                 *enemy_pos = aip->last_predicted_enemy_pos;
4125         } else {
4126                 *enemy_pos = en_objp->pos;
4127
4128                 aip->next_predict_pos_time = Missiontime + Skill_level_delay[Game_skill_level];
4129                 aip->last_predicted_enemy_pos = *enemy_pos;
4130         }
4131
4132
4133 }
4134
4135 //      --------------------------------------------------------------------------
4136 int find_nearest_waypoint(object *objp)
4137 {
4138         int     i;
4139         float   dist, min_dist, dot;
4140         int     min_ind;
4141         int     wp_listnum;
4142         waypoint_list   *wpl;
4143
4144         wp_listnum = Ai_info[Ships[objp->instance].ai_index].wp_list;
4145         SDL_assert(wp_listnum > 0);
4146         wpl = &Waypoint_lists[wp_listnum];
4147
4148         min_dist = 999999.0f;
4149         min_ind = -1;
4150
4151         for (i=0; i<wpl->count; i++) {
4152                 dist = vm_vec_dist_quick(&objp->pos, &wpl->waypoints[i]);
4153                 dot = vm_vec_dot_to_point(&objp->orient.v.fvec, &objp->pos, &wpl->waypoints[i]);
4154                 dist = (float) (dist * (1.25 - dot));
4155                 if (dist < min_dist) {
4156                         min_dist = dist;
4157                         min_ind = i;
4158                 }
4159         }
4160
4161         SDL_assert(min_ind != -1);
4162
4163         return min_ind;
4164 }
4165
4166 //      Given an ai_info struct, by reading current goal and path information,
4167 //      extract base path information and return in pmp and pmpv.
4168 //      Return true if found, else return false.
4169 //      false means the current point is not on the original path.
4170 int get_base_path_info(int path_cur, int goal_objnum, model_path **pmp, mp_vert **pmpv)
4171 {
4172         pnode                   *pn = &Path_points[path_cur];
4173         ship_info       *sip = &Ship_info[Ships[Objects[goal_objnum].instance].ship_info_index];
4174         polymodel       *pm = model_get(sip->modelnum);
4175         //static        int     debug_last_index = -1;  // no longer used
4176         *pmpv = NULL;
4177         *pmp = NULL;
4178
4179         if (pn->path_num != -1) {
4180                 *pmp = &pm->paths[pn->path_num];
4181                 if (pn->path_index != -1)
4182                         *pmpv = &(*pmp)->verts[pn->path_index];
4183                 else
4184                         return 0;
4185         } else
4186                 return 0;
4187
4188 /*      if (debug_last_index != *pmpv-(*pmp)->verts) {
4189                 debug_last_index = *pmpv-(*pmp)->verts;
4190                 nprintf(("AI", "Point %i has %i turrets: ", *pmpv-(*pmp)->verts, (*pmpv)->nturrets));
4191                 for (int i=0; i<(*pmpv)->nturrets; i++) {
4192                         nprintf(("AI", "%i ", (*pmpv)->turret_ids[i]));
4193                 }
4194                 nprintf(("AI", "\n"));
4195         }
4196 */
4197         return 1;
4198 }
4199
4200 //      Modify, in place, the points in a global model path.
4201 //      Only modify those points that are defined in the model path.  Don't modify the
4202 //      leadin points, such as those that are necessary to get the model on the path.
4203 void modify_model_path_points(object *objp)
4204 {       
4205         ai_info         *aip = &Ai_info[Ships[objp->instance].ai_index];
4206         object          *mobjp = &Objects[aip->path_objnum];
4207         ship_info       *osip = &Ship_info[Ships[mobjp->instance].ship_info_index];
4208         polymodel       *pm = model_get(osip->modelnum);
4209         pnode                   *pnp;
4210         int                     path_num, dir;
4211
4212         SDL_assert((aip->path_start >= 0) && (aip->path_start < MAX_PATH_POINTS));
4213
4214         pnp = &Path_points[aip->path_start];
4215         while ((pnp->path_index == -1) && (pnp-Path_points - aip->path_start < aip->path_length))
4216                 pnp++;
4217
4218         path_num = pnp->path_num;
4219         SDL_assert((path_num >= 0) && (path_num < pm->n_paths));
4220         
4221         SDL_assert(pnp->path_index != -1);      //      If this is -1, that means we never found the model path points
4222
4223         dir = 1;
4224         if ( aip->ai_flags & AIF_USE_EXIT_PATH ) {
4225                 dir = -1;
4226         }
4227
4228         copy_xlate_model_path_points(mobjp, &pm->paths[path_num], dir, pm->paths[path_num].nverts, path_num, pnp);
4229 }
4230
4231 //      Return an indication of the distance between two matrices.
4232 //      This is the sum of the distances of their dot products from 1.0f.
4233 float ai_matrix_dist(matrix *mat1, matrix *mat2)
4234 {
4235         float   t;
4236
4237         t =  1.0f - vm_vec_dot(&mat1->v.fvec, &mat2->v.fvec);
4238         t += 1.0f - vm_vec_dot(&mat1->v.uvec, &mat2->v.uvec);
4239         t += 1.0f - vm_vec_dot(&mat1->v.rvec, &mat2->v.rvec);
4240
4241         return t;
4242 }
4243
4244
4245 //      Paths are created in absolute space, so a moving object needs to have model paths within it recreated.
4246 //      This uses the hash functions which means the slightest movement will cause a recreate, though the timestamp
4247 //      prevents this from happening too often.
4248 //      force_recreate_flag TRUE means to recreate regardless of timestamp.
4249 //      Returns TRUE if path recreated.
4250 float maybe_recreate_path(object *objp, ai_info *aip, int force_recreate_flag)
4251 {
4252         int     hashval;
4253
4254         SDL_assert(&Ai_info[Ships[objp->instance].ai_index] == aip);
4255
4256         if ((aip->mode == AIM_BAY_EMERGE) || (aip->mode == AIM_BAY_DEPART))
4257                 if ((OBJ_INDEX(objp) % 4) == (Framecount % 4))
4258                         force_recreate_flag = 1;
4259
4260         //      If no path, that means we don't need one.
4261         if (aip->path_start == -1)
4262                 return 0.0f;
4263
4264         // AL 11-12-97: If AIF_USE_STATIC_PATH is set, don't try to recreate.  This is needed when ships
4265         //                                  emerge from fighter bays.  We don't need to recreate the path.. and in case the 
4266         //              parent ship dies, we still want to be able to continue on the path
4267         if ( aip->ai_flags & AIF_USE_STATIC_PATH ) 
4268                 return 0.0f;
4269
4270         if (force_recreate_flag || timestamp_elapsed(aip->path_next_create_time)) {
4271                 object  *path_objp;
4272
4273                 path_objp = &Objects[aip->path_objnum];
4274
4275                 if ((hashval = create_object_hash(path_objp)) != aip->path_goal_obj_hash) {
4276                         float dist;
4277                         
4278                         dist = vm_vec_dist_quick(&path_objp->pos, &aip->path_create_pos);
4279                         dist += ai_matrix_dist(&path_objp->orient, &aip->path_create_orient) * 25.0f;
4280
4281                         if (force_recreate_flag || (dist > 2.0f)) {
4282                                 aip->path_next_create_time = timestamp(1000);   //      Update again in as little as 1000 milliseconds, ie 1 second.
4283                                 aip->path_goal_obj_hash = hashval;
4284                                 modify_model_path_points(objp);
4285
4286                                 aip->path_create_pos = path_objp->pos;
4287                                 aip->path_create_orient = path_objp->orient;
4288                                 
4289                                 return dist;
4290                         }
4291                 }
4292         }
4293
4294         return 0.0f;
4295 }
4296
4297 //      Set acceleration for ai_dock().
4298 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)
4299 {
4300         float prev_dot_to_goal = aip->prev_dot_to_goal;
4301         
4302         aip->prev_dot_to_goal = dot;
4303
4304         if (objp->phys_info.speed < 0.0f) {
4305                 accelerate_ship(aip, 1.0f/32.0f);
4306         } else if ((prev_dot_to_goal-dot) > 0.01) {
4307                 if (prev_dot_to_goal > dot + 0.05f) {
4308                         accelerate_ship(aip, 0.0f);
4309                 } else {
4310                         change_acceleration(aip, -1.0f);        //      -1.0f means subtract off flFrametime from acceleration value in 0.0..1.0
4311                 }
4312         } else {
4313                 if ((aip->mode == AIM_DOCK) && (dist_to_next < 150.0f) && (aip->path_start + aip->path_length - 2 == aip->path_cur)) {
4314                         set_accel_for_target_speed(objp, sip->max_speed * max(dist_to_next/500.0f, 1.0f));
4315                         //mprintf(("dist = %7.3f, speed = %7.3f\n", dist_to_next, objp->phys_info.speed));
4316                 } else if ((dot_to_next >= dot * .9) || (dist_to_next > 100.0f)) {
4317                         if (dist_to_goal > 200.0f)
4318                                 set_accel_for_target_speed(objp, sip->max_speed * (dot + 1.0f) / 2.0f);
4319                         else {
4320                                 float   xdot;
4321
4322                                 xdot = (dot_to_next + dot)/2.0f;
4323                                 if (xdot < 0.0f)
4324                                         xdot = 0.0f;
4325
4326                                 // AL: if following a path not in dock mode, move full speed
4327                                 if (( aip->mode != AIM_DOCK ) && (dot > 0.9f)) {
4328                                         set_accel_for_target_speed(objp, sip->max_speed*dot*dot*dot);
4329                                 } else {
4330                                         if ((aip->path_cur - aip->path_start < aip->path_length-2) && (dist_to_goal < 2*objp->radius)) {
4331                                                 //nprintf(("AI", "Target speed = %7.3f\n", dist_to_goal/8.0f));
4332                                                 set_accel_for_target_speed(objp, dist_to_goal/8.0f + 2.0f);
4333                                         } else {
4334                                                 set_accel_for_target_speed(objp, sip->max_speed * (2*xdot + 0.25f)/4.0f);
4335                                         }
4336                                 }
4337                         }
4338                 } else {
4339                         float   xdot;
4340
4341                         xdot = max(dot_to_next, 0.1f);
4342                         if ( aip->mode != AIM_DOCK ) {
4343                                 set_accel_for_target_speed(objp, sip->max_speed);
4344                         } else {
4345                                 float   speed;
4346                                 if ((aip->path_cur - aip->path_start < aip->path_length-2) && (dist_to_goal < 2*objp->radius)) {
4347                                         speed = dist_to_goal/8.0f + 2.0f;
4348                                 } else if (dist_to_goal < 4*objp->radius + 50.0f) {
4349                                         speed = dist_to_goal/4.0f + 4.0f;
4350                                 } else {
4351                                         speed = sip->max_speed * (3*xdot + 1.0f)/4.0f;
4352                                 }
4353                                 if (aip->mode == AIM_DOCK) {
4354                                         speed = speed * 2.0f + 1.0f;
4355                                         if (aip->goal_objnum != -1) {
4356                                                 speed += Objects[aip->goal_objnum].phys_info.speed;
4357                                         }
4358                                 }
4359
4360                                 set_accel_for_target_speed(objp, speed);
4361                         }
4362                 }
4363         }
4364 }
4365
4366 //      --------------------------------------------------------------------------
4367 //      Follow a path associated with a large object, such as a capital ship.
4368 //      The points defined on the path are in the object's reference frame.
4369 //      The object of interest is goal_objnum.
4370 //      The paths are defined in the model.  The path of interest is wp_list.
4371 //      The next goal point in the path is wp_index.
4372 //      wp_flags contain special information specific to the path.
4373
4374 // The path vertices are defined by model_path structs:
4375 //              typedef struct model_path {
4376 //                      char            name[MAX_NAME_LEN];                                     // name of the subsystem.  Probably displayed on HUD
4377 //                      int             nverts;
4378 //                      vector  *verts;
4379 //              } model_path;
4380
4381 //      The polymodel struct for the object contains the following:
4382 //              int                     n_paths;
4383 //              model_path      *paths;
4384
4385 //      Returns distance to goal point.
4386 float ai_path()
4387 {
4388         polymodel       *pm;
4389         int             num_paths, num_points;
4390         float           dot, dist_to_goal, dist_to_next, dot_to_next;
4391         ship            *shipp = &Ships[Pl_objp->instance];
4392         ship_info       *sip = &Ship_info[shipp->ship_info_index];
4393         ai_info *aip;
4394         vector  nvel_vec;
4395         float           mag;//, prev_dot_to_goal;
4396         vector  temp_vec, *slop_vec;
4397         object  *gobjp;
4398         ship            *gshipp;
4399         vector  *cvp, *nvp, next_vec, gcvp, gnvp;               //      current and next vertices in global coordinates.
4400
4401         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
4402
4403         SDL_assert(aip->goal_objnum != -1);
4404         SDL_assert(Objects[aip->goal_objnum].type == OBJ_SHIP);
4405
4406         gobjp = &Objects[aip->goal_objnum];
4407         gshipp = &Ships[gobjp->instance];
4408
4409         pm = model_get( gshipp->modelnum );
4410         num_paths = pm->n_paths;
4411         SDL_assert(num_paths > 0);
4412
4413         if (aip->path_start == -1) {
4414                 int path_num;
4415                 path_num = ai_return_path_num_from_dockbay(&Objects[aip->goal_objnum], aip->dockee_index);
4416                 SDL_assert(aip->goal_objnum >= 0 && aip->goal_objnum < MAX_OBJECTS);
4417                 ai_find_path(Pl_objp, aip->goal_objnum, path_num, 0);
4418         }
4419
4420         // nprintf(("AI", "Frame: %i, Path index = %i/%i\n", AI_FrameCount, aip->path_cur-aip->path_start, aip->path_length));
4421
4422         maybe_recreate_path(Pl_objp, aip, 0);
4423
4424         num_points = aip->path_length;
4425
4426         //      Set cvp and nvp as pointers to current and next vertices of interest on path.
4427         cvp = &Path_points[aip->path_cur].pos;
4428         if ((aip->path_cur + aip->path_dir - aip->path_start < num_points) || (aip->path_cur + aip->path_dir < aip->path_start))
4429                 nvp = &Path_points[aip->path_cur + aip->path_dir].pos;
4430         else {
4431                 //      If this is 0, then path length must be 1 which means we have no direction!
4432                 SDL_assert((aip->path_cur - aip->path_dir >= aip->path_start) && (aip->path_cur - aip->path_dir - aip->path_start < num_points));
4433                 //      Cleanup for above SDL_assert() which we hit too near release. -- MK, 5/24/98.
4434                 if (aip->path_cur - aip->path_dir - aip->path_start >= num_points) {
4435                         if (aip->path_dir == 1)
4436                                 aip->path_cur = aip->path_start;
4437                         else
4438                                 aip->path_cur = aip->path_start + num_points - 1;
4439                 }
4440
4441                 vector  delvec;
4442                 vm_vec_sub(&delvec, cvp, &Path_points[aip->path_cur - aip->path_dir].pos);
4443                 vm_vec_normalize(&delvec);
4444                 vm_vec_scale_add(&next_vec, cvp, &delvec, 10.0f);
4445                 nvp = &next_vec;
4446         }
4447
4448         //      Interrupt if can't get to current goal point.  Debug only.
4449 /*      if (pp_collide(&Pl_objp->pos, cvp, gobjp, Pl_objp->radius)) {
4450                 Int3();
4451         }
4452 */
4453         //      See if can reach next point (as opposed to current point)
4454         //      However, don't do this if docking and next point is last point.
4455         //      That is, we don't want to pursue the last point under control of the
4456         //      path code.  In docking, this is a special hack.
4457         if ((aip->mode != AIM_DOCK) || ((aip->path_cur-aip->path_start) < num_points - 2)) {
4458                 if ((aip->path_cur + aip->path_dir > aip->path_start) && (aip->path_cur + aip->path_dir < aip->path_start + num_points-2)) {
4459                         if ( timestamp_elapsed(aip->path_next_check_time)) {
4460                                 aip->path_next_check_time = timestamp( 3000 );
4461                                 if (!pp_collide(&Pl_objp->pos, nvp, gobjp, 1.1f * Pl_objp->radius)) {
4462                                         cvp = nvp;
4463                                         aip->path_cur += aip->path_dir;
4464                                         nvp = &Path_points[aip->path_cur].pos;
4465                                         //nprintf(("AI", "Reach: Advancing from point %i to %i of %i points.\n", aip->path_cur-aip->path_dir, aip->path_cur, num_points));
4466                                 }
4467                         }
4468                 }
4469         }
4470
4471         gcvp = *cvp;
4472         gnvp = *nvp;
4473
4474         dist_to_goal = vm_vec_dist_quick(&Pl_objp->pos, &gcvp);
4475         dist_to_next = vm_vec_dist_quick(&Pl_objp->pos, &gnvp);
4476         //      Can't use fvec, need to use velocity vector because we aren't necessarily
4477         //      moving in the direction we're facing.
4478
4479 //      if (IS_VEC_NULL(&Pl_objp->phys_info.vel)) {
4480         if ( vm_vec_mag_quick(&Pl_objp->phys_info.vel) < AICODE_SMALL_MAGNITUDE ) {
4481                 mag = 0.0f;
4482                 vm_vec_zero(&nvel_vec);
4483         } else
4484                 mag = vm_vec_copy_normalize(&nvel_vec, &Pl_objp->phys_info.vel);
4485
4486         //      If moving not-very-slowly and sliding, then try to slide at goal, rather than
4487         //      point at goal.
4488         slop_vec = NULL;
4489         if (mag < 1.0f)
4490                 nvel_vec = Pl_objp->orient.v.fvec;
4491         else if (mag > 5.0f) {
4492                 float   nv_dot;
4493                 nv_dot = vm_vec_dot(&Pl_objp->orient.v.fvec, &nvel_vec);
4494                 if ((nv_dot > 0.5f) && (nv_dot < 0.97f)) {
4495                         slop_vec = &temp_vec;
4496                         vm_vec_sub(slop_vec, &nvel_vec, &Pl_objp->orient.v.fvec);
4497                 }
4498         }
4499
4500         if (dist_to_goal > 0.1f)
4501                 ai_turn_towards_vector(&gcvp, Pl_objp, flFrametime, sip->srotation_time, slop_vec, NULL, 0.0f, 0);
4502
4503         //      Code to control speed is MUCH less forgiving in path following than in waypoint
4504         //      following.  Must be very close to path or might hit objects.
4505 //      prev_dot_to_goal = aip->prev_dot_to_goal;
4506         dot = vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, &gcvp);
4507         dot_to_next = vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, &gnvp);
4508
4509         set_accel_for_docking(Pl_objp, aip, dot, dot_to_next, dist_to_next, dist_to_goal, sip);
4510         aip->prev_dot_to_goal = dot;
4511
4512 //mprintf(("Goal index = %i, dist = %7.3f, dot = %7.3f\n", wp_index, dist_to_goal, dot));
4513
4514         //      If moving at a non-tiny velocity, detect attaining path point by its being close to
4515         //      line between previous and current object location.
4516         if ((dist_to_goal < MIN_DIST_TO_WAYPOINT_GOAL) || (vm_vec_dist_quick(&Pl_objp->last_pos, &Pl_objp->pos) > 0.1f)) {
4517                 vector  nearest_point;
4518                 float           r, min_dist_to_goal;
4519
4520                 r = find_nearest_point_on_line(&nearest_point, &Pl_objp->last_pos, &Pl_objp->pos, &gcvp);
4521
4522                 //      Set min_dist_to_goal = how close must be to waypoint to pick next one.
4523                 //      If docking and this is the second last waypoint, must be very close.
4524                 if ((aip->mode == AIM_DOCK) && (aip->path_cur >= aip->path_length-2))
4525                         min_dist_to_goal = MIN_DIST_TO_WAYPOINT_GOAL;
4526                 else
4527                         min_dist_to_goal = MIN_DIST_TO_WAYPOINT_GOAL + Pl_objp->radius;
4528
4529                 if ( (vm_vec_dist_quick(&Pl_objp->pos, &gcvp) < min_dist_to_goal) ||
4530                         (((r >= 0.0f) && (r <= 1.0f)) && (vm_vec_dist_quick(&nearest_point, &gcvp) < (MIN_DIST_TO_WAYPOINT_GOAL + Pl_objp->radius)))) {
4531                         aip->path_cur += aip->path_dir;
4532                         //nprintf(("AI", " Near: Advancing from point %i to %i of %i points.\n", aip->path_cur-aip->path_dir, aip->path_cur, num_points));
4533                         if (((aip->path_cur - aip->path_start) > (num_points+1)) || (aip->path_cur < aip->path_start)) {
4534                                 SDL_assert(aip->mode != AIM_DOCK);              //      If docking, should never get this far, getting to last point handled outside ai_path()
4535                                 aip->path_dir = -aip->path_dir;
4536 //                              aip->path_cur += aip->path_dir;
4537                         }
4538                 }
4539         }
4540
4541         return dist_to_goal;
4542 }
4543
4544 void update_min_max(float val, float *min, float *max)
4545 {
4546         if (val < *min)
4547                 *min = val;
4548         else if (val > *max)
4549                 *max = val;
4550 }
4551
4552 //      Stuff bounding box of all enemy objects within "range" units of object *my_objp.
4553 //      Stuff ni min_vec and max_vec.
4554 //      Return value: Number of enemy objects in bounding box.
4555 int get_enemy_team_range(object *my_objp, float range, int enemy_team_mask, vector *min_vec, vector *max_vec)
4556 {
4557         object  *objp;
4558         ship_obj        *so;
4559         int             count = 0;
4560
4561         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
4562                 objp = &Objects[so->objnum];
4563                 if (Ships[objp->instance].team & enemy_team_mask) {
4564                         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))
4565                                 if (vm_vec_dist_quick(&my_objp->pos, &objp->pos) < range) {
4566                                         if (count == 0) {
4567                                                 *min_vec = objp->pos;
4568                                                 *max_vec = objp->pos;
4569                                                 count++;
4570                                         } else {
4571                                                 update_min_max(objp->pos.xyz.x, &min_vec->xyz.x, &max_vec->xyz.x);
4572                                                 update_min_max(objp->pos.xyz.y, &min_vec->xyz.y, &max_vec->xyz.y);
4573                                                 update_min_max(objp->pos.xyz.z, &min_vec->xyz.z, &max_vec->xyz.z);
4574                                         }
4575                                 }
4576
4577                 }
4578         }
4579
4580         return count;
4581 }
4582
4583 //      Pick a relatively safe spot for objp to fly to.
4584 //      Problem:
4585 //              Finds a spot away from any enemy within a bounding box.
4586 //              Doesn't verify that "safe spot" is not near some other enemy.
4587 void ai_safety_pick_spot(object *objp)
4588 {
4589         int             objnum;
4590         int             enemy_team_mask;
4591         vector  min_vec, max_vec;
4592         vector  vec_to_center, center;
4593         vector  goal_pos;
4594
4595         objnum = OBJ_INDEX(objp);
4596
4597         enemy_team_mask = get_enemy_team_mask(objnum);
4598
4599         if (get_enemy_team_range(objp, 1000.0f, enemy_team_mask, &min_vec, &max_vec)) {
4600                 vm_vec_avg(&center, &min_vec, &max_vec);
4601                 vm_vec_normalized_dir(&vec_to_center, &center, &objp->pos);
4602
4603                 vm_vec_scale_add(&goal_pos, &center, &vec_to_center, 2000.0f);
4604         } else
4605                 vm_vec_scale_add(&goal_pos, &objp->pos, &objp->orient.v.fvec, 100.0f);
4606
4607         Ai_info[Ships[objp->instance].ai_index].goal_point = goal_pos;
4608 }
4609
4610 //      Fly to desired safe point.
4611 // Returns distance to that point.
4612 float ai_safety_goto_spot(object *objp)
4613 {
4614         float   dot, dist;
4615         ai_info *aip;
4616         vector  vec_to_goal;
4617         ship_info       *sip;
4618         float   dot_val;
4619
4620         sip = &Ship_info[Ships[objp->instance].ship_info_index];
4621
4622         aip = &Ai_info[Ships[objp->instance].ai_index];
4623         dist = vm_vec_normalized_dir(&vec_to_goal, &aip->goal_point, &objp->pos);
4624         dot = vm_vec_dot(&vec_to_goal, &objp->orient.v.fvec);
4625
4626         dot_val = (1.1f + dot) / 2.0f;
4627         if (dist > 200.0f) {
4628                 set_accel_for_target_speed(objp, sip->max_speed * dot_val);
4629         } else
4630                 set_accel_for_target_speed(objp, sip->max_speed * dot_val * (dist/200.0f + 0.2f));
4631
4632         return dist;
4633 }
4634
4635 void ai_safety_circle_spot(object *objp)
4636 {
4637         vector  goal_point;
4638         ship_info       *sip;
4639         float           dot;
4640
4641         sip = &Ship_info[Ships[objp->instance].ship_info_index];
4642
4643         goal_point = Ai_info[Ships[objp->instance].ai_index].goal_point;
4644         dot = turn_towards_tangent(objp, &goal_point, 250.0f);  //      Increased from 50 to 250 to make circling not look so wacky.
4645
4646         set_accel_for_target_speed(objp, 0.5f * (1.0f + dot) * sip->max_speed/4.0f);
4647
4648 //      float dist = vm_vec_dist_quick(&goal_point, &Pl_objp->pos);
4649 //      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));
4650
4651 }
4652
4653 //      --------------------------------------------------------------------------
4654 void ai_safety()
4655 {
4656         ai_info *aip;
4657
4658         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
4659
4660         switch (aip->submode) {
4661         case AISS_1:
4662                 ai_safety_pick_spot(Pl_objp);
4663                 aip->submode = AISS_2;
4664                 aip->submode_start_time = Missiontime;
4665                 break;
4666         case AISS_1a:   //      Pick a safe point because we just got whacked!
4667                 Int3();
4668                 break;
4669         case AISS_2:
4670                 if (ai_safety_goto_spot(Pl_objp) < 25.0f) {
4671                         aip->submode = AISS_3;
4672                         aip->submode_start_time = Missiontime;
4673                 }
4674                 break;
4675         case AISS_3:
4676                 ai_safety_circle_spot(Pl_objp);
4677                 break;
4678         default:
4679                 Int3();         //      Illegal submode for ai_safety();
4680                 break;
4681         }
4682 }
4683
4684 //      --------------------------------------------------------------------------
4685 //      make Pl_objp fly waypoints.
4686 void ai_waypoints()
4687 {
4688         int             wp_index;
4689         vector  *wp_cur, *wp_next;
4690         float           dot, dist_to_goal;//, dot_to_next;
4691         ship            *shipp = &Ships[Pl_objp->instance];
4692         ship_info       *sip = &Ship_info[shipp->ship_info_index];
4693         waypoint_list   *wpl;
4694         ai_info *aip;
4695         vector  nvel_vec;
4696         float           mag;
4697         float           prev_dot_to_goal;
4698         vector  temp_vec;
4699         vector  *slop_vec;
4700
4701         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
4702
4703         wp_index = aip->wp_index;
4704
4705         if (wp_index == -1) {
4706                 ai_start_waypoints(Pl_objp, 0, WPF_REPEAT);
4707                 wp_index = aip->wp_index;
4708                 aip->wp_dir = 1;
4709         }
4710
4711         wpl = &Waypoint_lists[Ai_info[Ships[Pl_objp->instance].ai_index].wp_list];
4712
4713         SDL_assert(wpl->count); // What? Is this zero? Probably wp_index never got initialized!
4714
4715         wp_cur = &wpl->waypoints[wp_index];
4716         wp_next = &wpl->waypoints[(wp_index+1) % wpl->count];
4717
4718         dist_to_goal = vm_vec_dist_quick(&Pl_objp->pos, wp_cur);
4719
4720         //      Can't use fvec, need to use velocity vector because we aren't necessarily
4721         //      moving in the direction we're facing.
4722         // AL 23-3-98: Account for very small velocities by checking result of vm_vec_mag().
4723         //                                      If we don't vm_vec_copy_normalize() will think it is normalizing a null vector.
4724 //      if (IS_VEC_NULL(&Pl_objp->phys_info.vel)) {
4725         if ( vm_vec_mag_quick(&Pl_objp->phys_info.vel) < AICODE_SMALL_MAGNITUDE ) {
4726                 mag = 0.0f;
4727                 vm_vec_zero(&nvel_vec);
4728         } else {
4729                 mag = vm_vec_copy_normalize(&nvel_vec, &Pl_objp->phys_info.vel);
4730         }
4731
4732         //      If moving not-very-slowly and sliding, then try to slide at goal, rather than
4733         //      point at goal.
4734         slop_vec = NULL;
4735         if (mag < 1.0f) {
4736                 nvel_vec = Pl_objp->orient.v.fvec;
4737         } else if (mag > 5.0f) {
4738                 float   nv_dot;
4739                 nv_dot = vm_vec_dot(&Pl_objp->orient.v.fvec, &nvel_vec);
4740                 if ((nv_dot > 0.5f) && (nv_dot < 0.97f)) {
4741                         slop_vec = &temp_vec;
4742                         vm_vec_sub(slop_vec, &nvel_vec, &Pl_objp->orient.v.fvec);
4743                 }
4744         }
4745
4746         //      If a wing leader, take turns more slowly, based on size of wing.
4747         int     scale;
4748
4749         if (Ai_info[Ships[Pl_objp->instance].ai_index].wing >= 0) {
4750                 scale = Wings[Ai_info[Ships[Pl_objp->instance].ai_index].wing].current_count;
4751                 scale = (int) ((scale+1)/2);
4752         } else {
4753                 scale = 1;
4754         }
4755
4756         if (dist_to_goal > 0.1f) {
4757                 ai_turn_towards_vector(wp_cur, Pl_objp, flFrametime, sip->srotation_time*3.0f*scale, slop_vec, NULL, 0.0f, 0);
4758         }
4759
4760         prev_dot_to_goal = aip->prev_dot_to_goal;
4761         dot = vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, wp_cur);
4762         /*dot_to_next =*/ vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, wp_next);
4763         aip->prev_dot_to_goal = dot;
4764
4765         //      If there is no next point on the path, don't care about dot to next.
4766 //      if (wp_index + 1 >= wpl->count) {
4767 //              dot_to_next = dot;
4768 //      }
4769
4770         // nprintf(("AI", "Wp #%i, dot = %6.3f, next dot = %6.3f, dist = %7.2f\n", wp_index, dot, dot_to_next, dist_to_goal));
4771
4772         if (Pl_objp->phys_info.speed < 0.0f) {
4773                 accelerate_ship(aip, 1.0f/32);
4774         } else if (prev_dot_to_goal > dot+0.01f) {
4775                 //      We are further from pointing at our goal this frame than last frame, so slow down.
4776                 set_accel_for_target_speed(Pl_objp, Pl_objp->phys_info.speed * 0.95f);
4777         } else if (dist_to_goal < 100.0f) {
4778                 float slew_dot = vm_vec_dot(&Pl_objp->orient.v.fvec, &nvel_vec);
4779                 if (fl_abs(slew_dot) < 0.9f) {
4780                         accelerate_ship(aip, 0.0f);
4781                 } else if (dot < 0.88f + 0.1f*(100.0f - dist_to_goal)/100.0f) {
4782                         accelerate_ship(aip, 0.0f);
4783                 } else {
4784                         accelerate_ship(aip, 0.5f * dot * dot);
4785                 }
4786         } else {
4787                 float   dot1;
4788                 if (dist_to_goal < 250.0f) {
4789                         dot1 = dot*dot*dot;                             //      Very important to be pointing towards goal when nearby.  Note, cubing preserves sign.
4790                 } else {
4791                         if (dot > 0.0f) {
4792                                 dot1 = dot*dot;
4793                         } else {
4794                                 dot1 = dot;
4795                         }
4796                 }
4797
4798                 if (dist_to_goal > 100.0f + Pl_objp->radius * 2) {
4799                         if (dot < 0.2f) {
4800                                 dot1 = 0.2f;
4801                         }
4802                 }
4803
4804                 if (sip->flags & SIF_SMALL_SHIP) {
4805                         set_accel_for_target_speed(Pl_objp, dot1 * dist_to_goal/5.0f);
4806                 } else {
4807                         set_accel_for_target_speed(Pl_objp, dot1 * dist_to_goal/10.0f);
4808                 }
4809         }
4810
4811         //      Make sure not travelling too fast for someone to keep up.
4812         float   max_allowed_speed = 9999.9f;
4813
4814         if (shipp->wingnum != -1) {
4815                 max_allowed_speed = 0.9f * get_wing_lowest_max_speed(Pl_objp);
4816         }
4817
4818         // check if waypoint speed cap is set and adjust max speed
4819         if (aip->waypoint_speed_cap > 0) {
4820                 max_allowed_speed = (float) aip->waypoint_speed_cap;
4821         }
4822
4823         if (aip->prev_accel * shipp->current_max_speed > max_allowed_speed) {
4824                 accelerate_ship(aip, max_allowed_speed / shipp->current_max_speed);
4825         }
4826
4827         if (vm_vec_dist_quick(&Pl_objp->last_pos, &Pl_objp->pos) > 0.1f) {
4828                 vector  nearest_point;
4829                 float           r;
4830
4831                 r = find_nearest_point_on_line(&nearest_point, &Pl_objp->last_pos, &Pl_objp->pos, wp_cur);
4832
4833                 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))) ||
4834                         (((r >= 0.0f) && (r <= 1.0f)) && (vm_vec_dist_quick(&nearest_point, wp_cur) < (MIN_DIST_TO_WAYPOINT_GOAL + fl_sqrt(Pl_objp->radius))))) {
4835                         wp_index++;
4836                         if (wp_index >= wpl->count) {
4837                                 if (aip->wp_flags & WPF_REPEAT) {
4838                                         wp_index = 0;
4839                                 } else {
4840                                         int treat_as_ship;
4841
4842                                         // when not repeating waypoints -- mark the goal as done and put and entry into the mission log
4843                                         // we must be careful when dealing with wings.  A ship in a wing might be completing
4844                                         // a waypoint for for the entire wing, or it might be completing a goal for itself.  If
4845                                         // for itself and in a wing, treat the completion as we would a ship
4846                                         treat_as_ship = 1;
4847                                         if ( Ships[Pl_objp->instance].wingnum != -1 ) {
4848                                                 int type;
4849
4850                                                 // I don't think that you can fly waypoints as dynamic goals!!!
4851                                                 // -- This is legal, just stupid. -- SDL_assert( (aip->active_goal != AI_GOAL_NONE) && (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC) );
4852                                                 
4853                                                 //      Clean up from above SDL_assert, just in case we ship without fixing it.  (Encountered by JimB on 2/9/98)
4854                                                 if ( (aip->active_goal == AI_GOAL_NONE) || (aip->active_goal == AI_ACTIVE_GOAL_DYNAMIC) ) {
4855                                                         aip->mode = AIM_NONE;
4856                                                         Int3(); //      Look at the ship, find out of it's supposed to be flying waypoints. -- MK.
4857                                                 }
4858
4859                                                 type = aip->goals[aip->active_goal].type;
4860                                                 if ( (type == AIG_TYPE_EVENT_WING) || (type == AIG_TYPE_PLAYER_WING) ) {
4861                                                         treat_as_ship = 0;
4862                                                 } else {
4863                                                         treat_as_ship = 1;
4864                                                 }
4865                                         }
4866
4867                                         // if the ship is not in a wing, remove the goal and continue on
4868                                         if ( treat_as_ship ) {
4869                                                 ai_mission_goal_complete( aip );                                        // this call should reset the AI mode
4870                                                 mission_log_add_entry(LOG_WAYPOINTS_DONE, Ships[Pl_objp->instance].ship_name, wpl->name, -1 );
4871                                         } else {
4872                                                 // this ship is in a wing.  We must mark the goal as being completed for all ships
4873                                                 // in the wing.  We will also mark an entry in the log that the wing completed the goal
4874                                                 // not the individual ship.
4875                                                 ai_mission_wing_goal_complete( Ships[Pl_objp->instance].wingnum, &(aip->goals[aip->active_goal]) );
4876                                                 mission_log_add_entry( LOG_WAYPOINTS_DONE, Wings[Ships[Pl_objp->instance].wingnum].name, wpl->name, -1 );
4877                                         }
4878                                         //wp_index = wpl->count-1;
4879                                 }
4880                         }
4881
4882                         aip->wp_index = wp_index;
4883                 }
4884         }
4885 }
4886
4887 //      Make Pl_objp avoid En_objp
4888 //      Not like evading.  This is for avoiding a collision!
4889 //      Note, use sliding if available.
4890 void avoid_ship()
4891 {
4892         //      To avoid an object, turn towards right or left vector until facing away from object.
4893         //      To choose right vs. left, pick one that is further from center of avoid object.
4894         //      Keep turning away from until pointing away from ship.
4895         //      Stay in avoid mode until at least 3 enemy ship radii away.
4896
4897         //      Speed setting:
4898         //      If inside sphere, zero speed and turn towards outside.
4899         //      If outside sphere, inside 2x sphere, set speed percent of max to:
4900         //              max(away_dot, (dist-rad)/rad)
4901         //      where away_dot is dot(Pl_objp->v.fvec, vec_En_objp_to_Pl_objp)
4902
4903         vector  vec_to_enemy;
4904         float           away_dot;
4905         float           dist;
4906         ship            *shipp = &Ships[Pl_objp->instance];
4907         ship_info       *sip = &Ship_info[shipp->ship_info_index];
4908         ai_info *aip = &Ai_info[shipp->ai_index];
4909         vector  player_pos, enemy_pos;
4910
4911         // if we're avoiding a stealth ship, then we know where he is, update with no error
4912         if ( is_object_stealth_ship(En_objp) ) {
4913                 update_ai_stealth_info_with_error(aip/*, 1*/);
4914         }
4915
4916         ai_set_positions(Pl_objp, En_objp, aip, &player_pos, &enemy_pos);
4917         vm_vec_sub(&vec_to_enemy, &enemy_pos, &Pl_objp->pos);
4918
4919         dist = vm_vec_normalize(&vec_to_enemy);
4920         away_dot = -vm_vec_dot(&Pl_objp->orient.v.fvec, &vec_to_enemy);
4921         
4922         if ((sip->max_vel.xyz.x > 0.0f) || (sip->max_vel.xyz.y > 0.0f)) {
4923                 if (vm_vec_dot(&Pl_objp->orient.v.rvec, &vec_to_enemy) > 0.0f) {
4924                         AI_ci.sideways = -1.0f;
4925                 } else {
4926                         AI_ci.sideways = 1.0f;
4927                 }
4928                 if (vm_vec_dot(&Pl_objp->orient.v.uvec, &vec_to_enemy) > 0.0f) {
4929                         AI_ci.vertical = -1.0f;
4930                 } else {
4931                         AI_ci.vertical = 1.0f;
4932                 }
4933         }               
4934
4935         //nprintf(("AI", "Frame %i: Sliding: %s %s\n", Framecount, AI_ci.sideways < 0 ? "left" : "right", AI_ci.vertical < 0 ? "down" : "up" ));
4936         // nprintf(("AI", "away_dot = %6.3f, dist = %7.2f, dist/radsum = %6.3f\n", away_dot, dist, dist/(Pl_objp->radius + En_objp->radius)));
4937
4938         //      If in front of enemy, turn away from it.
4939         //      If behind enemy, try to get fully behind it.
4940         if (away_dot < 0.0f) {
4941                 turn_away_from_point(Pl_objp, &enemy_pos, Pl_objp->phys_info.speed);
4942         } else {
4943                 vector  goal_pos;
4944
4945                 vm_vec_scale_add(&goal_pos, &En_objp->pos, &En_objp->orient.v.fvec, -100.0f);
4946                 turn_towards_point(Pl_objp, &goal_pos, NULL, Pl_objp->phys_info.speed);
4947         }
4948
4949         //      Set speed.
4950         float   radsum = Pl_objp->radius + En_objp->radius;
4951
4952         if (dist < radsum)
4953                 accelerate_ship(aip, max(away_dot, 0.2f));
4954         else if (dist < 2*radsum)
4955                 accelerate_ship(aip, max(away_dot, (dist - radsum) / radsum)+0.2f);
4956         else
4957                 accelerate_ship(aip, 1.0f);
4958
4959 }
4960
4961 //      Maybe it's time to resume the previous AI mode in aip->previous_mode.
4962 //      Each type of previous_mode has its own criteria on when to resume.
4963 //      Return true if previous mode was resumed.
4964 int maybe_resume_previous_mode(object *objp, ai_info *aip)
4965 {
4966         //      Only (maybe) resume previous goal if current goal is dynamic.
4967         if (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC)
4968                 return 0;
4969
4970         if (aip->mode == AIM_EVADE_WEAPON) {
4971                 if (timestamp_elapsed(aip->mode_time) || (((aip->nearest_locked_object == -1) || (Objects[aip->nearest_locked_object].type != OBJ_WEAPON)) && (aip->danger_weapon_objnum == -1))) {
4972                         SDL_assert(aip->previous_mode != AIM_EVADE_WEAPON);
4973                         aip->mode = aip->previous_mode;
4974                         aip->submode = aip->previous_submode;
4975                         aip->submode_start_time = Missiontime;
4976                         aip->active_goal = AI_GOAL_NONE;
4977                         aip->mode_time = -1;                    //      Means do forever.
4978                         return 1;
4979                 }
4980         } else if ( aip->previous_mode == AIM_GUARD) {
4981                 if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
4982                         object  *guard_objp;
4983                         float   dist;
4984
4985                         guard_objp = &Objects[aip->guard_objnum];
4986                         dist = vm_vec_dist_quick(&guard_objp->pos, &objp->pos);
4987
4988                         //      If guarding ship is far away from guardee and enemy is far away from guardee,
4989                         //      then stop chasing and resume guarding.
4990                         if (dist > (MAX_GUARD_DIST + guard_objp->radius) * 6) {
4991                                 if ((En_objp != NULL) && (En_objp->type == OBJ_SHIP)) {
4992                                         if (vm_vec_dist_quick(&guard_objp->pos, &En_objp->pos) > (MAX_GUARD_DIST + guard_objp->radius) * 6) {
4993                                                 SDL_assert(aip->previous_mode == AIM_GUARD);
4994                                                 aip->mode = aip->previous_mode;
4995                                                 aip->submode = AIS_GUARD_PATROL;
4996                                                 aip->active_goal = AI_GOAL_NONE;
4997                                                 return 1;
4998                                         }
4999                                 }
5000                         }
5001                 }
5002         }
5003
5004         return 0;
5005
5006 }
5007
5008 //      Call this function if you want something to happen on average every N quarters of a second.
5009 //      The truth value returned by this function will be the same for any given quarter second interval.
5010 //      The value "num" is only passed in to get asynchronous behavior for different objects.
5011 //      modulus == 1 will always return true.
5012 //      modulus == 2 will return true half the time.
5013 //      modulus == 16 will return true for one quarter second interval every four seconds.
5014 int static_rand_timed(int num, int modulus)
5015 {
5016         if (modulus < 2)
5017                 return 1;
5018         else {
5019                 int     t;
5020
5021                 t = Missiontime >> 18;          //      Get time in quarters of a second
5022                 t += num;
5023
5024                 return !(t % modulus);
5025         }
5026 }
5027
5028 //      Maybe fire afterburner based on AI class
5029 int ai_maybe_fire_afterburner(object *objp, ai_info *aip)
5030 {
5031         if (aip->ai_class == 0)
5032                 return 0;               //      Lowest level never aburners away
5033         else  {
5034                 //      Maybe don't afterburner because of a potential collision with the player.
5035                 //      If not multiplayer, near player and player in front, probably don't afterburner.
5036                 if (!(Game_mode & GM_MULTIPLAYER)) {
5037                         if (Ships[objp->instance].team == Player_ship->team) {
5038                                 float   dist;
5039
5040                                 dist = vm_vec_dist_quick(&objp->pos, &Player_obj->pos) - Player_obj->radius - objp->radius;
5041                                 if (dist < 150.0f) {
5042                                         vector  v2p;
5043                                         float           dot;
5044
5045                                         vm_vec_normalized_dir(&v2p, &Player_obj->pos, &objp->pos);
5046                                         dot = vm_vec_dot(&v2p, &objp->orient.v.fvec);
5047
5048                                         if (dot > 0.0f) {
5049                                                 if (dot * dist > 50.0f)
5050                                                         return 0;
5051                                         }
5052                                 }
5053                         }
5054                 }
5055
5056                 if (aip->ai_class >= Num_ai_classes-2)
5057                         return 1;               //      Highest two levels always aburner away.
5058                 else {
5059                         return static_rand_timed(objp-Objects, Num_ai_classes - aip->ai_class);
5060                 }
5061         }
5062 }
5063
5064 //      Maybe engage afterburner after being hit by an object.
5065 void maybe_afterburner_after_ship_hit(object *objp, ai_info *aip, object *en_objp)
5066 {
5067         //      Only do if facing a little away.
5068         if (en_objp != NULL) {
5069                 vector  v2e;
5070
5071                 vm_vec_normalized_dir(&v2e, &en_objp->pos, &objp->pos);
5072                 if (vm_vec_dot(&v2e, &objp->orient.v.fvec) > -0.5f)
5073                         return;
5074         }
5075
5076         if (!( objp->phys_info.flags & PF_AFTERBURNER_ON )) {
5077                 if (ai_maybe_fire_afterburner(objp, aip)) {
5078                         afterburners_start(objp);
5079                         aip->afterburner_stop_time = Missiontime + F1_0/2;
5080                 }
5081         }
5082 }
5083
5084 //      Return true if object *objp is an instructor.
5085 //      Is an instructor if name begins INSTRUCTOR_SHIP_NAME else not.
5086 int is_instructor(object *objp)
5087 {
5088         return !SDL_strncasecmp(Ships[objp->instance].ship_name, INSTRUCTOR_SHIP_NAME, strlen(INSTRUCTOR_SHIP_NAME));
5089 }
5090
5091 //      Evade the weapon aip->danger_weapon_objnum
5092 //      If it's not valid, do a quick out.
5093 //      Evade by accelerating hard.
5094 //      If necessary, turn hard left or hard right.
5095 void evade_weapon()
5096 {
5097         object  *weapon_objp = NULL;
5098         object  *unlocked_weapon_objp = NULL, *locked_weapon_objp = NULL;
5099         vector  weapon_pos, player_pos, goal_point;
5100         vector  vec_from_enemy;
5101         float           dot_from_enemy, dot_to_enemy;
5102         float           dist;
5103         ship            *shipp = &Ships[Pl_objp->instance];
5104         ai_info *aip = &Ai_info[shipp->ai_index];
5105
5106         if (is_instructor(Pl_objp))
5107                 return;
5108
5109         //      Make sure we're actually being attacked.
5110         //      Favor locked objects.
5111         if (aip->nearest_locked_object != -1) {
5112                 if (Objects[aip->nearest_locked_object].type == OBJ_WEAPON)
5113                         locked_weapon_objp = &Objects[aip->nearest_locked_object];
5114         }
5115         
5116         if (aip->danger_weapon_objnum != -1) {
5117                 if (Objects[aip->danger_weapon_objnum].signature == aip->danger_weapon_signature) {
5118                         unlocked_weapon_objp = &Objects[aip->danger_weapon_objnum];
5119                 } else {
5120                         aip->danger_weapon_objnum = -1;         //      Signatures don't match, so no longer endangered.
5121                 }
5122         }
5123
5124         if (locked_weapon_objp != NULL) {
5125                 if (unlocked_weapon_objp != NULL) {
5126                         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))
5127                                 weapon_objp = locked_weapon_objp;
5128                         else
5129                                 weapon_objp = unlocked_weapon_objp;
5130                 } else
5131                         weapon_objp = locked_weapon_objp;
5132         } else if (unlocked_weapon_objp != NULL)
5133                 weapon_objp = unlocked_weapon_objp;
5134         else {
5135                 if (aip->mode == AIM_EVADE_WEAPON)
5136                         maybe_resume_previous_mode(Pl_objp, aip);
5137                 return;
5138         }
5139
5140         SDL_assert(weapon_objp != NULL);
5141
5142         if (weapon_objp->type != OBJ_WEAPON) {
5143                 if (aip->mode == AIM_EVADE_WEAPON)
5144                         maybe_resume_previous_mode(Pl_objp, aip);
5145                 return;
5146         }
5147         
5148         weapon_pos = weapon_objp->pos;
5149         player_pos = Pl_objp->pos;
5150
5151         //      Make speed based on skill level, varying at highest skill level, which is harder to hit.
5152         accelerate_ship(aip, 1.0f);
5153
5154         dist = vm_vec_normalized_dir(&vec_from_enemy, &player_pos, &weapon_pos);
5155
5156         dot_to_enemy = -vm_vec_dot(&Pl_objp->orient.v.fvec, &vec_from_enemy);
5157         dot_from_enemy = vm_vec_dot(&weapon_objp->orient.v.fvec, &vec_from_enemy);
5158         //nprintf(("AI", "dot from enemy = %7.3f\n", dot_from_enemy));
5159
5160         //      If shot is incoming...
5161         if (dot_from_enemy < 0.3f) {
5162                 if (weapon_objp == unlocked_weapon_objp)
5163                         aip->danger_weapon_objnum = -1;
5164                 return;
5165         } else if (dot_from_enemy > 0.7f) {
5166                 if (dist < 200.0f) {
5167                         if (!( Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
5168                                 if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
5169                                         //nprintf(("AI", "Frame %i, turning on afterburner.\n", AI_FrameCount));
5170                                         afterburners_start(Pl_objp);
5171                                         aip->afterburner_stop_time = Missiontime + F1_0/2;
5172                                 }
5173                         }
5174                 }
5175
5176                 //      If we're sort of pointing towards it...
5177                 if ((dot_to_enemy < -0.5f) || (dot_to_enemy > 0.5f)) {
5178                         float   rdot;
5179
5180                         //      Turn hard left or right, depending on which gets out of way quicker.
5181                         rdot = vm_vec_dot(&Pl_objp->orient.v.rvec, &vec_from_enemy);
5182
5183                         if ((rdot < -0.5f) || (rdot > 0.5f))
5184                                 vm_vec_scale_add(&goal_point, &Pl_objp->pos, &Pl_objp->orient.v.rvec, -200.0f);
5185                         else
5186                                 vm_vec_scale_add(&goal_point, &Pl_objp->pos, &Pl_objp->orient.v.rvec, 200.0f);
5187
5188                         turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
5189                 }
5190         }
5191
5192 }
5193
5194 //      Use sliding and backwards moving to face enemy.
5195 //      (Coded 2/20/98.  Works fine, but it's hard to see how to integrate it into the AI system.
5196 //       Typically ships are moving so fast that a little sliding isn't enough to gain an advantage.
5197 //       It's currently used to avoid collisions and could be used to evade weapon fire, but the latter
5198 //       would be frustrating, I think.
5199 //       This function is currently not called.)
5200 void slide_face_ship()
5201 {
5202         ship_info       *sip;
5203
5204         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
5205
5206         //      If can't slide, return.
5207         if ((sip->max_vel.xyz.x == 0.0f) && (sip->max_vel.xyz.y == 0.0f))
5208                 return;
5209
5210         vector  goal_pos;
5211         float           dot_from_enemy;
5212         vector  vec_from_enemy, vec_to_goal;
5213         float           dist;
5214         float           up, right;
5215         ai_info         *aip;
5216
5217         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
5218
5219         dist = vm_vec_normalized_dir(&vec_from_enemy, &Pl_objp->pos, &En_objp->pos);
5220
5221         ai_turn_towards_vector(&En_objp->pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
5222
5223         dot_from_enemy = vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.fvec);
5224
5225         if (vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.rvec) > 0.0f)
5226                 right = 1.0f;
5227         else
5228                 right = -1.0f;
5229
5230         if (vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.uvec) > 0.0f)
5231                 up = 1.0f;
5232         else
5233                 up = -1.0f;
5234
5235         vm_vec_scale_add(&goal_pos, &En_objp->pos, &En_objp->orient.v.rvec, right * 200.0f);
5236         vm_vec_scale_add(&goal_pos, &En_objp->pos, &En_objp->orient.v.uvec, up * 200.0f);
5237
5238         vm_vec_normalized_dir(&vec_to_goal, &goal_pos, &Pl_objp->pos);
5239
5240         if (vm_vec_dot(&vec_to_goal, &Pl_objp->orient.v.rvec) > 0.0f)
5241                 AI_ci.sideways = 1.0f;
5242         else
5243                 AI_ci.sideways = -1.0f;
5244
5245         if (vm_vec_dot(&vec_to_goal, &Pl_objp->orient.v.uvec) > 0.0f)
5246                 AI_ci.vertical = 1.0f;
5247         else
5248                 AI_ci.vertical = -1.0f;
5249
5250         if (dist < 200.0f) {
5251                 if (dot_from_enemy < 0.7f)
5252                         accelerate_ship(aip, -1.0f);
5253                 else
5254                         accelerate_ship(aip, dot_from_enemy + 0.5f);
5255         } else {
5256                 if (dot_from_enemy < 0.7f) {
5257                         accelerate_ship(aip, 0.2f);
5258                 } else {
5259                         accelerate_ship(aip, 1.0f);
5260                 }
5261         }
5262 }
5263
5264 //      General code for handling one ship evading another.
5265 //      Problem: This code is also used for avoiding an impending collision.
5266 //      In such a case, it is not good to go to max speed, which is often good
5267 //      for a certain kind of evasion.
5268 void evade_ship()
5269 {
5270         vector  player_pos, enemy_pos, goal_point;
5271         vector  vec_from_enemy;
5272         float           dot_from_enemy;
5273         float           dist;
5274         ship            *shipp = &Ships[Pl_objp->instance];
5275         ship_info       *sip = &Ship_info[shipp->ship_info_index];
5276         ai_info *aip = &Ai_info[shipp->ai_index];
5277         float           bank_override = 0.0f;
5278
5279         ai_set_positions(Pl_objp, En_objp, aip, &player_pos, &enemy_pos);
5280
5281         //      Make speed based on skill level, varying at highest skill level, which is harder to hit.
5282         if (Game_skill_level == NUM_SKILL_LEVELS-1) {
5283                 int     rand_int;
5284                 float   accel_val;
5285
5286                 rand_int = static_rand(Pl_objp-Objects);
5287                 accel_val = (float) (((Missiontime^rand_int) >> 14) & 0x0f)/32.0f + 0.5f;
5288                 accelerate_ship(aip, accel_val);
5289                 //nprintf(("AI", "Accel value = %7.3f\n", accel_val));
5290         } else
5291                 accelerate_ship(aip, (float) (Game_skill_level+2) / (NUM_SKILL_LEVELS+1));
5292
5293         if ((Missiontime - aip->submode_start_time > F1_0/2) && (sip->afterburner_fuel_capacity > 0.0f)) {
5294                 float percent_left = 100.0f * shipp->afterburner_fuel / sip->afterburner_fuel_capacity;
5295                 if (percent_left > 30.0f + ((Pl_objp-Objects) & 0x0f)) {
5296                         afterburners_start(Pl_objp);
5297                         aip->afterburner_stop_time = Missiontime + F1_0 + static_rand(Pl_objp-Objects)/4;
5298                 }
5299         }
5300
5301         vm_vec_sub(&vec_from_enemy, &player_pos, &enemy_pos);
5302
5303         dist = vm_vec_normalize(&vec_from_enemy);
5304         dot_from_enemy = vm_vec_dot(&En_objp->orient.v.fvec, &vec_from_enemy);
5305
5306         if (dist > 250.0f) {
5307                 vector  gp1, gp2;
5308                 //      If far away from enemy, circle, going to nearer of point far off left or right wing
5309                 vm_vec_scale_add(&gp1, &enemy_pos, &En_objp->orient.v.rvec, 250.0f);
5310                 vm_vec_scale_add(&gp2, &enemy_pos, &En_objp->orient.v.rvec, -250.0f);
5311                 if (vm_vec_dist_quick(&gp1, &Pl_objp->pos) < vm_vec_dist_quick(&gp2, &Pl_objp->pos))
5312                         goal_point = gp1;
5313                 else
5314                         goal_point = gp2;
5315         } else if (dot_from_enemy < 0.1f) {
5316                 //      If already close to behind, goal is to get completely behind.
5317                 vm_vec_scale_add(&goal_point, &enemy_pos, &En_objp->orient.v.fvec, -1000.0f);
5318         } else if (dot_from_enemy > 0.9f) {
5319                 //      If enemy pointing almost right at self, and self pointing close to enemy, turn away from
5320                 vector  vec_to_enemy;
5321                 float           dot_to_enemy;
5322
5323                 vm_vec_sub(&vec_to_enemy, &enemy_pos, &player_pos);
5324
5325                 vm_vec_normalize(&vec_to_enemy);
5326                 dot_to_enemy = vm_vec_dot(&Pl_objp->orient.v.fvec, &vec_to_enemy);
5327                 if (dot_to_enemy > 0.75f) {
5328                         //      Used to go to En_objp's right vector, but due to banking while turning, that
5329                         //      caused flying in an odd spiral.
5330                         vm_vec_scale_add(&goal_point, &enemy_pos, &Pl_objp->orient.v.rvec, 1000.0f);
5331                         if (dist < 100.0f)
5332                                 bank_override = Pl_objp->phys_info.speed; 
5333                 } else {
5334                         bank_override = Pl_objp->phys_info.speed;                       //      In enemy's sights, not pointing at him, twirl away.
5335                         // nprintf(("Mike", " Do sumpin' else."));
5336                         goto evade_ship_l1;
5337                 }
5338         } else {
5339 evade_ship_l1: ;
5340                 if (aip->ai_evasion > myrand()*100.0f/32767.0f) {
5341                         int     temp;
5342                         float   scale;
5343                         float   psrandval;      //      some value close to zero to choose whether to turn right or left.
5344
5345                         psrandval = (float) (((Missiontime >> 14) & 0x0f) - 8); //      Value between -8 and 7
5346                         psrandval = psrandval/16.0f;                                                    //      Value between -1/2 and 1/2 (approx)
5347
5348                         //      If not close to behind, turn towards his right or left vector, whichever won't cross his path.
5349                         if (vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.rvec) > psrandval) {
5350                                 scale = 1000.0f;
5351                         } else {
5352                                 scale = -1000.0f;
5353                         }
5354
5355                         vm_vec_scale_add(&goal_point, &enemy_pos, &En_objp->orient.v.rvec, scale);
5356
5357                         temp = ((Missiontime >> 16) & 0x07);
5358                         temp = ((temp * (temp+1)) % 16)/2 - 4;
5359                         if ((psrandval == 0) && (temp == 0))
5360                                 temp = 3;
5361
5362                         scale = 200.0f * temp;
5363
5364                         vm_vec_scale_add2(&goal_point, &En_objp->orient.v.uvec, scale);
5365                 } else {
5366                         //      No evasion this frame, but continue with previous turn.
5367                         //      Reason: If you don't, you lose rotational momentum.  Turning every other frame,
5368                         //      and not in between results in a very slow turn because of loss of momentum.
5369                         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))
5370                                 goal_point = aip->prev_goal_point;
5371                         else
5372                                 vm_vec_scale_add(&goal_point, &enemy_pos, &En_objp->orient.v.rvec, 100.0f);
5373                 }
5374         }
5375
5376         // nprintf(("Mike", "Goal point = %7.1f %7.1f %7.1f\n", goal_point.xyz.x, goal_point.xyz.y, goal_point.xyz.z));
5377         turn_towards_point(Pl_objp, &goal_point, NULL, bank_override);
5378
5379         aip->prev_goal_point = goal_point;
5380 }
5381
5382 //      --------------------------------------------------------------------------
5383 //      Fly in a manner making it difficult for opponent to attack.
5384 void ai_evade()
5385 {
5386         evade_ship();
5387 }
5388
5389 /*
5390 // -------------------------------------------------------------------
5391 //      Refine predicted enemy position because enemy will move while we move
5392 //      towards predicted enemy position.
5393 //      last_delta_vec is stuffed with size of polishing in last step.  This small amount
5394 //      can be used to perturb the predicted position to make firing not be exact.
5395 //      This function will almost always undershoot actual position, assuming both ships
5396 //      are moving at constant speed.  But with even one polishing step, the error should
5397 //      be under 1%. The number of polishing steps is specified in the parameter num_polish_steps.
5398 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)
5399 {
5400         int     iteration;
5401         vector  player_pos = pobjp->pos;
5402         vector  enemy_pos = *predicted_enemy_pos;
5403         physics_info    *en_physp = &eobjp->phys_info;
5404         float           time_to_enemy;
5405         vector  last_predicted_enemy_pos = *predicted_enemy_pos;
5406         
5407         vm_vec_zero(last_delta_vec);
5408
5409         for (iteration=0; iteration < num_polish_steps; iteration++) {
5410                 dist_to_enemy = vm_vec_dist_quick(predicted_enemy_pos, &player_pos);
5411                 time_to_enemy = compute_time_to_enemy(dist_to_enemy, pobjp, eobjp);
5412                 vm_vec_scale_add(predicted_enemy_pos, &eobjp->pos, &eobjp->phys_info.vel, time_to_enemy);
5413                 vm_vec_sub(last_delta_vec, predicted_enemy_pos, &last_predicted_enemy_pos);
5414                 last_predicted_enemy_pos= *predicted_enemy_pos;
5415         }
5416 }
5417 */
5418
5419 /*
5420 Relevant variables are:
5421         best_dot_to_enemy               best dot product to enemy in last BEST_DOT_TIME seconds
5422         best_dot_to_time                time at which best dot occurred
5423         best_dot_from_enemy     best dot product for enemy to player in last BEST_DOT_TIME seconds
5424         best_dot_from_time      time at which best dot occurred
5425         submode_start_time      time at which we entered the current submode
5426         previous_submode                previous submode, get it?
5427 Legal submodes are:
5428         CONTINUOUS_TURN vector_id {0..3 = right, -right, up, -up}
5429         ATTACK
5430         EVADE_SQUIGGLE
5431         EVADE_BRAKE
5432 */
5433
5434 float   G_collision_time;
5435 vector  G_predicted_pos, G_fire_pos;
5436
5437 /*
5438 void show_firing_diag()
5439 {
5440         float           dot;
5441         vector  v2t;
5442         vector  pos1, pos2;
5443         float           dist;
5444
5445         if (G_collision_time == 0.0f)
5446                 return;
5447
5448         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",
5449                 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));
5450         vm_vec_normalized_dir(&v2t, &G_predicted_pos, &G_fire_pos);
5451         dot = vm_vec_dot(&v2t, &Pl_objp->orient.v.fvec);
5452         mprintf(("Dot of v.fvec and vector to predicted position = %10.7f (%7.3f degrees)\n", dot, acos(dot)*180.0f/3.141592654f));
5453
5454         vm_vec_scale_add(&pos1, &En_objp->pos, &En_objp->phys_info.vel, G_collision_time);
5455         vm_vec_scale_add(&pos2, &G_fire_pos, &Pl_objp->orient.v.fvec, G_collision_time*300.0f);
5456         dist = vm_vec_dist(&pos1, &pos2);
5457
5458         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));
5459 }
5460 */
5461
5462 //      If:
5463 //              flags & WIF_PUNCTURE
5464 //      Then Select a Puncture weapon.
5465 //      Else
5466 //              Select Any ol' weapon.
5467 //      Returns primary_bank index.
5468 int ai_select_primary_weapon(object *objp, object *other_objp, int flags)
5469 {
5470         ship    *shipp = &Ships[objp->instance];
5471         ship_weapon *swp = &shipp->weapons;
5472
5473         //SDL_assert( other_objp != NULL );
5474         SDL_assert( shipp->ship_info_index >= 0 && shipp->ship_info_index < MAX_SHIP_TYPES);
5475
5476         if (flags & WIF_PUNCTURE) {
5477                 if (swp->current_primary_bank >= 0) {
5478                         int     bank_index;
5479
5480                         bank_index = swp->current_primary_bank;
5481
5482                         if (Weapon_info[swp->primary_bank_weapons[bank_index]].wi_flags & WIF_PUNCTURE) {
5483                                 //nprintf(("AI", "%i: Ship %s selecting weapon %s\n", Framecount, Ships[objp->instance].ship_name, Weapon_info[swp->primary_bank_weapons[bank_index]].name));
5484                                 return swp->current_primary_bank;
5485                         }
5486                 }
5487                 for (int i=0; i<swp->num_primary_banks; i++) {
5488                         int     weapon_info_index;
5489
5490                         weapon_info_index = swp->primary_bank_weapons[i];
5491
5492                         if (weapon_info_index > -1){
5493                                 if (Weapon_info[weapon_info_index].wi_flags & WIF_PUNCTURE) {
5494                                         swp->current_primary_bank = i;
5495                                         //nprintf(("AI", "%i: Ship %s selecting weapon %s\n", Framecount, Ships[objp->instance].ship_name, Weapon_info[swp->primary_bank_weapons[i]].name));
5496                                         return i;
5497                                 }
5498                         }
5499                 }
5500                 
5501                 // AL 26-3-98: If we couldn't find a puncture weapon, pick first available weapon if one isn't active
5502                 if ( swp->current_primary_bank < 0 ) {
5503                         if ( swp->num_primary_banks > 0 ) {
5504                                 swp->current_primary_bank = 0;
5505                         }
5506                 }
5507
5508         } else {                //      Don't need to be using a puncture weapon.
5509                 if (swp->current_primary_bank >= 0) {
5510                         if (!(Weapon_info[swp->primary_bank_weapons[swp->current_primary_bank]].wi_flags & WIF_PUNCTURE)){
5511                                 return swp->current_primary_bank;
5512                         }
5513                 }
5514                 for (int i=0; i<swp->num_primary_banks; i++) {
5515                         if (swp->primary_bank_weapons[i] > -1) {
5516                                 if (!(Weapon_info[swp->primary_bank_weapons[i]].wi_flags & WIF_PUNCTURE)) {
5517                                         swp->current_primary_bank = i;
5518                                         nprintf(("AI", "%i: Ship %s selecting weapon %s\n", Framecount, Ships[objp->instance].ship_name, Weapon_info[swp->primary_bank_weapons[i]].name));
5519                                         return i;
5520                                 }
5521                         }
5522                 }
5523                 //      Wasn't able to find a non-puncture weapon.  Stick with what we have.
5524         }
5525
5526         SDL_assert( swp->current_primary_bank != -1 );          // get Alan or Allender
5527
5528         return swp->current_primary_bank;
5529 }
5530
5531 //      --------------------------------------------------------------------------
5532 //      Maybe link primary weapons.
5533 void set_primary_weapon_linkage(object *objp)
5534 {
5535         ship            *shipp;
5536         ai_info *aip;
5537
5538         shipp = &Ships[objp->instance];
5539         aip     = &Ai_info[shipp->ai_index];
5540
5541         shipp->flags &= ~SF_PRIMARY_LINKED;
5542
5543         if (Num_weapons > (int) (MAX_WEAPONS * 0.75f)) {
5544                 if (shipp->flags & SF_PRIMARY_LINKED)
5545                         nprintf(("AI", "Frame %i, ship %s: Unlinking primaries.\n", Framecount, shipp->ship_name));
5546                 shipp->flags &= ~SF_PRIMARY_LINKED;
5547                 return;         //      If low on slots, don't link.
5548         }
5549
5550         shipp->flags &= ~SF_PRIMARY_LINKED;
5551
5552         // AL: ensure target is a ship!
5553         if ( Objects[aip->target_objnum].type == OBJ_SHIP ) {
5554                 // If trying to destroy a big ship (i.e., not disable/disarm), always unleash all weapons
5555                 if ( ship_get_SIF(&Ships[Objects[aip->target_objnum].instance]) & SIF_BIG_SHIP) {
5556                         if ( aip->targeted_subsys == NULL ) {
5557                                 shipp->flags |= SF_PRIMARY_LINKED;
5558                                 shipp->flags |= SF_SECONDARY_DUAL_FIRE;
5559                                 return;
5560                         }
5561                 }
5562         }
5563
5564         // AL 2-11-98: If ship has a disarm or disable goal, don't link unless both weapons are
5565         //                                      puncture weapons
5566         if ( (aip->active_goal != AI_GOAL_NONE) && (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC) ) {
5567                 if ( aip->goals[aip->active_goal].ai_mode & (AI_GOAL_DISABLE_SHIP|AI_GOAL_DISARM_SHIP) ) {
5568                         ship_weapon     *swp;
5569                         swp = &shipp->weapons;
5570                         // only continue if both primaries are puncture weapons
5571                         if ( swp->num_primary_banks == 2 ) {
5572                                 if ( !(Weapon_info[swp->primary_bank_weapons[0]].wi_flags & WIF_PUNCTURE) ) 
5573                                         return;
5574                                 if ( !(Weapon_info[swp->primary_bank_weapons[1]].wi_flags & WIF_PUNCTURE) ) 
5575                                         return;
5576                         }
5577                 }
5578         }
5579
5580         //      Don't want all ships always linking weapons at start, so asynchronize.
5581         if (Missiontime < i2f(30))
5582                 return;
5583         else if (Missiontime < i2f(120)) {
5584                 int r = static_rand((Missiontime >> 17) ^ OBJ_INDEX(objp));
5585                 if ( (r&3) != 0)
5586                         return;
5587         }
5588
5589         if (shipp->weapon_energy > Link_energy_levels_always[Game_skill_level]) {
5590                 shipp->flags |= SF_PRIMARY_LINKED;
5591         } else if (shipp->weapon_energy > Link_energy_levels_maybe[Game_skill_level]) {
5592                 if (objp->hull_strength < Ship_info[shipp->ship_info_index].initial_hull_strength/3.0f)
5593                         shipp->flags |= SF_PRIMARY_LINKED;
5594         }
5595 }
5596
5597 //      --------------------------------------------------------------------------
5598 //      Fire the current primary weapon.
5599 //      *objp is the object to fire from.
5600 void ai_fire_primary_weapon(object *objp)
5601 {
5602         ship                    *shipp = &Ships[objp->instance];
5603         ship_weapon     *swp = &shipp->weapons;
5604         ai_info         *aip;
5605         object          *enemy_objp;
5606
5607         SDL_assert( shipp->ship_info_index >= 0 && shipp->ship_info_index < MAX_SHIP_TYPES);
5608
5609         aip = &Ai_info[shipp->ai_index];
5610
5611         //      If low on slots, fire a little less often.
5612         if (Num_weapons > (int) (0.9f * MAX_WEAPONS)) {
5613                 if (frand() > 0.5f) {
5614                         nprintf(("AI", "Frame %i, %s not fire.\n", Framecount, shipp->ship_name));
5615                         return;
5616                 }
5617         }
5618
5619         if (!Ai_firing_enabled){
5620                 return;
5621         }
5622
5623         if (aip->target_objnum != -1){
5624                 enemy_objp = &Objects[aip->target_objnum];
5625         } else {
5626                 enemy_objp = NULL;
5627         }
5628
5629         if ( (swp->current_primary_bank < 0) || (swp->current_primary_bank >= swp->num_primary_banks) || timestamp_elapsed(aip->primary_select_timestamp)) {
5630                 int     flags = 0;
5631                 // AL 2-11-98: If attacking any subsystem (not just engines), use disrupter weapon
5632 //              if ((aip->targeted_subsys != NULL) && (aip->targeted_subsys->system_info->type == SUBSYSTEM_ENGINE)) {
5633                 if ( aip->targeted_subsys != NULL ) {
5634                         flags = WIF_PUNCTURE;
5635                 }
5636                 ai_select_primary_weapon(objp, enemy_objp, flags);
5637                 ship_primary_changed(shipp);    // AL: maybe send multiplayer information when AI ship changes primaries
5638                 aip->primary_select_timestamp = timestamp(5 * 1000);    //      Maybe change primary weapon five seconds from now.
5639         }
5640
5641         //      If pointing nearly at predicted collision point of target, bash orientation to be perfectly pointing.
5642         float   dot;
5643         vector  v2t;
5644
5645 //      if (!IS_VEC_NULL(&G_predicted_pos)) {
5646         if (!( vm_vec_mag_quick(&G_predicted_pos) < AICODE_SMALL_MAGNITUDE )) {
5647                 if ( !vm_vec_cmp(&G_predicted_pos, &G_fire_pos) ) {
5648                         nprintf(("Warning", "Avoid NULL vector assert.. why are G_predicted_pos and G_fire_pos the same?\n"));
5649                 } else {
5650                         vm_vec_normalized_dir(&v2t, &G_predicted_pos, &G_fire_pos);
5651                         dot = vm_vec_dot(&v2t, &objp->orient.v.fvec);
5652                         if (dot > .998629534f){ //      if within 3.0 degrees of desired heading, bash
5653                                 vm_vector_2_matrix(&objp->orient, &v2t, &objp->orient.v.uvec, NULL);
5654                         }
5655                 }
5656         }
5657
5658         //      Make sure not firing at a protected ship unless firing at a live subsystem.
5659         //      Note: This happens every time the ship tries to fire, perhaps every frame.
5660         //      Should be wrapped in a timestamp, same one that enables it to fire, but that is complicated
5661         //      by multiple banks it can fire from.
5662         if (aip->target_objnum != -1) {
5663                 object  *tobjp = &Objects[aip->target_objnum];
5664                 if (tobjp->flags & OF_PROTECTED) {
5665                         if (aip->targeted_subsys != NULL) {
5666                                 int     type;
5667
5668                                 type = aip->targeted_subsys->system_info->type;
5669                                 if (ship_get_subsystem_strength(&Ships[tobjp->instance], type) == 0.0f) {
5670                                         aip->target_objnum = -1;
5671                                         return;
5672                                 }
5673                         } else {
5674                                 aip->target_objnum = -1;
5675                                 return;
5676                         }
5677                 }
5678         }
5679
5680         //      If enemy is protected, not firing a puncture weapon and enemy's hull is low, don't fire.
5681         if ((enemy_objp != NULL) && (enemy_objp->flags & OF_PROTECTED)) {
5682                 // AL: 3-6-98: Check if current_primary_bank is valid
5683                 if ((enemy_objp->hull_strength < 750.0f) && 
5684                         ((aip->targeted_subsys == NULL) || (enemy_objp->hull_strength < aip->targeted_subsys->current_hits + 50.0f)) &&
5685                         (swp->current_primary_bank >= 0) ) {
5686                         if (!(Weapon_info[swp->primary_bank_weapons[swp->current_primary_bank]].wi_flags & WIF_PUNCTURE)) {
5687                                 //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));
5688                                 swp->next_primary_fire_stamp[swp->current_primary_bank] = timestamp(1000);
5689                                 return;
5690                         }
5691
5692                         /*
5693                         int     num_attacking;
5694                         num_attacking = num_enemies_attacking(enemy_objp-Objects);
5695                         if (enemy_objp->hull_strength / num_attacking < 200.0f) {
5696                                 if (frand() < 0.75f) {
5697                                         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));
5698                                         swp->next_primary_fire_stamp[swp->current_primary_bank] = timestamp(500);
5699                                         return;
5700                                 }
5701                         }
5702                         */
5703                 }
5704         }
5705
5706         set_primary_weapon_linkage(objp);
5707         
5708         // I think this will properly solve the problem
5709         // fire non-streaming weapons
5710         ship_fire_primary(objp, 0);
5711         
5712         // fire streaming weapons
5713         shipp->flags |= SF_TRIGGER_DOWN;
5714         ship_fire_primary(objp, 1);
5715         shipp->flags &= ~SF_TRIGGER_DOWN;
5716 }
5717
5718 //      --------------------------------------------------------------------------
5719 //      Return number of nearby enemy fighters.
5720 //      threshold is the distance within which a ship is considered near.
5721 //
5722 // input:       enemy_team_mask =>      teams that are considered as an enemy
5723 //                              pos                                     =>      world position to measure ship distances from
5724 //                              threshold                       =>      max distance from pos to be considered "near"
5725 //
5726 // exit:                number of ships within threshold units of pos
5727 int num_nearby_fighters(int enemy_team_mask, vector *pos, float threshold)
5728 {
5729         ship_obj        *so;
5730         object  *ship_objp;
5731         int             count = 0;
5732
5733         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
5734
5735                 ship_objp = &Objects[so->objnum];
5736
5737                 if (Ships[ship_objp->instance].team & enemy_team_mask) {
5738                         if (Ship_info[Ships[ship_objp->instance].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER)) {
5739                                 if (vm_vec_dist_quick(pos, &ship_objp->pos) < threshold)
5740                                         count++;
5741                         }
5742                 }
5743         }
5744
5745         return count;
5746 }
5747
5748 //      --------------------------------------------------------------------------
5749 //      Select secondary weapon to fire.
5750 //      Currently, 1/16/98:
5751 //              If 0 secondary weapons available, return -1
5752 //              If 1 available, use it.
5753 //              If 2 or more, if the current weapon is one of them, stick with it, otherwise choose a random one.
5754 //      priority1 and priority2 are Weapon_info[] bitmasks such as WIF_HOMING_ASPECT.  If any weapon has any bit in priority1
5755 //      set, that weapon will be selected.  If not, apply to priority2.  If neither, return -1, meaning no weapon selected.
5756 //      Note, priorityX have default values of -1, meaning if not set, they will match any weapon.
5757 //      Return value:
5758 //              bank index
5759 //      Should do this:
5760 //              Favor aspect seekers when attacking small ships faraway.
5761 //              Favor rapid fire dumbfire when attacking a large ship.
5762 //              Ignore heat seekers because we're not sure how they'll work.
5763 void ai_select_secondary_weapon(object *objp, ship_weapon *swp, int priority1 = -1, int priority2 = -1)
5764 {
5765         int     num_weapon_types;
5766         int     weapon_id_list[MAX_WEAPON_TYPES], weapon_bank_list[MAX_WEAPON_TYPES];
5767         int     i;
5768         int     ignore_mask;
5769         int     initial_bank;
5770
5771         initial_bank = swp->current_secondary_bank;
5772
5773         //      Ignore bombs unless one of the priorities asks for them to be selected.
5774         if (WIF_HUGE & (priority1 | priority2))
5775                 ignore_mask = 0;
5776         else
5777                 ignore_mask = WIF_HUGE;
5778
5779         if (!(WIF_BOMBER_PLUS & (priority1 | priority2)))
5780                 ignore_mask |= WIF_BOMBER_PLUS;
5781
5782 #ifndef NDEBUG
5783         for (i=0; i<MAX_WEAPON_TYPES; i++) {
5784                 weapon_id_list[i] = -1;
5785                 weapon_bank_list[i] = -1;
5786         }
5787 #endif
5788
5789         //      Stuff weapon_bank_list with bank index of available weapons.
5790         num_weapon_types = get_available_secondary_weapons(objp, weapon_id_list, weapon_bank_list);
5791
5792         int     priority2_index = -1;
5793
5794         for (i=0; i<num_weapon_types; i++) {
5795                 int     wi_flags;
5796
5797                 wi_flags = Weapon_info[swp->secondary_bank_weapons[weapon_bank_list[i]]].wi_flags;
5798                 if (!(wi_flags & ignore_mask)) {                                        //      Maybe bombs are illegal.
5799                         if (wi_flags & priority1) {
5800                                 swp->current_secondary_bank = weapon_bank_list[i];                              //      Found first priority, return it.
5801                                 break;
5802                         } else if (wi_flags & priority2)
5803                                 priority2_index = weapon_bank_list[i];  //      Found second priority, but might still find first priority.
5804                 }
5805         }
5806
5807         //      If didn't find anything above, then pick any secondary weapon.
5808         if (i == num_weapon_types) {
5809                 swp->current_secondary_bank = priority2_index;  //      Assume we won't find anything.
5810                 if (priority2_index == -1) {
5811                         for (i=0; i<num_weapon_types; i++) {
5812                                 int     wi_flags;
5813
5814                                 wi_flags = Weapon_info[swp->secondary_bank_weapons[weapon_bank_list[i]]].wi_flags;
5815                                 if (!(wi_flags & ignore_mask)) {                                        //      Maybe bombs are illegal.
5816                                         if (swp->secondary_bank_ammo[i] > 0) {
5817                                                 swp->current_secondary_bank = i;
5818                                                 break;
5819                                         }
5820                                 }
5821                         }
5822                 }
5823         }
5824
5825         //      If switched banks, force reacquisition of aspect lock.
5826         if (swp->current_secondary_bank != initial_bank) {
5827                 ai_info *aip = &Ai_info[Ships[objp->instance].ai_index];
5828                 
5829                 aip->aspect_locked_time = 0.0f;
5830                 aip->current_target_is_locked = 0;
5831         }
5832
5833
5834         ship_secondary_changed(&Ships[objp->instance]); // AL: let multiplayer know if secondary bank has changed
5835         // nprintf(("AI", "Ship %s selected weapon %s\n", Ships[objp->instance].ship_name, Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]].name));
5836 }
5837
5838 //      Return number of objects homing on object *target_objp
5839 int compute_num_homing_objects(object *target_objp)
5840 {
5841         object  *objp;
5842         int             count = 0;
5843
5844         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
5845                 if (objp->type == OBJ_WEAPON) {
5846                         if (Weapon_info[Weapons[objp->instance].weapon_info_index].wi_flags & WIF_HOMING) {
5847                                 if (Weapons[objp->instance].homing_object == target_objp) {
5848                                         count++;
5849                                 }
5850                         }
5851                 }
5852         }
5853
5854         return count;
5855 }
5856
5857 //      Object *firing_objp just fired weapon weapon_index (index in Weapon_info).
5858 //      If it's a shockwave weapon, tell your team about it!
5859 void ai_maybe_announce_shockwave_weapon(object *firing_objp, int weapon_index)
5860 {
5861         if ((firing_objp->type == OBJ_SHIP) && (Weapon_info[weapon_index].shockwave_speed > 0.0f)) {
5862                 ship_obj        *so;
5863                 int             firing_ship_team;
5864
5865                 firing_ship_team = Ships[firing_objp->instance].team;
5866
5867                 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
5868                         object  *A = &Objects[so->objnum];
5869                         SDL_assert(A->type == OBJ_SHIP);
5870
5871                         if (Ships[A->instance].team == firing_ship_team) {
5872                                 ai_info *aip = &Ai_info[Ships[A->instance].ai_index];
5873                                 // AL 1-5-98: only avoid shockwave if not docked or repairing
5874                                 if ( !(aip->ai_flags & (AIF_DOCKED|AIF_BEING_REPAIRED)) ) {
5875                                         aip->ai_flags |= AIF_AVOID_SHOCKWAVE_WEAPON;
5876                                 }
5877                         }
5878                 }
5879         }
5880 }
5881
5882 //      Return total payload of all incoming missiles.
5883 float compute_incoming_payload(object *target_objp)
5884 {
5885         missile_obj     *mo;
5886         float                   payload = 0.0f;
5887
5888         for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
5889                 object  *objp;
5890
5891                 objp = &Objects[mo->objnum];
5892                 SDL_assert(objp->type == OBJ_WEAPON);
5893                 if (Weapons[objp->instance].homing_object == target_objp) {
5894                         payload += Weapon_info[Weapons[objp->instance].weapon_info_index].damage;
5895                 }
5896         }
5897
5898         return payload;
5899 }
5900
5901 //      --------------------------------------------------------------------------
5902 //      Return true if OK for *aip to fire its current weapon at its current target.
5903 //      Only reason this function returns false is:
5904 //              weapon is a homer
5905 //              targeted at player
5906 //                      OR:     player has too many homers targeted at him
5907 //                                      Missiontime in that dead zone in which can't fire at this player
5908 //      Note: If player is attacking a ship, that ship is allowed to fire at player.  Otherwise, we get in a situation in which
5909 //      player is attacking a large ship, but that large ship is not defending itself with missiles.
5910 int check_ok_to_fire(int objnum, int target_objnum, weapon_info *wip)
5911 {
5912         int     num_homers = 0;
5913         object  *tobjp = &Objects[target_objnum];
5914
5915         if (target_objnum > -1) {
5916                 // AL 3-4-98: Ensure objp target is a ship first 
5917                 if ( tobjp->type == OBJ_SHIP ) {
5918
5919                         // should not get this far. check if ship is protected from beam and weapon is type beam
5920                         if ( (wip->wi_flags & WIF_BEAM) && (tobjp->flags & OF_BEAM_PROTECTED) ) {
5921                                 Int3();
5922                                 return 0;
5923                         }
5924                         if (Ship_info[Ships[tobjp->instance].ship_info_index].flags & SIF_SMALL_SHIP) {
5925                                 num_homers = compute_num_homing_objects(&Objects[target_objnum]);
5926                         }
5927                 }
5928
5929                 //      If player, maybe fire based on Skill_level and number of incoming weapons.
5930                 //      If non-player, maybe fire based on payload of incoming weapons.
5931                 if (wip->wi_flags & WIF_HOMING) {
5932                         if ((target_objnum > -1) && (tobjp->flags & OF_PLAYER_SHIP)) {
5933                                 if (Ai_info[Ships[tobjp->instance].ai_index].target_objnum != objnum) {
5934                                         //      Don't allow AI ships to fire at player for fixed periods of time based on skill level.
5935                                         //      With 5 skill levels, at Very Easy, they fire in 1/7 of every 10 second interval.
5936                                         //      At Easy, 2/7...at Expert, 5/7
5937                                         int t = ((Missiontime /(65536*10)) ^ target_objnum ^ 0x01) % (NUM_SKILL_LEVELS+2);
5938                                         if (t > Game_skill_level) {
5939                                                 //nprintf(("AI", "Not OK to fire homer at time thing %i\n", t));
5940                                                 return 0;
5941                                         }
5942                                 }
5943                                 //nprintf(("AI", " IS OK to fire homer at time thing %i ***\n", t));
5944                                 int     swarmers = 0;
5945                                 if (wip->wi_flags & WIF_SWARM)
5946                                         swarmers = 2;   //      Note, always want to be able to fire swarmers if no currently incident homers.
5947                                 if (Max_allowed_player_homers[Game_skill_level] < num_homers + swarmers) {
5948                                         return 0;
5949                                 }
5950                         } else if (num_homers > 3) {
5951                                 float   incoming_payload;
5952
5953                                 incoming_payload = compute_incoming_payload(&Objects[target_objnum]);
5954
5955                                 if (incoming_payload > tobjp->hull_strength) {
5956                                         return 0;
5957                                 }
5958                         }
5959                 }
5960         }
5961
5962         return 1;
5963 }
5964
5965 //      --------------------------------------------------------------------------
5966 //      Fire a secondary weapon.
5967 //      Maybe choose to fire a different one.
5968 //      priority1 and priority2 are optional parameters with defaults = -1
5969 int ai_fire_secondary_weapon(object *objp, int priority1, int priority2)
5970 {
5971         ship_weapon *swp;
5972         ship    *shipp;
5973         int             current_bank;
5974         int             rval = 0;
5975
5976 #ifndef NDEBUG
5977         if (!Ai_firing_enabled)
5978                 return rval;
5979 #endif
5980
5981         SDL_assert( objp != NULL );
5982         SDL_assert(objp->type == OBJ_SHIP);
5983         shipp = &Ships[objp->instance];
5984         swp = &shipp->weapons;
5985
5986         //      Select secondary weapon.
5987         current_bank = swp->current_secondary_bank; //ai_select_secondary_weapon(objp, swp, priority1, priority2);
5988
5989         //nprintf(("AI", "Frame %i: Current bank = %i, ammo remaining = %i\n", Framecount, current_bank, swp->secondary_bank_ammo[current_bank]));
5990         if (current_bank == -1) {
5991                 swp->next_secondary_fire_stamp[current_bank] = timestamp(500);
5992                 return rval;
5993         }
5994
5995         SDL_assert(current_bank < shipp->weapons.num_secondary_banks);
5996
5997         weapon_info     *wip = &Weapon_info[shipp->weapons.secondary_bank_weapons[current_bank]];
5998
5999         if ((wip->wi_flags & WIF_HOMING_ASPECT) && (!Ai_info[shipp->ai_index].current_target_is_locked)) {
6000                 //nprintf(("AI", "Not firing secondary weapon because not aspect locked.\n"));
6001                 swp->next_secondary_fire_stamp[current_bank] = timestamp(250);
6002         } else if ((wip->wi_flags & WIF_BOMB) || (vm_vec_dist_quick(&objp->pos, &En_objp->pos) > 50.0f)) {
6003                 //      This might look dumb, firing a bomb even if closer than 50 meters, but the reason is, if you're carrying
6004                 //      bombs, delivering them is probably more important than surviving.
6005                 ai_info *aip;
6006
6007                 aip = &Ai_info[shipp->ai_index];
6008                 
6009                 //      Note, maybe don't fire if firing at player and any homers yet fired.
6010                 //      Decreasing chance to fire the more homers are incoming on player.
6011                 if (check_ok_to_fire(OBJ_INDEX(objp), aip->target_objnum, wip)) {
6012                         if (ship_fire_secondary(objp)) {
6013                                 rval = 1;
6014                                 swp->next_secondary_fire_stamp[current_bank] = timestamp(500);
6015                                 //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));
6016                         }
6017
6018                 } else {
6019                         swp->next_secondary_fire_stamp[current_bank] = timestamp(500);
6020                 }
6021         }
6022
6023         return rval;
6024 }
6025
6026 //      Return true if it looks like obj1, if continuing to move along current vector, will
6027 //      collide with obj2.
6028 int might_collide_with_ship(object *obj1, object *obj2, float dot_to_enemy, float dist_to_enemy, float duration)
6029 {
6030         if (obj1->phys_info.speed * duration + 2*(obj1->radius + obj2->radius) > dist_to_enemy)
6031                 if (dot_to_enemy > 0.8f - 2*(obj1->radius + obj2->radius)/dist_to_enemy)
6032                         return objects_will_collide(obj1, obj2, duration, 2.0f);
6033
6034 //              BABY - 
6035 //              CONDITION 1, dist_to_enemy < o1_rad + o2_rad + (obj1.speed + obj2.speed) * time + 50
6036         
6037         return 0;
6038
6039 }
6040
6041 //      --------------------------------------------------------------------------
6042 //      Return true if ship *objp firing a laser believes it will hit a teammate.
6043 int might_hit_teammate(object *firing_objp)
6044 {
6045         int             team;
6046         object  *objp;
6047         ship_obj        *so;
6048
6049         team = Ships[firing_objp->instance].team;
6050
6051         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
6052                 objp = &Objects[so->objnum];
6053                 if (Ships[objp->instance].team == team) {
6054                         float           dist, dot;
6055                         vector  vec_to_objp;
6056
6057                         vm_vec_sub(&vec_to_objp, &firing_objp->pos, &objp->pos);
6058                         dist = vm_vec_mag_quick(&vec_to_objp);
6059                         dot = vm_vec_dot(&firing_objp->orient.v.fvec, &vec_to_objp)/dist;
6060                         if (might_collide_with_ship(firing_objp, objp, dot, dist, 2.0f))
6061                                 return 1;
6062                 }
6063         }
6064
6065         return 0;
6066
6067 }
6068
6069 //int   Team_not_fire_count=0, Team_hit_count = 0;
6070
6071 void render_all_ship_bay_paths(object *objp)
6072 {
6073         int             i,j,color;
6074         ship            *sp = &Ships[objp->instance];
6075         polymodel       *pm;
6076         model_path      *mp;
6077
6078         pm = model_get(sp->modelnum);
6079         vector  global_path_point;
6080         vertex  v, prev_vertex;
6081
6082         if ( pm->ship_bay == NULL )
6083                 return;
6084
6085         for ( i = 0; i < pm->ship_bay->num_paths; i++ ) {
6086                 mp = &pm->paths[pm->ship_bay->paths[i]];
6087
6088                 for ( j = 0; j < mp->nverts; j++ ) {
6089                         vm_vec_unrotate(&global_path_point, &mp->verts[j].pos, &objp->orient);
6090                         vm_vec_add2(&global_path_point, &objp->pos);
6091                         g3_rotate_vertex(&v, &global_path_point);
6092                         color = 255 - j*50;
6093                         if ( color < 50 ) 
6094                                 color = 100;
6095                         gr_set_color(0, color, 0);
6096
6097                         if ( j == mp->nverts-1 ) {
6098                                 gr_set_color(255, 0, 0);
6099                         }
6100
6101                         g3_draw_sphere( &v, 1.5f);
6102
6103                         if ( j > 0 )
6104                                 g3_draw_line(&v, &prev_vertex);
6105
6106                         prev_vertex = v;
6107         
6108                 }
6109         }
6110 }
6111
6112 // debug function to show all path points associated with an object
6113 void render_all_subsys_paths(object *objp)
6114 {
6115         int             i,j,color;
6116         ship            *sp = &Ships[objp->instance];
6117         polymodel       *pm;
6118         model_path      *mp;
6119
6120         pm = model_get(sp->modelnum);
6121         vector  global_path_point;
6122         vertex  v, prev_vertex;
6123
6124         if ( pm->ship_bay == NULL )
6125                 return;
6126
6127         for ( i = 0; i < pm->n_paths; i++ ) {
6128                 mp = &pm->paths[i];
6129                 for ( j = 0; j < mp->nverts; j++ ) {
6130                         vm_vec_unrotate(&global_path_point, &mp->verts[j].pos, &objp->orient);
6131                         vm_vec_add2(&global_path_point, &objp->pos);
6132                         g3_rotate_vertex(&v, &global_path_point);
6133                         color = 255 - j*50;
6134                         if ( color < 50 ) 
6135                                 color = 100;
6136                         gr_set_color(0, color, 0);
6137
6138                         if ( j == mp->nverts-1 ) {
6139                                 gr_set_color(255, 0, 0);
6140                         }
6141
6142                         g3_draw_sphere( &v, 1.5f);
6143
6144                         if ( j > 0 )
6145                                 g3_draw_line(&v, &prev_vertex);
6146
6147                         prev_vertex = v;
6148                 }
6149         }
6150 }
6151
6152 void render_path_points(object *objp)
6153 {
6154         ship            *shipp = &Ships[objp->instance];
6155         ai_info *aip = &Ai_info[shipp->ai_index];
6156         object  *dobjp;
6157         polymodel       *pm;
6158
6159         render_all_subsys_paths(objp);
6160         render_all_ship_bay_paths(objp);
6161
6162         if (aip->goal_objnum < 0)
6163                 return;
6164
6165         dobjp = &Objects[aip->goal_objnum];
6166         pm = model_get(Ships[dobjp->instance].modelnum);
6167         vector  dock_point, global_dock_point;
6168         vertex  v;
6169
6170         ship_model_start(&Objects[aip->goal_objnum]);
6171         if (pm->n_docks) {
6172                 dock_point = pm->docking_bays[0].pnt[0];
6173                 model_find_world_point(&global_dock_point, &dock_point, Ships[dobjp->instance].modelnum, 0, &dobjp->orient, &dobjp->pos );
6174                 g3_rotate_vertex(&v, &global_dock_point);
6175                 gr_set_color(255, 255, 255);
6176                 g3_draw_sphere( &v, 1.5f);
6177         }
6178
6179         if (aip->path_start != -1) {
6180                 vertex          prev_vertex;
6181                 pnode                   *pp = &Path_points[aip->path_start];
6182                 int                     num_points = aip->path_length;
6183                 int                     i;
6184
6185                 for (i=0; i<num_points; i++) {
6186                         vertex  v0;
6187
6188                         g3_rotate_vertex( &v0, &pp->pos );
6189
6190                         gr_set_color(0, 128, 96);
6191                         if (i != 0)
6192                                 g3_draw_line(&v0, &prev_vertex);
6193
6194                         if (pp-Path_points == aip->path_cur)
6195                                 gr_set_color(255,255,0);
6196                         
6197                         g3_draw_sphere( &v0, 4.5f);
6198
6199                         //      Connect all the turrets that can fire upon this point to this point.
6200 /*                      if (0) { //pp->path_index != -1) {
6201                                 model_path      *pmp;
6202                                 mp_vert         *pmpv;
6203
6204                                 get_base_path_info(pp->path_index, aip->goal_objnum, &pmp, &pmpv);
6205
6206                                 if (pmpv->nturrets) {
6207                                         for (int j = 0; j<pmpv->nturrets; j++) {
6208                                                 vertex  v1;
6209                                                 vector  turret_pos;
6210                                                 ship_subsys     *ssp;
6211
6212                                                 ssp = ship_get_indexed_subsys(&Ships[Objects[aip->goal_objnum].instance], pmpv->turret_ids[j]);
6213
6214 model_find_world_point(&turret_pos, &ssp->system_info->pnt, Ships[dobjp->instance].modelnum, 0, &dobjp->orient, &dobjp->pos );
6215         
6216                                                 g3_rotate_vertex(&v1, &turret_pos);
6217                                                 gr_set_color(255, 255, 0);
6218                                                 g3_draw_line(&v0, &v1);
6219                                                 g3_draw_sphere( &v1, 1.5f);
6220                                         }
6221                                 }
6222                         } */
6223
6224                         prev_vertex = v0;
6225
6226                         pp++;
6227                 }
6228         }
6229
6230         ship_model_stop(&Objects[aip->goal_objnum]);
6231 }
6232
6233 // Return the distance that the current AI weapon will travel
6234 float ai_get_weapon_dist(ship_weapon *swp)
6235 {
6236         int     bank_num, weapon_num;
6237
6238         bank_num = swp->current_primary_bank;
6239         weapon_num = swp->primary_bank_weapons[bank_num];
6240
6241         //      If weapon_num is illegal, return a reasonable value.  A valid weapon
6242         //      will get selected when this ship tries to fire.
6243         if (weapon_num == -1) {
6244                 // Int3();
6245                 return 1000.0f;
6246         }
6247
6248         return Weapon_info[weapon_num].max_speed * Weapon_info[weapon_num].lifetime;
6249 }
6250
6251 float ai_get_weapon_speed(ship_weapon *swp)
6252 {
6253         int     bank_num, weapon_num;
6254
6255         bank_num = swp->current_primary_bank;
6256         if (bank_num < 0)
6257                 return 100.0f;
6258
6259         weapon_num = swp->primary_bank_weapons[bank_num];
6260
6261         if (weapon_num == -1) {
6262                 //Int3();
6263                 return 100.0f;
6264         }
6265
6266         return Weapon_info[weapon_num].max_speed;
6267 }
6268
6269 //      Compute the predicted position of a ship to be fired upon from a turret.
6270 //      This is based on position of firing gun, enemy object, weapon speed and skill level constraints.
6271 //      Return value in *predicted_enemy_pos.
6272 //      Also, stuff globals G_predicted_pos, G_collision_time and G_fire_pos.
6273 //      *pobjp          object firing the weapon
6274 //      *eobjp          object being fired upon
6275 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)
6276 {
6277         ship    *shipp = &Ships[pobjp->instance];
6278         float   range_time;
6279
6280         //weapon_speed = ai_get_weapon_speed(&shipp->weapons);
6281
6282         if (weapon_speed < 1.0f)
6283                 weapon_speed = 1.0f;
6284
6285         range_time = 2.0f;
6286
6287         //      Make it take longer for enemies to get player's allies in range based on skill level.
6288         if (Ships[pobjp->instance].team != Ships[Player_obj->instance].team)
6289                 range_time += In_range_time[Game_skill_level];
6290
6291         //nprintf(("AI", "time enemy in range = %7.3f\n", aip->time_enemy_in_range));
6292
6293         if (time_enemy_in_range < range_time) {
6294                 float   dist;
6295
6296                 dist = vm_vec_dist_quick(&pobjp->pos, enemy_pos);
6297                 vm_vec_scale_add(predicted_enemy_pos, enemy_pos, enemy_vel, time_enemy_in_range * dist/weapon_speed);
6298         } else {
6299                 float   collision_time, scale;
6300                 vector  rand_vec;
6301                 ai_info *aip = &Ai_info[shipp->ai_index];
6302
6303                 collision_time = compute_collision_time(enemy_pos, enemy_vel, gun_pos, weapon_speed);
6304
6305                 if (collision_time == 0.0f){
6306                         collision_time = 100.0f;
6307                 }
6308
6309                 vm_vec_scale_add(predicted_enemy_pos, enemy_pos, enemy_vel, collision_time);
6310                 if (time_enemy_in_range > 2*range_time){
6311                         scale = (1.0f - aip->ai_accuracy) * 4.0f;
6312                 } else {
6313                         scale = (1.0f - aip->ai_accuracy) * 4.0f * (1.0f + 4.0f * (1.0f - time_enemy_in_range/(2*range_time)));
6314                 }               
6315
6316                 static_randvec(((pobjp-Objects) ^ (Missiontime >> 16)) & 7, &rand_vec);
6317
6318                 vm_vec_scale_add2(predicted_enemy_pos, &rand_vec, scale);
6319                 G_collision_time = collision_time;
6320                 G_fire_pos = *gun_pos;
6321         }
6322
6323         G_predicted_pos = *predicted_enemy_pos;
6324 }
6325
6326 //      Compute the predicted position of a ship to be fired upon.
6327 //      This is based on current position of firing object, enemy object, relative position of gun on firing object,
6328 //      weapon speed and skill level constraints.
6329 //      Return value in *predicted_enemy_pos.
6330 //      Also, stuff globals G_predicted_pos, G_collision_time and G_fire_pos.
6331 void set_predicted_enemy_pos(vector *predicted_enemy_pos, object *pobjp, object *eobjp, ai_info *aip)
6332 {
6333         float   weapon_speed, range_time;
6334         ship    *shipp = &Ships[pobjp->instance];
6335
6336         weapon_speed = ai_get_weapon_speed(&shipp->weapons);
6337         weapon_speed = max(weapon_speed, 1.0f);         // set not less than 1
6338
6339         range_time = 2.0f;
6340
6341         //      Make it take longer for enemies to get player's allies in range based on skill level.
6342         // but don't bias team v. team missions
6343         if ( !((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_TEAM)) ) {
6344                 if (Ships[pobjp->instance].team != Ships[Player_obj->instance].team) {
6345                         range_time += In_range_time[Game_skill_level];
6346                 }
6347         }
6348         //nprintf(("AI", "time enemy in range = %7.3f\n", aip->time_enemy_in_range));
6349
6350         if (aip->time_enemy_in_range < range_time) {
6351                 float   dist;
6352
6353                 dist = vm_vec_dist_quick(&pobjp->pos, &eobjp->pos);
6354                 vm_vec_scale_add(predicted_enemy_pos, &eobjp->pos, &eobjp->phys_info.vel, aip->time_enemy_in_range * dist/weapon_speed);
6355         } else {
6356                 float   collision_time;
6357                 vector  gun_pos, pnt;
6358                 polymodel *po = model_get( Ship_info[shipp->ship_info_index].modelnum );
6359
6360                 //      Compute position of gun in absolute space and use that as fire position.
6361                 if(po->gun_banks != NULL){
6362                         pnt = po->gun_banks[0].pnt[0];
6363                 } else {
6364                         pnt = Objects[shipp->objnum].pos;
6365                 }
6366                 vm_vec_unrotate(&gun_pos, &pnt, &pobjp->orient);
6367                 vm_vec_add2(&gun_pos, &pobjp->pos);
6368
6369                 collision_time = compute_collision_time(&eobjp->pos, &eobjp->phys_info.vel, &gun_pos, weapon_speed);
6370
6371                 if (collision_time == 0.0f) {
6372                         collision_time = 100.0f;
6373                 }
6374
6375                 vm_vec_scale_add(predicted_enemy_pos, &eobjp->pos, &eobjp->phys_info.vel, collision_time);
6376
6377                 // set globals
6378                 G_collision_time = collision_time;
6379                 G_fire_pos = gun_pos;
6380         }
6381
6382         // Now add error terms (1) regular aim (2) EMP (3) stealth
6383         float scale = 0.0f;
6384         vector rand_vec;
6385
6386         // regular skill level error in aim
6387         if (aip->time_enemy_in_range > 2*range_time) {
6388                 scale = (1.0f - aip->ai_accuracy) * 4.0f;
6389         } else {
6390                 scale = (1.0f - aip->ai_accuracy) * 4.0f * (1.0f + 4.0f * (1.0f - aip->time_enemy_in_range/(2*range_time)));
6391         }
6392
6393         // if this ship is under the effect of an EMP blast, throw his aim off a bit
6394         if (shipp->emp_intensity > 0.0f) {
6395                 // never go lower than 1/2 of the EMP effect max, otherwise things aren't noticeable
6396                 scale += (MAX_EMP_INACCURACY * (shipp->emp_intensity < 0.5f ? 0.5f : shipp->emp_intensity));
6397                 mprintf(("AI miss scale factor (EMP) %f\n",scale));
6398         }
6399
6400         // if stealthy ship, throw his aim off, more when farther away and when dot is small
6401         if ( aip->ai_flags & AIF_STEALTH_PURSIUT ) {
6402                 float dist = vm_vec_dist_quick(&pobjp->pos, &eobjp->pos);
6403                 vector temp;
6404                 vm_vec_sub(&temp, &eobjp->pos, &pobjp->pos);
6405                 vm_vec_normalize_quick(&temp);
6406                 float dot = vm_vec_dotprod(&temp, &pobjp->orient.v.fvec);
6407                 float st_err = 3.0f * (1.4f - dot) * (1.0f + dist / (get_skill_stealth_dist_scaler() * STEALTH_MAX_VIEW_DIST)) * (1 - aip->ai_accuracy);
6408                 scale += st_err;
6409                 // mprintf(("error term: %.1f, total %.1f, dot %.3f\n", st_err, scale, dot));
6410         }
6411
6412         // get a random vector that changes slowly over time (1x / sec)
6413         static_randvec(((pobjp-Objects) ^ (Missiontime >> 16)) & 7, &rand_vec);
6414
6415         vm_vec_scale_add2(predicted_enemy_pos, &rand_vec, scale);
6416
6417         // set global
6418         G_predicted_pos = *predicted_enemy_pos;
6419 }
6420
6421 //      Handler of submode for Chase.  Go into a continuous turn for awhile.
6422 void ai_chase_ct()
6423 {
6424         vector          tvec;
6425         ship_info       *sip;
6426         ai_info         *aip;
6427
6428         SDL_assert(Ships[Pl_objp->instance].ship_info_index >= 0);
6429         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6430         SDL_assert(Ships[Pl_objp->instance].ai_index >= 0);
6431         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
6432
6433         //      Make a continuous turn towards any combination of possibly negated
6434         // up and right vectors.
6435         tvec = Pl_objp->pos;
6436
6437         if (aip->submode_parm0 & 0x01)
6438                 vm_vec_add2(&tvec, &Pl_objp->orient.v.rvec);
6439         if (aip->submode_parm0 & 0x02)
6440                 vm_vec_sub2(&tvec, &Pl_objp->orient.v.rvec);
6441         if (aip->submode_parm0 & 0x04)
6442                 vm_vec_add2(&tvec, &Pl_objp->orient.v.uvec);
6443         if (aip->submode_parm0 & 0x08)
6444                 vm_vec_sub2(&tvec, &Pl_objp->orient.v.uvec);
6445
6446         //      Detect degenerate cases that cause tvec to be same as player pos.
6447         if (vm_vec_dist_quick(&tvec, &Pl_objp->pos) < 0.1f) {
6448                 aip->submode_parm0 &= 0x05;
6449                 if (aip->submode_parm0 == 0)
6450                         aip->submode_parm0 = 1;
6451                 vm_vec_add2(&tvec, &Pl_objp->orient.v.rvec);
6452         }
6453
6454         ai_turn_towards_vector(&tvec, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6455         accelerate_ship(aip, 1.0f);
6456 }
6457
6458 //      ATTACK submode handler for chase mode.
6459 void ai_chase_eb(ai_info *aip, ship_info *sip, vector *predicted_enemy_pos, float dist_to_enemy)
6460 {
6461         vector  _pep;
6462         float           dot_to_enemy, dot_from_enemy;
6463
6464         compute_dots(Pl_objp, En_objp, &dot_to_enemy, &dot_from_enemy);
6465
6466         //      If we're trying to slow down to get behind, then point to turn towards is different.
6467         _pep = *predicted_enemy_pos;
6468         if ((dot_to_enemy > dot_from_enemy + 0.1f) || (dot_to_enemy > 0.9f))
6469                 vm_vec_scale_add(&_pep, &Pl_objp->pos, &En_objp->orient.v.fvec, 100.0f);
6470
6471         ai_turn_towards_vector(&_pep, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6472
6473         accelerate_ship(aip, 0.0f);
6474 }
6475
6476 //      Return time until weapon_objp might hit ship_objp.
6477 //      Assumes ship_objp is not moving.
6478 //      Returns negative time if not going to hit.
6479 //      This is a very approximate function, but is pretty fast.
6480 float ai_endangered_time(object *ship_objp, object *weapon_objp)
6481 {
6482         float           to_dot, from_dot, dist;
6483
6484         dist = compute_dots(ship_objp, weapon_objp, &to_dot, &from_dot);
6485
6486         //      Note, this is bogus.  It assumes only the weapon is moving.
6487         //      Only proceed if weapon sort of pointing at object and object pointing towards or away from weapon
6488         //      (Ie, if object moving at right angle to weapon, just continue for now...)
6489         if (weapon_objp->phys_info.speed < 1.0f)
6490                 return dist + 1.0f;
6491         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))
6492                 return dist / weapon_objp->phys_info.speed;
6493         else
6494                 return -1.0f;
6495 }
6496
6497 //      Return time until danger weapon could hit this ai object.
6498 //      Return negative time if not endangered.
6499 float ai_endangered_by_weapon(ai_info *aip)
6500 {
6501         object  *weapon_objp;
6502
6503         if (aip->danger_weapon_objnum == -1) {
6504                 return -1.0f;
6505         }
6506
6507         weapon_objp = &Objects[aip->danger_weapon_objnum];
6508
6509         if (weapon_objp->signature != aip->danger_weapon_signature) {
6510                 aip->danger_weapon_objnum = -1;
6511                 return -1.0f;
6512         }
6513
6514         return ai_endangered_time(&Objects[Ships[aip->shipnum].objnum], weapon_objp);
6515 }
6516
6517 //      Return true if this ship is near full strength.
6518 int ai_near_full_strength(object *objp, ship_info *sip)
6519 {
6520         return (objp->hull_strength/sip->initial_hull_strength > 0.9f) || (get_shield_strength(objp)/sip->shields > 0.8f);
6521 }
6522                                 
6523 //      Set acceleration while in attack mode.
6524 void attack_set_accel(ai_info *aip, float dist_to_enemy, float dot_to_enemy, float dot_from_enemy)
6525 {
6526         float   speed_ratio;
6527
6528         if (En_objp->phys_info.speed > 1.0f)
6529                 speed_ratio = Pl_objp->phys_info.speed/En_objp->phys_info.speed;
6530         else
6531                 speed_ratio = 5.0f;
6532
6533         //      Sometimes, told to attack slowly.  Allows to get in more hits.
6534         if (aip->ai_flags & AIF_ATTACK_SLOWLY) {
6535                 if ((dist_to_enemy > 200.0f) && (dist_to_enemy < 800.0f)) {
6536                         if ((dot_from_enemy < 0.9f) || ai_near_full_strength(Pl_objp, &Ship_info[Ships[Pl_objp->instance].ship_info_index])) {
6537                                 //nprintf(("AI", " slowly "));
6538                                 accelerate_ship(aip, max(1.0f - (dist_to_enemy-200.0f)/600.0f, 0.1f));
6539                                 return;
6540                         }
6541                 } else
6542                         aip->ai_flags &= ~AIF_ATTACK_SLOWLY;
6543         }
6544
6545         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) {
6546                 //nprintf(("AI", "1"));
6547                 if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
6548                         if (dist_to_enemy > 800.0f) {
6549                                 if (!( Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
6550                                         float percent_left;
6551                                         ship    *shipp;
6552                                         ship_info *sip;
6553
6554                                         shipp = &Ships[Pl_objp->instance];
6555                                         sip = &Ship_info[shipp->ship_info_index];
6556
6557                                         if (sip->afterburner_fuel_capacity > 0.0f) {
6558                                                 percent_left = 100.0f * shipp->afterburner_fuel / sip->afterburner_fuel_capacity;
6559                                                 if (percent_left > 30.0f + ((Pl_objp-Objects) & 0x0f)) {
6560                                                         afterburners_start(Pl_objp);
6561                                                         aip->afterburner_stop_time = Missiontime + F1_0 + static_rand(Pl_objp-Objects)/4;
6562                                                 }
6563                                         }
6564                                 }
6565                         }
6566                 }
6567
6568                 accelerate_ship(aip, 1.0f);
6569         } else if ((Missiontime - aip->last_hit_time > F1_0*7)
6570                 && (En_objp->phys_info.speed < 10.0f) 
6571                 && (dist_to_enemy > 25.0f) 
6572                 && (dot_to_enemy > 0.8f)
6573                 && (dot_from_enemy < 0.8f)) {
6574                 accelerate_ship(aip, 0.0f);             //      No one attacking us, so don't need to move.
6575         } else if ((dot_from_enemy < 0.25f) && (dot_to_enemy > 0.5f)) {
6576                 set_accel_for_target_speed(Pl_objp, En_objp->phys_info.speed);
6577         } else if (Pl_objp->phys_info.speed < 15.0f) {
6578                 accelerate_ship(aip, 1.0f);
6579         } else if (Pl_objp->phys_info.speed > En_objp->phys_info.speed - 1.0f) {
6580                 if (dot_from_enemy > 0.75f)
6581                         accelerate_ship(aip, 1.0f);
6582                 else
6583                         set_accel_for_target_speed(Pl_objp, En_objp->phys_info.speed*0.75f + 3.0f);
6584         } else {
6585                 change_acceleration(aip, 0.5f);
6586         }
6587 }
6588
6589 //      Pl_objp (aip) tries to get behind En_objp.
6590 //      New on 2/21/98: If this ship can move backwards and slide, maybe do that to get behind.
6591 void get_behind_ship(ai_info *aip, ship_info *sip, float dist_to_enemy)
6592 {
6593         vector  new_pos;
6594         float           dot;
6595         vector  vec_from_enemy;
6596
6597         vm_vec_normalized_dir(&vec_from_enemy, &Pl_objp->pos, &En_objp->pos);
6598
6599         vm_vec_scale_add(&new_pos, &En_objp->pos, &En_objp->orient.v.fvec, -100.0f);            //      Pick point 100 units behind.
6600         ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6601
6602         dot = vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.fvec);
6603
6604         if (dot > 0.25f) {
6605                 accelerate_ship(aip, 1.0f);
6606         } else {
6607                 accelerate_ship(aip, (dot + 1.0f)/2.0f);
6608         }
6609 }
6610
6611 int avoid_player(object *objp, vector *goal_pos)
6612 {
6613         maybe_avoid_player(Pl_objp, goal_pos);
6614         ai_info *aip = &Ai_info[Ships[objp->instance].ai_index];
6615
6616         if (aip->ai_flags & AIF_AVOIDING_SMALL_SHIP) {
6617                 ship_info *sip = &Ship_info[Ships[objp->instance].ship_info_index];
6618
6619                 if (aip->ai_flags & AIF_AVOIDING_SMALL_SHIP) {
6620                         ai_turn_towards_vector(&aip->avoid_goal_point, objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6621                         accelerate_ship(aip, 0.5f);
6622                         return 1;
6623                 }
6624         }
6625
6626         return 0;
6627 }
6628
6629 //      Determine if a cylinder of width radius from p0 to p1 will collide with big_objp.
6630 //      If so, stuff *collision_point.
6631 int will_collide_pp(vector *p0, vector *p1, float radius, object *big_objp, vector *collision_point)
6632 {
6633         mc_info mc;
6634
6635         mc.model_num = Ships[big_objp->instance].modelnum;              // Fill in the model to check
6636         mc.orient = &big_objp->orient;                  // The object's orient
6637         mc.pos = &big_objp->pos;                                        // The object's position
6638         mc.p0 = p0;                                                                             // Point 1 of ray to check
6639         mc.p1 = p1;
6640         mc.flags = MC_CHECK_MODEL | MC_CHECK_SPHERELINE | MC_SUBMODEL;                                  // flags
6641
6642         mc.radius = radius;
6643
6644         // Only check the 2nd lowest hull object
6645         polymodel *pm = model_get(Ships[big_objp->instance].modelnum);
6646         mc.submodel_num = pm->detail[0]; //pm->submodel->num_details-2];
6647         model_collide(&mc);
6648
6649         if (mc.num_hits)
6650                 *collision_point = mc.hit_point_world;
6651
6652         return mc.num_hits;
6653 }
6654
6655 //      Return true/false if *objp will collide with *big_objp
6656 //      Stuff distance in *distance to collision point if *objp will collide with *big_objp within delta_time seconds.
6657 //      Global collision point stuffed in *collision_point
6658 int will_collide_with_big_ship(object *objp, vector *goal_point, object *big_objp, vector *collision_point, float delta_time)
6659 {
6660         float           radius;
6661         vector  end_pos;
6662
6663         radius = big_objp->radius + delta_time * objp->phys_info.speed;
6664
6665         if (vm_vec_dist_quick(&big_objp->pos, &objp->pos) > radius) {
6666                 return 0;
6667         }
6668
6669         if (goal_point == NULL) {
6670                 vm_vec_scale_add(&end_pos, &objp->pos, &objp->phys_info.vel, delta_time);                                       // Point 2 of ray to check
6671         } else {
6672                 end_pos = *goal_point;
6673         }
6674
6675         return will_collide_pp(&objp->pos, &end_pos, objp->radius, big_objp, collision_point);
6676 }
6677
6678 //      Return true if *objp is expected to collide with a large ship.
6679 //      Stuff global collision point in *collision_point.
6680 //      If *goal_point is not NULL, use that as the point towards which *objp will be flying.  Don't use *objp velocity
6681 //      *ignore_objp will typically be the target this ship is pursuing, either to attack or guard.  We don't want to avoid it.
6682 int will_collide_with_big_ship_all(object *objp, object *ignore_objp, vector *goal_point, vector *collision_point, float *distance, float delta_time)
6683 {
6684         ship_obj        *so;
6685         object  *big_objp;
6686         int             collision_obj_index = -1;
6687         float           min_dist = 999999.9f;
6688
6689         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
6690                 big_objp = &Objects[so->objnum];
6691
6692                 if (big_objp == ignore_objp)
6693                         continue;
6694
6695                 if (Ship_info[Ships[big_objp->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
6696                         vector  cur_collision_point;
6697                         float           cur_dist;
6698
6699                         if (will_collide_with_big_ship(objp, goal_point, big_objp, &cur_collision_point, delta_time)) {
6700
6701                                 cur_dist = vm_vec_dist(&cur_collision_point, &objp->pos);
6702
6703                                 if (cur_dist < min_dist) {
6704                                         min_dist = cur_dist;
6705                                         *collision_point = cur_collision_point;
6706                                         collision_obj_index = OBJ_INDEX(big_objp);
6707                                 }
6708                         }
6709                 }
6710         }
6711
6712         *distance = min_dist;
6713         return collision_obj_index;
6714
6715 }
6716
6717 typedef struct {
6718         float           dist;
6719         int             collide;
6720         vector  pos;
6721 } sgoal;
6722
6723 //int will_collide_pp(vector *p0, vector *p1, float radius, object *big_objp, vector *collision_point)
6724 //      Pick a point for *objp to fly towards to avoid a collision with *big_objp at *collision_point
6725 //      Return result in *avoid_pos
6726 void mabs_pick_goal_point(object *objp, object *big_objp, vector *collision_point, vector *avoid_pos)
6727 {
6728         matrix  mat1;
6729         sgoal           goals[4];
6730         vector  v2b;
6731
6732         vm_vec_normalized_dir(&v2b, collision_point, &objp->pos);
6733         vm_vector_2_matrix(&mat1, &v2b, NULL, NULL);
6734
6735         int     found = 0;
6736
6737         //      Try various scales, in 0.5f, 0.75f, 1.0f, 1.25f.
6738         //      First try 0.5f to see if we can find a point that near the center of the target ship, which presumably
6739         //      means less of a turn.
6740         //      Try going as far as 1.25f * radius.
6741         float   s;
6742         for (s=0.5f; s<1.3f; s += 0.25f) {
6743                 int     i;
6744                 for (i=0; i<4; i++) {
6745                         vector p = big_objp->pos;
6746                         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
6747                         float kr = big_objp->radius*s + objp->radius * ((OBJ_INDEX(objp) % 4) ^ 2)/4;
6748                         if (i&1)
6749                                 ku = -ku;
6750                         if (i&2)
6751                                 kr = -kr;
6752                         vm_vec_scale_add2(&p, &mat1.v.uvec, ku);
6753                         vm_vec_scale_add2(&p, &mat1.v.rvec, kr);
6754                         goals[i].pos = p;
6755                         goals[i].dist = vm_vec_dist_quick(&objp->pos, &p);
6756                         goals[i].collide = will_collide_pp(&objp->pos, &p, objp->radius, big_objp, collision_point);
6757                         if (!goals[i].collide)
6758                                 found = 1;
6759                 }
6760
6761                 //      If we found a point that doesn't collide, find the nearest one and make that the *avoid_pos.
6762                 if (found) {
6763                         float   min_dist = 9999999.9f;
6764                         int     min_index = -1;
6765
6766                         for (i=0; i<4; i++) {
6767                                 if (!goals[i].collide && (goals[i].dist < min_dist)) {
6768                                         min_dist = goals[i].dist;
6769                                         min_index = i;
6770                                 }
6771                         }
6772
6773                         SDL_assert(i != -1);
6774                         if (i != -1) {
6775                                 *avoid_pos = goals[min_index].pos;
6776                                 return;
6777                         }
6778                 }
6779         }
6780
6781         //      Drat.  We tried and tried and could not find a point that did not cause a collision.
6782         //      Get this dump pilot far away from the problem ship.
6783         vector  away_vec;
6784         vm_vec_normalized_dir(&away_vec, &objp->pos, collision_point);
6785         vm_vec_scale_add(avoid_pos, &objp->pos, &away_vec, big_objp->radius*1.5f);
6786
6787 }
6788
6789 //      Return true if a large ship is being ignored.
6790 int maybe_avoid_big_ship(object *objp, object *ignore_objp, ai_info *aip, vector *goal_point, float delta_time)
6791 {
6792         if (timestamp_elapsed(aip->avoid_check_timestamp)) {
6793                 float           distance;
6794                 vector  collision_point;
6795                 int             ship_num;
6796                 if ((ship_num = will_collide_with_big_ship_all(Pl_objp, ignore_objp, goal_point, &collision_point, &distance, delta_time)) != -1) {
6797                         aip->ai_flags |= AIF_AVOIDING_BIG_SHIP;
6798                         mabs_pick_goal_point(objp, &Objects[ship_num], &collision_point, &aip->avoid_goal_point);
6799                         float dist = vm_vec_dist_quick(&aip->avoid_goal_point, &objp->pos);
6800                         aip->avoid_check_timestamp = timestamp(2000 + min(1000, (int) (dist * 2.0f)));  //      Delay until check again is based on distance to avoid point.
6801                         aip->avoid_ship_num = ship_num;
6802                 } else {
6803                         aip->ai_flags &= ~AIF_AVOIDING_BIG_SHIP;
6804                         aip->ai_flags &= ~AIF_AVOIDING_SMALL_SHIP;
6805                         aip->avoid_ship_num = -1;
6806                         aip->avoid_check_timestamp = timestamp(1500);
6807                 }
6808         }
6809         
6810         if (aip->ai_flags & AIF_AVOIDING_BIG_SHIP) {
6811                 ship_info *sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6812
6813                 vector  v2g;
6814
6815                 ai_turn_towards_vector(&aip->avoid_goal_point, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6816                 vm_vec_normalized_dir(&v2g, &aip->avoid_goal_point, &Pl_objp->pos);
6817                 float dot = vm_vec_dot(&objp->orient.v.fvec, &v2g);
6818                 float d2 = (1.0f + dot) * (1.0f + dot);
6819                 accelerate_ship(aip, d2/4.0f);
6820                 return 1;
6821         }
6822
6823         return 0;
6824 }
6825
6826 //      Set desired right vector for ships flying towards another ship.
6827 //      Since this is governed only by vector to target, it causes ships to align bank and look less chaotic.
6828 void compute_desired_rvec(vector *rvec, vector *goal_pos, vector *cur_pos)
6829 {
6830         vector  v2e;
6831
6832         vm_vec_normalized_dir(&v2e, goal_pos, cur_pos);
6833         rvec->xyz.x = v2e.xyz.z;
6834         rvec->xyz.y = 0.0f;
6835         rvec->xyz.z = -v2e.xyz.x;
6836         if (vm_vec_mag_squared(rvec) < 0.001f)
6837                 rvec->xyz.y = 1.0f;
6838 }
6839
6840 // Handler for stealth find submode of Chase.
6841 void ai_stealth_find()
6842 {
6843         ai_info         *aip;
6844         ship_info       *sip;
6845
6846         vector new_pos, vec_to_enemy;
6847         float dist_to_enemy, dot_to_enemy, dot_from_enemy;
6848
6849         SDL_assert(Ships[Pl_objp->instance].ship_info_index >= 0);
6850         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6851         SDL_assert(Ships[Pl_objp->instance].ai_index >= 0);
6852         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
6853
6854         // get time since last seen
6855         int delta_time = (timestamp() - aip->stealth_last_visible_stamp);
6856
6857         // if delta_time is really big, i'm real confused, start sweep
6858         if (delta_time > 10000) {
6859                 aip->submode_parm0 = SM_SF_BAIL;
6860         }
6861
6862         // guestimate new position
6863         vm_vec_scale_add(&new_pos, &aip->stealth_last_pos, &aip->stealth_velocity, (delta_time * 0.001f));
6864
6865         // if I think he's behind me, go to the goal point
6866         if ( aip->submode_parm0 == SM_SF_BEHIND ) {
6867                 new_pos = aip->goal_point;
6868         }
6869
6870         // check for collision with big ships
6871         if (maybe_avoid_big_ship(Pl_objp, En_objp, aip, &new_pos, 10.0f)) {
6872                 // reset ai submode to chase
6873                 return;
6874         }
6875
6876         // if dist is near max and dot is close to 1, accel, afterburn
6877         vm_vec_sub(&vec_to_enemy, &new_pos, &Pl_objp->pos);
6878         dist_to_enemy = vm_vec_normalize_quick(&vec_to_enemy);
6879         dot_to_enemy = vm_vec_dotprod(&vec_to_enemy, &Pl_objp->orient.v.fvec);
6880
6881         // 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
6882         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) ) {
6883                 // do turn around)
6884                 vm_vec_scale_add(&aip->goal_point, &Pl_objp->pos, &Pl_objp->orient.v.fvec, -300.0f);
6885                 aip->submode_parm0 = SM_SF_BEHIND;
6886                 vm_vec_sub(&vec_to_enemy, &new_pos, &Pl_objp->pos);
6887                 dist_to_enemy = vm_vec_normalize_quick(&vec_to_enemy);
6888                 dot_to_enemy = vm_vec_dotprod(&vec_to_enemy, &Pl_objp->orient.v.fvec);
6889         }
6890
6891         if ( (dist_to_enemy > get_skill_stealth_dist_scaler()*STEALTH_MAX_VIEW_DIST) && (dot_to_enemy > 0.94f) ) {              // 20 degree half angle
6892                 // accelerate ship
6893                 accelerate_ship(aip, 1.0f);
6894
6895                 // engage afterburner
6896                 if (!( Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
6897                         if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
6898                                 afterburners_start(Pl_objp);
6899                                 aip->afterburner_stop_time = Missiontime + 3*F1_0/2;
6900                         }
6901                 }
6902
6903                 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6904                 return;
6905         }
6906
6907         //      If enemy more than 500 meters away, all ships flying there will tend to match bank.
6908         //      They do this by using their vector to their target to compute their right vector and causing ai_turn_towards_vector
6909         //      to interpolate a matrix rather than just a vector.
6910         if (dist_to_enemy > 500.0f) {
6911                 vector  rvec;
6912                 compute_desired_rvec(&rvec, &new_pos, &Pl_objp->pos);
6913                 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0, &rvec);
6914         } else {
6915                 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6916         }
6917
6918         dot_from_enemy = -vm_vec_dotprod(&vec_to_enemy, &En_objp->orient.v.fvec);
6919
6920         attack_set_accel(aip, dist_to_enemy, dot_to_enemy, dot_from_enemy);
6921 }
6922
6923 // -----------------------------------------------------------------------------
6924 // try to find stealth ship by sweeping an area
6925 void ai_stealth_sweep()
6926 {
6927         ai_info         *aip;
6928         ship_info       *sip;
6929
6930         SDL_assert(Ships[Pl_objp->instance].ship_info_index >= 0);
6931         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6932         SDL_assert(Ships[Pl_objp->instance].ai_index >= 0);
6933         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
6934
6935         vector goal_pt;
6936         vector forward, right, up;
6937         int lost_time;
6938
6939         // time since stealth last seen
6940         lost_time = (timestamp() - aip->stealth_last_visible_stamp);
6941
6942         // determine which pt to fly to in sweep by keeping track of parm0
6943         if (aip->submode_parm0 == SM_SS_SET_GOAL) {
6944
6945                 // don't make goal pt more than 2k from current pos
6946                 vm_vec_scale_add(&goal_pt, &aip->stealth_last_pos, &aip->stealth_velocity, (0.001f * lost_time));
6947
6948                 // make box size based on speed of stealth and expected time to intercept (keep box in range 200-500)
6949                 float box_size = vm_vec_mag_quick(&aip->stealth_velocity) * (0.001f * lost_time);
6950                 box_size = min(200.0f, box_size);
6951                 box_size = max(500.0f, box_size);
6952                 aip->stealth_sweep_box_size = box_size;
6953
6954                 aip->goal_point = goal_pt;
6955                 aip->submode_parm0 = SM_SS_BOX0;
6956         }
6957
6958         // GET UP, RIGHT, FORWARD FOR BOX based on stealth ship's velocity
6959         // if velocity changes in stealth mode, then ship is *seen*, and falls out of sweep mode
6960         // if stealth has no velocity make a velocity
6961         if ( vm_vec_mag_quick(&aip->stealth_velocity) < 1 ) {
6962                 vm_vec_rand_vec_quick(&aip->stealth_velocity);
6963         }
6964
6965         // get "right" vector for box
6966         vm_vec_crossprod(&right, &aip->stealth_velocity, &vmd_y_vector);
6967
6968         if ( vm_vec_mag_quick(&right) < 0.01 ) {
6969                 vm_vec_crossprod(&right, &aip->stealth_velocity, &vmd_z_vector);
6970         }
6971
6972         vm_vec_normalize_quick(&right);
6973
6974         // get forward for box
6975         vm_vec_copy_normalize_quick(&forward, &aip->stealth_velocity);
6976
6977         // get "up" for box
6978         vm_vec_crossprod(&up, &forward, &right);
6979         
6980         // lost far away ahead (do box)
6981         switch(aip->submode_parm0) {
6982         case SM_SS_BOX0:
6983                 goal_pt = aip->goal_point;
6984                 break;
6985
6986         // pt1 -U +R
6987         case SM_SS_LR:
6988                 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, -aip->stealth_sweep_box_size);
6989                 vm_vec_scale_add2(&goal_pt, &right, aip->stealth_sweep_box_size);
6990                 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
6991                 break;
6992
6993         // pt2 +U -R
6994         case SM_SS_UL:
6995                 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, aip->stealth_sweep_box_size);
6996                 vm_vec_scale_add2(&goal_pt, &right, -aip->stealth_sweep_box_size);
6997                 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
6998                 break;
6999
7000         // pt3 back
7001         case SM_SS_BOX1:
7002                 goal_pt = aip->goal_point;
7003                 break;
7004
7005         // pt4 +U +R
7006         case SM_SS_UR:
7007                 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, aip->stealth_sweep_box_size);
7008                 vm_vec_scale_add2(&goal_pt, &right, aip->stealth_sweep_box_size);
7009                 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
7010                 break;
7011
7012         // pt5 -U -R
7013         case SM_SS_LL:
7014                 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, -aip->stealth_sweep_box_size);
7015                 vm_vec_scale_add2(&goal_pt, &right, -aip->stealth_sweep_box_size);
7016                 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
7017                 break;
7018
7019         // pt6 back
7020         case SM_SS_BOX2:
7021                 goal_pt = aip->goal_point;
7022                 break;
7023
7024         default:
7025                 Int3();
7026
7027         }
7028
7029         // when close to goal_pt, update next goal pt
7030         float dist_to_goal = vm_vec_dist(&goal_pt, &Pl_objp->pos);
7031         if (dist_to_goal < 15) {
7032                 aip->submode_parm0++;
7033         }
7034
7035         // check for collision with big ship
7036         if (maybe_avoid_big_ship(Pl_objp, En_objp, aip, &goal_pt, 10.0f)) {
7037                 // skip to the next pt on box
7038                 aip->submode_parm0++;
7039                 return;
7040         }
7041
7042         ai_turn_towards_vector(&goal_pt, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
7043
7044         float dot = 1.0f;
7045         if (dist_to_goal < 100) {
7046                 vector vec_to_goal;
7047                 vm_vec_normalized_dir(&vec_to_goal, &goal_pt, &Pl_objp->pos);
7048                 dot = vm_vec_dotprod(&vec_to_goal, &Pl_objp->orient.v.fvec);
7049         }
7050
7051         accelerate_ship(aip, 0.8f*dot);
7052 }
7053
7054 //      ATTACK submode handler for chase mode.
7055 void ai_chase_attack(ai_info *aip, ship_info *sip, vector *predicted_enemy_pos, float dist_to_enemy)
7056 {
7057         int             start_bank;
7058         float           dot_to_enemy, dot_from_enemy; //, time_to_hit;
7059         float           bank_override = 0.0f;
7060
7061         if (avoid_player(Pl_objp, predicted_enemy_pos))
7062                 return;
7063
7064         compute_dots(Pl_objp, En_objp, &dot_to_enemy, &dot_from_enemy);
7065
7066         polymodel *po = model_get( sip->modelnum );
7067
7068         vector  *rel_pos;
7069         float           scale;
7070         vector  randvec;
7071         vector  new_pos;
7072
7073         start_bank = Ships[aip->shipnum].weapons.current_primary_bank;
7074         if (po->n_guns && start_bank != -1 ) {
7075                 rel_pos = &po->gun_banks[start_bank].pnt[0];
7076         } else
7077                 rel_pos = NULL;
7078
7079         //      If ship moving slowly relative to its size, then don't attack its center point.
7080         //      How far from center we attack is based on speed, size and distance to enemy
7081         if (En_objp->radius > En_objp->phys_info.speed) {
7082                 static_randvec(Pl_objp-Objects, &randvec);
7083                 scale = dist_to_enemy/(dist_to_enemy + En_objp->radius) * En_objp->radius;
7084                 scale *= 0.5f * En_objp->radius/(En_objp->phys_info.speed + En_objp->radius);   // scale downward by 1/2 to 1/4
7085                 vm_vec_scale_add(&new_pos, predicted_enemy_pos, &randvec, scale);
7086         } else
7087                 new_pos = *predicted_enemy_pos;
7088
7089         if (dist_to_enemy < 250.0f) {
7090                 if (dot_from_enemy > 0.7f) {
7091                         bank_override = Pl_objp->phys_info.speed;
7092                 }
7093         }
7094
7095         //      If enemy more than 500 meters away, all ships flying there will tend to match bank.
7096         //      They do this by using their vector to their target to compute their right vector and causing ai_turn_towards_vector
7097         //      to interpolate a matrix rather than just a vector.
7098         if (dist_to_enemy > 500.0f) {
7099                 vector  rvec;
7100                 compute_desired_rvec(&rvec, predicted_enemy_pos, &Pl_objp->pos);
7101                 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, rel_pos, bank_override, 0, &rvec);
7102         } else {
7103                 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, rel_pos, bank_override, 0);
7104         }
7105
7106         attack_set_accel(aip, dist_to_enemy, dot_to_enemy, dot_from_enemy);
7107 }
7108
7109 //      EVADE_SQUIGGLE submode handler for chase mode.
7110 //      Changed by MK on 5/5/97.
7111 //      Used to evade towards a point off the right or up vector.
7112 //      Now, evade straight away to try to get far away.
7113 //      The squiggling should protect against laser fire.
7114 void ai_chase_es(ai_info *aip, ship_info *sip)
7115 {
7116         vector  tvec;
7117         fix             timeslice;
7118         fix             scale;
7119         float           bank_override = 0.0f;
7120
7121         tvec = Pl_objp->pos;
7122
7123         timeslice = (Missiontime >> 16) & 0x0f;
7124         scale = ((Missiontime >> 16) & 0x0f) << 14;
7125
7126         if (timeslice & 0x01)
7127                 vm_vec_scale_add2(&tvec, &Pl_objp->orient.v.rvec, f2fl(scale ^ 0x10000));
7128         if (timeslice & 0x02)
7129                 vm_vec_scale_sub2(&tvec, &Pl_objp->orient.v.rvec, f2fl(scale));
7130         if (timeslice & 0x04)
7131                 vm_vec_scale_add2(&tvec, &Pl_objp->orient.v.uvec, f2fl(scale ^ 0x10000));
7132         if (timeslice & 0x08)
7133                 vm_vec_scale_sub2(&tvec, &Pl_objp->orient.v.uvec, f2fl(scale));
7134
7135         while (vm_vec_dist_quick(&tvec, &Pl_objp->pos) < 0.1f) {
7136                 tvec.xyz.x += frand();
7137                 tvec.xyz.y += frand();
7138         }
7139
7140         bank_override = Pl_objp->phys_info.speed;
7141
7142         ai_turn_towards_vector(&tvec, Pl_objp, flFrametime/2, sip->srotation_time, NULL, NULL, bank_override, 0);
7143         accelerate_ship(aip, 1.0f);
7144 }
7145
7146 //      Trying to get away from opponent.
7147 void ai_chase_ga(ai_info *aip, ship_info *sip)
7148 {
7149         //      If not near end of this submode, evade squiggly.  If near end, just fly straight for a bit
7150         vector  tvec;
7151         float           bank_override;
7152         vector  vec_from_enemy;
7153
7154         if (En_objp != NULL) {
7155                 vm_vec_normalized_dir(&vec_from_enemy, &Pl_objp->pos, &En_objp->pos);
7156         } else
7157                 vec_from_enemy = Pl_objp->orient.v.fvec;
7158
7159         static_randvec(Missiontime >> 15, &tvec);
7160         vm_vec_scale(&tvec, 100.0f);
7161         vm_vec_scale_add2(&tvec, &vec_from_enemy, 300.0f);
7162         vm_vec_add2(&tvec, &Pl_objp->pos);
7163
7164         bank_override = Pl_objp->phys_info.speed;
7165
7166         ai_turn_towards_vector(&tvec, Pl_objp, flFrametime/2, sip->srotation_time, NULL, NULL, bank_override, 0);
7167
7168         accelerate_ship(aip, 2.0f);
7169
7170         if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
7171                 if (!(Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
7172                         float percent_left = 100.0f * Ships[Pl_objp->instance].afterburner_fuel / sip->afterburner_fuel_capacity;
7173                         if (percent_left > 30.0f + ((Pl_objp-Objects) & 0x0f)) {
7174                                 afterburners_start(Pl_objp);
7175                                 aip->afterburner_stop_time = Missiontime + 3*F1_0/2;
7176                         }
7177                         afterburners_start(Pl_objp);
7178                         aip->afterburner_stop_time = Missiontime + 3*F1_0/2;
7179                 }
7180         }
7181
7182 }
7183
7184 //      Make object *objp attack subsystem with ID = subnum.
7185 //      Return true if found a subsystem to attack, else return false.
7186 //      Note, can fail if subsystem exists, but has no hits.
7187 int ai_set_attack_subsystem(object *objp, int subnum)
7188 {
7189         ship                    *shipp, *attacker_shipp;
7190         ai_info         *aip;
7191         ship_subsys     *ssp;
7192         object          *attacked_objp;
7193
7194         SDL_assert(objp->type == OBJ_SHIP);
7195         SDL_assert(objp->instance >= 0);
7196
7197         attacker_shipp = &Ships[objp->instance];
7198         SDL_assert(attacker_shipp->ai_index >= 0);
7199
7200         aip = &Ai_info[attacker_shipp->ai_index];
7201
7202         // MWA -- 2/27/98.  Due to AL's changes, target_objnum is now not always valid (at least sometimes
7203         // in terms of goals).  So, bail if we don't have a valid target.
7204         if ( aip->target_objnum == -1 )
7205                 return 0;
7206
7207         attacked_objp = &Objects[aip->target_objnum];
7208         shipp = &Ships[attacked_objp->instance];                //  need to get our target's ship pointer!!!
7209
7210         ssp = ship_get_indexed_subsys(shipp, subnum, &objp->pos);
7211         if (ssp == NULL)
7212                 return 0;
7213
7214         set_targeted_subsys(aip, ssp, aip->target_objnum);
7215         
7216         if (aip->ignore_objnum == aip->target_objnum)
7217                 aip->ignore_objnum = UNUSED_OBJNUM;
7218
7219         // -- Done at caller in ai_process_mission_orders -- attacked_objp->flags |= OF_PROTECTED;
7220
7221         ai_set_goal_maybe_abort_dock(objp, aip);
7222         aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);
7223
7224         return 1;
7225 }
7226
7227 void ai_set_guard_vec(object *objp, object *guard_objp)
7228 {
7229         ai_info *aip;
7230         float   radius;
7231
7232         aip = &Ai_info[Ships[objp->instance].ai_index];
7233
7234         //      Handle case of bogus call in which ship is told to guard self.
7235         SDL_assert(objp != guard_objp);
7236         if (objp == guard_objp) {
7237                 vm_vec_rand_vec_quick(&aip->guard_vec);
7238                 vm_vec_scale(&aip->guard_vec, 100.0f);
7239                 return;
7240         }
7241
7242         // check if guard_objp is BIG
7243         radius = 5.0f * (objp->radius + guard_objp->radius) + 50.0f;
7244         if (radius > 300.0f) {
7245                 radius = guard_objp->radius * 1.25f;
7246         }
7247
7248         vm_vec_sub(&aip->guard_vec, &objp->pos, &guard_objp->pos);
7249
7250         if (vm_vec_mag(&aip->guard_vec) > 3.0f*radius) {
7251                 //      Far away, don't just use vector to object, causes clustering of guard ships.
7252                 vector  tvec, rvec;
7253                 float   mag;
7254                 mag = vm_vec_copy_normalize(&tvec, &aip->guard_vec);
7255                 vm_vec_rand_vec_quick(&rvec);                   
7256                 vm_vec_scale_add2(&tvec, &rvec, 0.5f);
7257                 vm_vec_copy_scale(&aip->guard_vec, &tvec, mag);
7258         }
7259
7260         vm_vec_normalize_quick(&aip->guard_vec);
7261         vm_vec_scale(&aip->guard_vec, radius);
7262 }
7263
7264 //      Make object *objp guard object *other_objp.
7265 //      To be called from the goals code.
7266 void ai_set_guard_wing(object *objp, int wingnum)
7267 {
7268         ship            *shipp;
7269         ai_info *aip;
7270         int             leader_objnum, leader_shipnum;
7271
7272         SDL_assert(wingnum >= 0);
7273
7274         SDL_assert(objp->type == OBJ_SHIP);
7275         SDL_assert(objp->instance >= 0);
7276
7277         // shouldn't set the ai mode for the player
7278         if ( objp == Player_obj ) {
7279                 return;
7280         }
7281
7282         shipp = &Ships[objp->instance];
7283
7284         SDL_assert(shipp->ai_index >= 0);
7285
7286         aip = &Ai_info[shipp->ai_index];
7287         force_avoid_player_check(objp, aip);
7288
7289         ai_set_goal_maybe_abort_dock(objp, aip);
7290         aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);
7291
7292         //      This function is called whenever a guarded ship is destroyed, so this code
7293         //      prevents a ship from trying to guard a non-existent wing.
7294         if (Wings[wingnum].current_count < 1) {
7295                 aip->guard_objnum = -1;
7296                 aip->guard_wingnum = -1;
7297                 aip->mode = AIM_NONE;
7298         } else {
7299                 leader_shipnum = Wings[wingnum].ship_index[0];
7300                 leader_objnum = Ships[leader_shipnum].objnum;
7301
7302                 SDL_assert((leader_objnum >= 0) && (leader_objnum < MAX_OBJECTS));
7303                 //SDL_assert(leader_objnum != objp-Objects);    //      Don't allow ships to guard themselves.
7304                 if (leader_objnum == OBJ_INDEX(objp)) {
7305                         //Int3();       //      Seems illegal, but let's clean up.  Get MikeK.
7306                         return;
7307                 }
7308
7309                 aip->guard_wingnum = wingnum;
7310                 aip->guard_objnum = leader_objnum;
7311                 aip->guard_signature = Objects[leader_objnum].signature;
7312                 aip->mode = AIM_GUARD;
7313                 aip->submode = AIS_GUARD_STATIC;
7314
7315                 ai_set_guard_vec(objp, &Objects[leader_objnum]);
7316         }
7317 }
7318
7319 //      Make object *objp guard object *other_objp.
7320 //      To be called from the goals code.
7321 void ai_set_evade_object(object *objp, object *other_objp)
7322 {
7323         ship            *shipp;
7324         ai_info *aip;
7325         int             other_objnum;
7326
7327         SDL_assert(objp->type == OBJ_SHIP);
7328         SDL_assert(objp->instance >= 0);
7329
7330         shipp = &Ships[objp->instance];
7331
7332         SDL_assert(shipp->ai_index >= 0);
7333
7334         aip = &Ai_info[shipp->ai_index];
7335
7336         other_objnum = OBJ_INDEX(other_objp);
7337         SDL_assert(other_objnum >= 0);
7338
7339         SDL_assert(other_objnum != Ships[aip->shipnum].objnum); //      make sure not targeting self
7340         aip->target_objnum = other_objnum;
7341
7342         aip->mode = AIM_EVADE;
7343 }
7344
7345 //      Make objp guard other_objp
7346 //      If other_objp is a member of a wing, objp will guard that whole wing
7347 //      UNLESS objp is also a member of the wing!
7348 void ai_set_guard_object(object *objp, object *other_objp)
7349 {
7350         ship            *shipp;
7351         ai_info *aip;
7352         int             other_objnum;
7353
7354         SDL_assert(objp->type == OBJ_SHIP);
7355         SDL_assert(objp->instance >= 0);
7356         SDL_assert(objp != other_objp);
7357
7358         shipp = &Ships[objp->instance];
7359
7360         SDL_assert(shipp->ai_index >= 0);
7361
7362         aip = &Ai_info[shipp->ai_index];
7363         aip->avoid_check_timestamp = timestamp(1);
7364
7365         //      If ship to guard is in a wing, guard that whole wing.
7366         ai_info *other_aip = &Ai_info[Ships[other_objp->instance].ai_index];
7367         if ((other_aip->wing != -1) && (other_aip->wing != aip->wing)) {
7368                 ai_set_guard_wing(objp, Ai_info[Ships[other_objp->instance].ai_index].wing);
7369         } else {
7370
7371                 other_objnum = other_objp-Objects;
7372
7373                 aip->guard_objnum = other_objnum;
7374                 aip->guard_signature = other_objp->signature;
7375                 aip->guard_wingnum = -1;
7376
7377                 aip->mode = AIM_GUARD;
7378                 aip->submode = AIS_GUARD_STATIC;
7379
7380                 SDL_assert(other_objnum >= 0);  //      Hmm, bogus object and we need its position for guard_vec.
7381
7382                 // vm_vec_sub(&aip->guard_vec, &objp->pos, &Objects[other_objnum].pos);
7383                 ai_set_guard_vec(objp, &Objects[other_objnum]);
7384
7385                 ai_set_goal_maybe_abort_dock(objp, aip);
7386                 aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);
7387         }
7388 }
7389
7390 //      Update the aspect_locked_time field based on whether enemy is in view cone.
7391 //      Also set/clear AIF_SEEK_LOCK.
7392 void update_aspect_lock_information(ai_info *aip, vector *vec_to_enemy, float dist_to_enemy, float enemy_radius)
7393 {
7394         float   dot_to_enemy;
7395         int     num_weapon_types;
7396         int     weapon_id_list[MAX_WEAPON_TYPES], weapon_bank_list[MAX_WEAPON_TYPES];
7397         ship    *shipp;
7398         ship_weapon     *swp;
7399         weapon_info     *wip;
7400
7401         shipp = &Ships[aip->shipnum];
7402         swp = &shipp->weapons;
7403
7404         // AL 3-7-98: This probably should never happen, but check to ensure that current_secondary_bank is valid
7405         if ( (swp->current_secondary_bank < 0) || (swp->current_secondary_bank > swp->num_secondary_banks) ) {
7406                 return;
7407         }
7408
7409         num_weapon_types = get_available_secondary_weapons(Pl_objp, weapon_id_list, weapon_bank_list);
7410
7411         wip = &Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]];
7412
7413         if (num_weapon_types && (wip->wi_flags & WIF_HOMING_ASPECT)) {
7414                 if (dist_to_enemy > 300.0f - min(enemy_radius, 100.0f))
7415                         aip->ai_flags |= AIF_SEEK_LOCK;
7416                 else
7417                         aip->ai_flags &= ~AIF_SEEK_LOCK;
7418
7419                 //      Update locking information for aspect seeking missiles.
7420                 aip->current_target_is_locked = 0;
7421                 dot_to_enemy = vm_vec_dot(vec_to_enemy, &Pl_objp->orient.v.fvec);
7422
7423                 float   needed_dot = 0.9f - 0.5f * enemy_radius/(dist_to_enemy + enemy_radius); //      Replaced MIN_TRACKABLE_DOT with 0.9f
7424                 if (dot_to_enemy > needed_dot) {
7425                         aip->aspect_locked_time += flFrametime;
7426                         // nprintf(("AI", "+ Lock time = %7.3f\n", aip->aspect_locked_time));
7427                         if (aip->aspect_locked_time >= wip->min_lock_time) {
7428                                 aip->aspect_locked_time = wip->min_lock_time;
7429                                 aip->current_target_is_locked = 1;
7430                         }
7431                 } else {
7432                         aip->aspect_locked_time -= flFrametime*2;
7433                         // nprintf(("AI", "- Lock time = %7.3f\n", aip->aspect_locked_time));
7434                         if (aip->aspect_locked_time < 0.0f)
7435                                 aip->aspect_locked_time = 0.0f;
7436                 }
7437                 //nprintf(("AI", "dot = %7.3f, time = %7.3f\n", dot_to_enemy, aip->aspect_locked_time));
7438         
7439         } else {
7440                 aip->current_target_is_locked = 0;
7441                 aip->aspect_locked_time = 0.0f; // Used to be this, why?: wip->min_lock_time;
7442                 aip->ai_flags &= ~AIF_SEEK_LOCK;
7443         }
7444
7445 }
7446
7447 //      We're in chase mode and we've recently collided with our target.
7448 //      Fly away from it!
7449 void ai_chase_fly_away(object *objp, ai_info *aip)
7450 {
7451         int     abort_flag = 0;
7452
7453         if (aip->ai_flags & AIF_TARGET_COLLISION) {
7454                 aip->ai_flags &= ~AIF_TARGET_COLLISION; //      Don't process this hit again next frame.
7455                 aip->submode = SM_FLY_AWAY;                                     //      Focus on avoiding target
7456                 aip->submode_start_time = Missiontime;
7457         }
7458
7459         if ((aip->target_objnum == -1) || (Objects[aip->target_objnum].signature != aip->target_signature)) {
7460                 abort_flag = 1;
7461         }
7462
7463         if (abort_flag || (Missiontime > aip->submode_start_time + F1_0)) {
7464                 aip->last_attack_time = Missiontime;
7465                 aip->submode = SM_ATTACK;
7466                 aip->submode_start_time = Missiontime;
7467         } else {
7468                 vector  v2e;
7469                 float           dot;
7470
7471                 vm_vec_normalized_dir(&v2e, &Objects[aip->target_objnum].pos, &objp->pos);
7472
7473                 dot = vm_vec_dot(&objp->orient.v.fvec, &v2e);
7474                 if (dot < 0.0f)
7475                         accelerate_ship(aip, 1.0f);
7476                 else
7477                         accelerate_ship(aip, 1.0f - dot);
7478                 turn_away_from_point(objp, &Objects[aip->target_objnum].pos, 0.0f);
7479         }
7480 }
7481
7482 //      Return bank index of favored secondary weapon.
7483 //      Return -1 if nothing favored.
7484 //      "favored" means SEXPs have specified the weapon as being good to fire at en_objp.
7485 int has_preferred_secondary(object *objp, object *en_objp, ship_weapon *swp)
7486 {
7487 // int is_preferred_weapon(int weapon_num, object *firer_objp, object *target_objp)
7488         int     i;
7489
7490         for (i=0; i<swp->num_secondary_banks; i++) {
7491                 if (swp->secondary_bank_capacity[i] > 0) {
7492                         if (swp->secondary_bank_ammo[i] > 0) {
7493                                 if (is_preferred_weapon(swp->secondary_bank_weapons[i], objp, en_objp) != -1){
7494                                         return i;
7495                                 }
7496                         }
7497                 }
7498         }
7499
7500         return -1;
7501 }
7502
7503 //      Choose which secondary weapon to fire.
7504 //      Note, this is not like ai_select_secondary_weapon().  "choose" means make a choice.
7505 //      "select" means execute an order.  Get it?
7506 //      This function calls ai_select_secondary_weapon() with the characteristics it should search for.
7507 void ai_choose_secondary_weapon(object *objp, ai_info *aip, object *en_objp)
7508 {
7509         float                   subsystem_strength = 0.0f;
7510         int                     is_big_ship, priority1, priority2;
7511         ship_weapon     *swp;
7512         ship_info       *esip;
7513
7514         if ( en_objp->type == OBJ_SHIP ) {
7515                 esip = &Ship_info[Ships[en_objp->instance].ship_info_index];
7516         } else {
7517                 esip = NULL;
7518         }
7519
7520         swp = &Ships[objp->instance].weapons;
7521
7522         // AL 3-5-98: do a quick out if the ship has no secondaries
7523         if ( swp->num_secondary_banks <= 0 ) {
7524                 swp->current_secondary_bank = -1;
7525                 return;
7526         }
7527
7528         int preferred_secondary = has_preferred_secondary(objp, en_objp, swp);
7529
7530         if (preferred_secondary != -1) {
7531                 if (swp->current_secondary_bank != preferred_secondary) {
7532                         aip->current_target_is_locked = 0;
7533                         aip->aspect_locked_time = 0.0f;
7534                         swp->current_secondary_bank = preferred_secondary;
7535                 }
7536                 //nprintf(("AI", "Favored secondary = %s\n", Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]].name));
7537                 aip->ai_flags |= AIF_UNLOAD_SECONDARIES;
7538         } else {
7539                 aip->ai_flags &= ~AIF_UNLOAD_SECONDARIES;
7540                 if (aip->targeted_subsys) {
7541                         subsystem_strength = aip->targeted_subsys->current_hits;
7542                 }
7543
7544                 if ( esip ) {
7545                         is_big_ship = esip->flags & (SIF_HUGE_SHIP | SIF_BIG_SHIP);
7546                 } else {
7547                         is_big_ship=0;
7548                 }
7549
7550                 if (is_big_ship) {
7551                         priority1 = WIF_HUGE;
7552                         priority2 = WIF_HOMING;
7553                 } else if ( (esip != NULL) && (esip->flags & SIF_BOMBER) ) {
7554                         priority1 = WIF_BOMBER_PLUS;
7555                         priority2 = WIF_HOMING;
7556                 } else if (subsystem_strength > 100.0f) {
7557                         priority1 = WIF_PUNCTURE;
7558                         priority2 = WIF_HOMING;
7559                 } else {
7560                         priority1 = WIF_HOMING;
7561                         priority2 = 0;
7562                 }
7563                 
7564                 ai_select_secondary_weapon(objp, swp, priority1, priority2);
7565         }
7566
7567         // nprintf(("AI", "Frame %i: Chose secondary %s\n", Framecount, Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]].name));
7568 }
7569
7570 //      Return time, in seconds, at which this ship can next fire its current secondary weapon.
7571 float set_secondary_fire_delay(ai_info *aip, ship *shipp, weapon_info *swip)
7572 {
7573         float t = swip->fire_wait;              //      Base delay for this weapon.
7574         if (shipp->team == Player_ship->team) {
7575                 //      On player's team, _lower_ skill level = faster firing
7576                 t = t * (Game_skill_level+2) / (NUM_SKILL_LEVELS);
7577         } else {                //      Not on player's team, higher skill level = faster firing
7578                 t = t * (NUM_SKILL_LEVELS - Game_skill_level+2) / (NUM_SKILL_LEVELS);
7579         }
7580
7581         t += (Num_ai_classes - aip->ai_class + 1) * 0.5f;
7582         t *= frand_range(0.8f, 1.2f);
7583
7584         //      For the missiles that fire fairly quickly, occasionally add an additional substantial delay.
7585         if (t < 5.0f)
7586                 if (frand() < 0.5f)
7587                         t = t * 2.0f + 2.0f;
7588
7589         return t;
7590 }
7591
7592
7593 void ai_chase_big_approach_set_goal(vector *goal_pos, object *attack_objp, object *target_objp, float *accel)
7594 {
7595         float dist_to_goal;
7596
7597         // head straight toward him and maybe circle later
7598         vm_vec_avg(goal_pos, &attack_objp->pos, &target_objp->pos);
7599
7600         // get distance to goal
7601         dist_to_goal = vm_vec_dist(goal_pos, &attack_objp->pos);
7602         
7603         // set accel
7604         if (dist_to_goal > 400.0f) {
7605                 *accel = 1.0f;
7606         } else {
7607                 *accel = dist_to_goal/400.0f;
7608         }
7609 }
7610
7611 void ai_chase_big_circle_set_goal(vector *goal_pos, object *attack_objp, object *target_objp, float *accel)
7612 {
7613         get_tangent_point(goal_pos, attack_objp, &target_objp->pos, attack_objp->radius + target_objp->radius + 100.0f);
7614
7615         *accel = 1.0f;
7616 }
7617
7618 // get the current and desired horizontal separations between target
7619 void ai_chase_big_get_separations(object *attack_objp, object *target_objp, vector *horz_vec_to_target, float *desired_separation, float *cur_separation)
7620 {
7621         float temp, r_target, r_attacker;
7622         float perp_dist;
7623         vector vec_to_target;
7624         polymodel *pm;
7625
7626         // get parameters of ships (as cylinders - radius and height)
7627         // get radius of attacker (for rotations about forward)
7628         pm = model_get(Ships[attack_objp->instance].modelnum);
7629         temp = max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7630         r_attacker = max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7631         r_attacker = max(temp, r_attacker);
7632
7633         // get radius of target (for rotations about forward)
7634         pm = model_get(Ships[attack_objp->instance].modelnum);
7635         temp = max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7636         r_target = max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7637         r_target = max(temp, r_target);
7638
7639         // find separation between cylinders [if parallel]
7640         vm_vec_sub(&vec_to_target, &attack_objp->pos, &target_objp->pos);
7641
7642         // find the distance between centers along forward direction of ships
7643         perp_dist = vm_vec_dotprod(&vec_to_target, &target_objp->orient.v.fvec);
7644
7645         // subtract off perp component to get "horizontal" separation vector between cylinders [ASSUMING parallel]
7646         vm_vec_scale_add(horz_vec_to_target, &vec_to_target, &target_objp->orient.v.fvec, -perp_dist);
7647         *cur_separation = vm_vec_mag_quick(horz_vec_to_target);
7648
7649         // choose "optimal" separation of 1000 + r_target + r_attacker
7650         *desired_separation = 1000 + r_target + r_attacker;
7651 }
7652
7653 void ai_chase_big_parallel_set_goal(vector *goal_pos, object *attack_objp, object *target_objp, float *accel)
7654 {
7655         int opposing;
7656         float temp, r_target, r_attacker;
7657         float separation, optimal_separation;
7658         vector  horz_vec_to_target;
7659         polymodel *pm;
7660
7661         // get parameters of ships (as cylinders - radius and height)
7662         // get radius of attacker (for rotations about forward)
7663         pm = model_get(Ships[attack_objp->instance].modelnum);
7664         temp = max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7665         r_attacker = max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7666         r_attacker = max(temp, r_attacker);
7667
7668         // get radius of target (for rotations about forward)
7669         pm = model_get(Ships[attack_objp->instance].modelnum);
7670         temp = max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7671         r_target = max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7672         r_target = max(temp, r_target);
7673
7674         // are we opposing (only when other ship is not moving)
7675         opposing = ( vm_vec_dotprod(&attack_objp->orient.v.fvec, &target_objp->orient.v.fvec) < 0 );
7676
7677         ai_chase_big_get_separations(attack_objp, target_objp, &horz_vec_to_target, &optimal_separation, &separation);
7678
7679         // choose dist (2000) so that we don't bash
7680         float dist = 2000;
7681         if (opposing) {
7682                 dist = - dist;
7683         }
7684
7685         // set the goal pos as dist forward from target along target forward
7686         vm_vec_scale_add(goal_pos, &target_objp->pos, &target_objp->orient.v.fvec, dist);
7687         // then add horizontal separation
7688         vm_vec_scale_add2(goal_pos, &horz_vec_to_target, optimal_separation/separation);
7689
7690         // find the distance between centers along forward direction of ships
7691         vector vec_to_target;
7692         vm_vec_sub(&vec_to_target, &target_objp->pos, &attack_objp->pos);
7693         float perp_dist = vm_vec_dotprod(&vec_to_target, &target_objp->orient.v.fvec);
7694
7695         float match_accel = target_objp->phys_info.vel.xyz.z / Ship_info[Ships[attack_objp->instance].ship_info_index].max_vel.xyz.z;
7696         float length_scale = attack_objp->radius;
7697
7698         // if we're heading toward enemy ship, we want to keep going if we're ahead
7699         if (opposing) {
7700                 perp_dist = -perp_dist;
7701         }
7702
7703         if (perp_dist > 0) {
7704                 // falling behind, so speed up
7705                 *accel = match_accel + (1.0f - match_accel) / length_scale * (perp_dist);
7706         } else {
7707                 // up in front, so slow down
7708                 *accel = match_accel  - match_accel / length_scale * -perp_dist;
7709                 *accel = max(0.0f, *accel);
7710         }
7711
7712 }
7713
7714
7715 //      Return *goal_pos for one cruiser to attack another (big ship).
7716 //      Choose point fairly nearby that is not occupied by another cruiser.
7717 void ai_cruiser_chase_set_goal_pos(vector *goal_pos, object *pl_objp, object *en_objp)
7718 {
7719         ai_info *aip;
7720
7721         aip = &Ai_info[Ships[pl_objp->instance].ai_index];
7722         float accel;
7723
7724         switch (aip->submode) {
7725         case SM_BIG_APPROACH:
7726                 // do approach stuff;
7727                 ai_chase_big_approach_set_goal(goal_pos, pl_objp, en_objp, &accel);
7728                 break;
7729
7730         case SM_BIG_CIRCLE:
7731                 // do circle stuff
7732                 ai_chase_big_circle_set_goal(goal_pos, pl_objp, en_objp, &accel);
7733                 break;
7734
7735         case SM_BIG_PARALLEL:
7736                 // do parallel stuff
7737                 ai_chase_big_parallel_set_goal(goal_pos, pl_objp, en_objp, &accel);
7738                 break;
7739         }
7740 }
7741
7742 int maybe_hack_cruiser_chase_abort()
7743 {
7744         ship                    *shipp = &Ships[Pl_objp->instance];     
7745         ship                    *eshipp = &Ships[En_objp->instance];
7746         ai_info         *aip = &Ai_info[shipp->ai_index];
7747
7748         // mission sm3-08, sathanos chasing collosus
7749         if ( SDL_strcasecmp(Mission_filename, "sm3-08.fs2") == 0 ) {
7750                 if (( SDL_strcasecmp(eshipp->ship_name, "colossus") == 0 ) || ( SDL_strcasecmp(shipp->ship_name, "colossus") == 0 )) {
7751                         // Changed so all big ships attacking the Colossus will not do the chase code.
7752                         // Did this so Beast wouldn't swerve away from Colossus. -- MK, 9/14/99
7753                         //if ( SDL_strcasecmp(shipp->ship_name, "Sathanas") == 0 ) {
7754                                 // do cool hack stuff here
7755                                 ai_clear_ship_goals( aip );
7756                                 aip->mode = AIM_NONE;
7757                                 return 1;
7758                         //}
7759                 }
7760         }
7761
7762         return 0;
7763 }
7764
7765 //      Make a big ship pursue another big ship.
7766 //      (Note, called "ai_cruiser_chase" because we already have ai_chase_big() which means fighter chases big ship.
7767 void ai_cruiser_chase()
7768 {
7769         ship_info       *sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
7770         ship                    *shipp = &Ships[Pl_objp->instance];     
7771         ai_info         *aip = &Ai_info[shipp->ai_index];
7772
7773         if (!(sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
7774                 Int3(); //      Hmm, not a very big ship, how did we get in this function?
7775                 aip->mode = AIM_NONE;
7776                 return;
7777         }
7778
7779         if (En_objp->type != OBJ_SHIP) {
7780                 Int3();
7781                 return;
7782         }
7783
7784         if (En_objp->instance < 0) {
7785                 Int3();
7786                 return;
7787         }
7788
7789         ship                    *eshipp;
7790         ship_info       *esip;
7791
7792         eshipp = &Ships[En_objp->instance];
7793         esip = &Ship_info[eshipp->ship_info_index];
7794
7795         if (!(esip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
7796                 // Int3();      //      Hmm, we're big and we're pursuing something other than a big ship?
7797                 aip->mode = AIM_NONE;
7798                 return;
7799         }
7800
7801         vector  goal_pos;
7802         float turn_time = Ship_info[Ships[Pl_objp->instance].ship_info_index].srotation_time;
7803
7804         // kamikaze - ram and explode
7805         if (aip->ai_flags & AIF_KAMIKAZE) {
7806                 ai_turn_towards_vector(&En_objp->pos, Pl_objp, flFrametime, turn_time, NULL, NULL, 0.0f, 0);
7807                 accelerate_ship(aip, 1.0f);
7808         } 
7809         
7810         // really track down and chase
7811         else {
7812                 // check valid submode
7813                 SDL_assert( (aip->submode == SM_ATTACK) || (aip->submode == SM_BIG_APPROACH) || (aip->submode == SM_BIG_CIRCLE) || (aip->submode == SM_BIG_PARALLEL) );
7814
7815                 // just entering, approach enemy ship
7816                 if (aip->submode == SM_ATTACK) {
7817                         aip->submode = SM_BIG_APPROACH;
7818                 }
7819
7820                 // desired accel
7821                 float accel = 0.0f;
7822                 vector *rvecp = NULL;
7823
7824                 switch (aip->submode) {
7825                 case SM_BIG_APPROACH:
7826                         // do approach stuff;
7827                         ai_chase_big_approach_set_goal(&goal_pos, Pl_objp, En_objp, &accel);
7828                         // maybe set rvec
7829                         break;
7830
7831                 case SM_BIG_CIRCLE:
7832                         // do circle stuff
7833                         ai_chase_big_circle_set_goal(&goal_pos, Pl_objp, En_objp, &accel);
7834                         // maybe set rvec
7835                         break;
7836
7837                 case SM_BIG_PARALLEL:
7838                         // do parallel stuff
7839                         ai_chase_big_parallel_set_goal(&goal_pos, Pl_objp, En_objp, &accel);
7840                         //maybe set rvec
7841                         break;
7842                 }
7843
7844
7845                 // now move as desired
7846                 ai_turn_towards_vector(&goal_pos, Pl_objp, flFrametime, turn_time, NULL, NULL, 0.0f, 0, rvecp);
7847                 accelerate_ship(aip, accel);
7848
7849
7850                 // maybe switch to new mode
7851                 vector vec_to_enemy;
7852                 float dist_to_enemy;
7853                 int moving = (En_objp->phys_info.vel.xyz.z > 0.5f);
7854                 vm_vec_sub(&vec_to_enemy, &En_objp->pos, &Pl_objp->pos);
7855                 dist_to_enemy = vm_vec_mag_quick(&vec_to_enemy);
7856
7857                 switch (aip->submode) {
7858                 case SM_BIG_APPROACH:
7859                         if ( dist_to_enemy < (Pl_objp->radius + En_objp->radius)*1.25f + 200.0f ) {
7860                                 // moving
7861                                 if (moving) {
7862                                         // if within 90 degrees of en forward, go into parallel, otherwise circle
7863                                         if ( vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) > 0 ) {
7864                                                 aip->submode = SM_BIG_PARALLEL;
7865                                         }
7866                                 }
7867
7868                                 // otherwise cirle
7869                                 if ( !maybe_hack_cruiser_chase_abort() ) {
7870                                         aip->submode = SM_BIG_CIRCLE;
7871                                 }
7872                         }
7873                         break;
7874
7875                 case SM_BIG_CIRCLE:
7876                         // moving
7877                         if (moving) {
7878                                 vector temp;
7879                                 float desired_sep, cur_sep;
7880                                 // we're behind the enemy ship
7881                                 if (vm_vec_dotprod(&vec_to_enemy, &En_objp->orient.v.fvec) > 0) {
7882                                         // and we're turning toward the enemy
7883                                         if (vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) > 0) {
7884                                                 // get separation
7885                                                 ai_chase_big_get_separations(Pl_objp, En_objp, &temp, &desired_sep, &cur_sep);
7886                                                 // and the separation is > 0.9 desired
7887                                                 if (cur_sep > 0.9 * desired_sep) {
7888                                                         aip->submode = SM_BIG_PARALLEL;
7889                                                 }
7890                                         }
7891                                 }
7892                         } else {
7893                                 // still
7894                                 vector temp;
7895                                 float desired_sep, cur_sep;
7896                                 // we're behind the enemy ship
7897                                 if (vm_vec_dotprod(&vec_to_enemy, &En_objp->orient.v.fvec) > 0) {
7898                                         // and we're turning toward the enemy
7899                                         if (vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) > 0) {
7900                                                 // get separation
7901                                                 ai_chase_big_get_separations(Pl_objp, En_objp, &temp, &desired_sep, &cur_sep);
7902                                                 //and the separation is [0.9 to 1.1] desired
7903                                                 if ( (cur_sep > 0.9f * desired_sep) ) {
7904                                                         aip->submode = SM_BIG_PARALLEL;
7905                                                 }
7906                                         }
7907                                 }
7908                                 // in front of ship
7909                                 else {
7910                                         // and we're turning toward the enemy
7911                                         if (vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) < 0) {
7912                                                 // get separation
7913                                                 ai_chase_big_get_separations(Pl_objp, En_objp, &temp, &desired_sep, &cur_sep);
7914                                                 //and the separation is [0.9 to 1.1] desired
7915                                                 if ( (cur_sep > 0.9f * desired_sep) ) {
7916                                                         aip->submode = SM_BIG_PARALLEL;
7917                                                 }
7918                                         }
7919                                 }
7920                         }
7921                         break;
7922
7923                 case SM_BIG_PARALLEL:
7924                         // we're opposing
7925                         if ( vm_vec_dotprod(&Pl_objp->orient.v.fvec, &En_objp->orient.v.fvec) < 0 ) {
7926                                 // and the other ship is moving
7927                                 if (moving) {
7928                                         // and we no longer overlap
7929                                         if ( dist_to_enemy > (0.75 * (En_objp->radius + Pl_objp->radius)) ) {
7930                                                 aip->submode = SM_BIG_APPROACH;
7931                                         }
7932                                 }
7933                         }
7934                         break;
7935                 }
7936         }
7937 }
7938
7939 // --------------------------------------------------------------------------
7940 // Make object Pl_objp chase object En_objp
7941 void ai_chase()
7942 {
7943         float                   dist_to_enemy;
7944         float                   dot_to_enemy, dot_from_enemy, real_dot_to_enemy;
7945         vector          player_pos, enemy_pos, predicted_enemy_pos, real_vec_to_enemy, predicted_vec_to_enemy;
7946         ship_info       *sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
7947         ship                    *shipp = &Ships[Pl_objp->instance];
7948         ship_weapon     *swp = &shipp->weapons;
7949         ai_info         *aip = &Ai_info[shipp->ai_index];
7950         int                     enemy_sip_flags;
7951
7952         if (aip->mode != AIM_CHASE) {
7953                 Int3();
7954         }
7955
7956         if (sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
7957                 ai_cruiser_chase();
7958                 return;
7959         }
7960
7961         if (!(sip->flags & (SIF_FIGHTER | SIF_BOMBER | SIF_ESCAPEPOD))) {
7962                 Warning(LOCATION, "Ship %s is not 'small', but is in chase mode.\nSwitching to AI=none.\n", shipp->ship_name);
7963                 aip->mode = AIM_NONE;
7964                 return;
7965         }
7966
7967         //nprintf(("AI", "%7s ", Submode_text[aip->submode]));
7968
7969         if ( En_objp->type == OBJ_SHIP ) {
7970                 enemy_sip_flags = Ship_info[Ships[En_objp->instance].ship_info_index].flags;
7971         } else {
7972                 enemy_sip_flags = 0;
7973         }
7974
7975         if ( enemy_sip_flags > 0 ) {
7976                 if (enemy_sip_flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
7977                         ai_big_chase();
7978                         return;
7979                 }
7980         }
7981
7982         //      If collided with target_objnum last frame, avoid that ship.
7983         //      This should prevent the embarrassing behavior of ships getting stuck on each other
7984         //      as if they were magnetically attracted. -- MK, 11/13/97.
7985         if ((aip->ai_flags & AIF_TARGET_COLLISION) || (aip->submode == SM_FLY_AWAY)) {
7986                 ai_chase_fly_away(Pl_objp, aip);
7987                 return;
7988         }
7989
7990         ai_set_positions(Pl_objp, En_objp, aip, &player_pos, &enemy_pos);
7991         dist_to_enemy = vm_vec_dist_quick(&player_pos, &enemy_pos);
7992         vm_vec_sub(&real_vec_to_enemy, &enemy_pos, &player_pos);
7993
7994         vm_vec_normalize(&real_vec_to_enemy);
7995
7996         real_dot_to_enemy = vm_vec_dot(&real_vec_to_enemy, &Pl_objp->orient.v.fvec);
7997
7998         int is_stealthy_ship = 0;
7999         if ( (enemy_sip_flags > 0) && (enemy_sip_flags & SIF_STEALTH) ) {
8000                 if ( ai_is_stealth_visible(Pl_objp, En_objp) != STEALTH_FULLY_TARGETABLE ) {
8001                         is_stealthy_ship = 1;
8002                 }
8003         }
8004
8005         // Can only acquire lock on a target that isn't hidden from sensors
8006         if ( !(Ships[En_objp->instance].flags & SF_HIDDEN_FROM_SENSORS) && !is_stealthy_ship ) {
8007                 update_aspect_lock_information(aip, &real_vec_to_enemy, dist_to_enemy, En_objp->radius);
8008         } else {
8009                 aip->current_target_is_locked = 0;
8010                 aip->ai_flags &= ~AIF_SEEK_LOCK;
8011         }
8012
8013         //      If seeking lock, try to point directly at ship, else predict position so lasers can hit it.
8014         //      If just acquired target, or target is not in reasonable cone, don't refine believed enemy position.
8015         if ((real_dot_to_enemy < 0.25f) || (aip->target_time < 1.0f) || (aip->ai_flags & AIF_SEEK_LOCK)) {
8016                 predicted_enemy_pos = enemy_pos;
8017         } else {
8018                 //      Set predicted_enemy_pos.
8019                 //      See if attacking a subsystem.
8020                 if (aip->targeted_subsys != NULL) {
8021                         SDL_assert(En_objp->type == OBJ_SHIP);
8022                         ship_info       *esip = &Ship_info[Ships[En_objp->instance].ship_info_index];
8023                         if (get_shield_strength(En_objp)/esip->shields < HULL_DAMAGE_THRESHOLD_PERCENT) {
8024                                 //int   rval;
8025
8026                                 if (aip->targeted_subsys != NULL) {
8027                                         get_subsystem_pos(&enemy_pos, En_objp, aip->targeted_subsys);
8028                                         predicted_enemy_pos = enemy_pos;
8029                                         predicted_vec_to_enemy = real_vec_to_enemy;
8030                                 } else {
8031                                         set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, En_objp, aip);
8032                                         set_target_objnum(aip, -1);
8033                                 }
8034                                 // 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));
8035
8036                         } else {
8037                                 set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, En_objp, aip);
8038                                 // 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));
8039                         }
8040                 } else {
8041                         set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, En_objp, aip);
8042                 }
8043         }
8044
8045         vm_vec_sub(&predicted_vec_to_enemy, &predicted_enemy_pos, &player_pos);
8046
8047         vm_vec_normalize(&predicted_vec_to_enemy);
8048
8049         dot_to_enemy = vm_vec_dot(&Pl_objp->orient.v.fvec, &predicted_vec_to_enemy);
8050         dot_from_enemy= - vm_vec_dot(&En_objp->orient.v.fvec, &real_vec_to_enemy);
8051
8052         //
8053         //      Set turn and acceleration based on submode.
8054         //
8055         switch (aip->submode) {
8056         case SM_CONTINUOUS_TURN:
8057                 ai_chase_ct();
8058                 break;
8059
8060         case SM_STEALTH_FIND:
8061                 ai_stealth_find();
8062                 break;
8063
8064         case SM_STEALTH_SWEEP:
8065                 ai_stealth_sweep();
8066                 break;
8067
8068         case SM_ATTACK:
8069         case SM_SUPER_ATTACK:
8070         case SM_ATTACK_FOREVER:
8071                 if (vm_vec_dist_quick(&Pl_objp->pos, &predicted_enemy_pos) > 100.0f + En_objp->radius * 2.0f) {
8072                         if (maybe_avoid_big_ship(Pl_objp, En_objp, aip, &predicted_enemy_pos, 10.0f))
8073                                 return;
8074                 }
8075
8076                 ai_chase_attack(aip, sip, &predicted_enemy_pos, dist_to_enemy);
8077                 break;
8078
8079         case SM_EVADE_SQUIGGLE:
8080                 ai_chase_es(aip, sip);
8081                 break;
8082
8083         case SM_EVADE_BRAKE:
8084                 ai_chase_eb(aip, sip, &predicted_enemy_pos, dist_to_enemy);
8085                 break;
8086
8087         case SM_EVADE:
8088                 evade_ship();
8089                 break;
8090
8091         case SM_AVOID:
8092                 avoid_ship();
8093                 break;
8094
8095         case SM_GET_BEHIND:
8096                 get_behind_ship(aip, sip, dist_to_enemy);
8097                 break;
8098
8099         case SM_GET_AWAY:               //      Used to get away from opponent to prevent endless circling.
8100                 ai_chase_ga(aip, sip);
8101                 break;
8102
8103         case SM_EVADE_WEAPON:
8104                 evade_weapon();
8105                 break;
8106
8107         default:
8108                 // Int3();
8109                 aip->last_attack_time = Missiontime;
8110                 aip->submode = SM_ATTACK;
8111                 aip->submode_start_time = Missiontime;
8112         }
8113
8114         //
8115         //      Maybe choose a new submode.
8116         //
8117         if ( (aip->submode != SM_AVOID) && (aip->submode != SM_ATTACK_FOREVER) ) {
8118                 //      If a very long time since attacked, attack no matter what!
8119                 if ( (aip->submode != SM_SUPER_ATTACK) && (aip->submode != SM_GET_AWAY) && !(aip->ai_flags & AIF_STEALTH_PURSIUT) ) {
8120                         if (Missiontime - aip->last_attack_time > i2f(6)) {
8121                                 aip->submode = SM_SUPER_ATTACK;
8122                                 aip->submode_start_time = Missiontime;
8123                                 aip->last_attack_time = Missiontime;
8124                         }
8125                 }
8126
8127                 //      If a collision is expected, pull out!
8128                 //      If enemy is pointing away and moving a bit, don't worry about collision detection.
8129                 if ((dot_from_enemy > 0.5f) || (En_objp->phys_info.speed < 10.0f)) {
8130                         if (might_collide_with_ship(Pl_objp, En_objp, dot_to_enemy, dist_to_enemy, 4.0f)) {
8131                                 if ((Missiontime - aip->last_hit_time > F1_0*4) && (dist_to_enemy < Pl_objp->radius*2 + En_objp->radius*2)) {
8132                                         accelerate_ship(aip, -1.0f);
8133                                 } else {
8134                                         aip->submode = SM_AVOID;
8135                                         aip->submode_start_time = Missiontime;
8136                                 }
8137                         }
8138                 }
8139         }
8140
8141         switch (aip->submode) {
8142         case SM_CONTINUOUS_TURN:
8143                 if (Missiontime - aip->submode_start_time > i2f(3)) {
8144                         aip->last_attack_time = Missiontime;
8145                         aip->submode = SM_ATTACK;
8146                         aip->submode_start_time = Missiontime;
8147                 }
8148                 break;
8149
8150         case SM_ATTACK:
8151                 // if taraget is stealth and stealth not visible, then enter stealth find mode
8152                 if ( (aip->ai_flags & AIF_STEALTH_PURSIUT) && (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_INVISIBLE) ) {
8153                         aip->submode = SM_STEALTH_FIND;
8154                         aip->submode_start_time = Missiontime;
8155                         aip->submode_parm0 = SM_SF_AHEAD;
8156                 } 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)) {
8157                         aip->submode = SM_SUPER_ATTACK;
8158                         aip->submode_start_time = Missiontime;
8159                         aip->last_attack_time = Missiontime;
8160                 } else if ((Missiontime - aip->last_hit_target_time > i2f(6)) &&
8161                         (dist_to_enemy < 500.0f) && (dot_to_enemy < 0.2f) &&
8162                         (frand() < (float) Game_skill_level/NUM_SKILL_LEVELS)) {
8163                         aip->submode = SM_GET_AWAY;
8164                         aip->submode_start_time = Missiontime;
8165                         aip->last_hit_target_time = Missiontime;
8166                 } else if ((enemy_sip_flags & SIF_SMALL_SHIP)
8167                         && (dot_to_enemy < dot_from_enemy)
8168                         && (En_objp->phys_info.speed > 15.0f) 
8169                         && (dist_to_enemy < 200.0f) 
8170                         && (dist_to_enemy > 50.0f)
8171                         && (dot_to_enemy < 0.1f)
8172                         && (Missiontime - aip->submode_start_time > i2f(2))) {
8173                         aip->submode = SM_EVADE_BRAKE;
8174                         aip->submode_start_time = Missiontime;
8175                 } else if ((dot_to_enemy > 0.2f) && (dot_from_enemy > -0.2f) && (dot_from_enemy < 0.1f)) {
8176                         aip->submode = SM_GET_BEHIND;
8177                         aip->submode_start_time = Missiontime;
8178                 } 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)) {
8179                         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;
8180                                 aip->submode_start_time = Missiontime;
8181                                 aip->last_hit_target_time = Missiontime;
8182                         } else {
8183                                 aip->submode = SM_EVADE_SQUIGGLE;
8184                                 aip->submode_start_time = Missiontime;
8185                         }
8186                 } else if ((enemy_sip_flags & SIF_SMALL_SHIP) && (Missiontime - aip->submode_start_time > F1_0*2)) {
8187                         if ((dot_to_enemy < 0.8f) && (dot_from_enemy > dot_to_enemy)) {
8188                                 if (frand() > 0.5f) {
8189                                         aip->submode = SM_CONTINUOUS_TURN;
8190                                         aip->submode_parm0 = myrand() & 0x0f;
8191                                         aip->submode_start_time = Missiontime;
8192                                 } else {
8193                                         aip->submode = SM_EVADE;
8194                                         aip->submode_start_time = Missiontime;
8195                                 }
8196                         } else {
8197                                 aip->submode_start_time = Missiontime;
8198                         }
8199                 }
8200
8201                 aip->last_attack_time = Missiontime;
8202
8203                 break;
8204                 
8205         case SM_EVADE_SQUIGGLE:
8206                 if ((Missiontime - aip->submode_start_time > i2f(5)) || (dist_to_enemy > 300.0f)) {
8207                         if ((dist_to_enemy < 100.0f) && (dot_to_enemy < 0.0f) && (dot_from_enemy > 0.5f)) {
8208                                 aip->submode = SM_EVADE_BRAKE;
8209                                 aip->submode_start_time = Missiontime;
8210                         } else {
8211                                 aip->last_attack_time = Missiontime;
8212                                 aip->submode = SM_ATTACK;
8213                                 aip->submode_start_time = Missiontime;
8214                         }
8215                 }
8216                 break;
8217         
8218         case SM_EVADE_BRAKE:
8219                 if ((dist_to_enemy < 15.0f) || (En_objp->phys_info.speed < 10.0f)) {
8220                         aip->submode = SM_AVOID;
8221                         aip->submode_start_time = Missiontime;
8222                 } else if ((dot_to_enemy > 0.9f) || ((dot_from_enemy > 0.9f) && (Missiontime - aip->submode_start_time > i2f(1)))) {
8223                         aip->last_attack_time = Missiontime;
8224                         aip->submode = SM_ATTACK;
8225                         aip->submode_start_time = Missiontime;
8226                 } else if (Missiontime - aip->submode_start_time > i2f(4)) {
8227                         aip->last_attack_time = Missiontime;
8228                         aip->submode = SM_ATTACK;
8229                         aip->submode_start_time = Missiontime;
8230                 }
8231                 break;
8232
8233         case SM_EVADE:
8234                 //      Modified by MK on 5/5/97 to keep trying to regain attack mode.  It's what a human would do.
8235                 if ((dot_to_enemy < 0.2f) && (dot_from_enemy < 0.8f) && (dist_to_enemy < 100.0f) && (En_objp->phys_info.speed > 15.0f)) {
8236                         aip->last_attack_time = Missiontime;
8237                         aip->submode = SM_EVADE_BRAKE;
8238                         aip->submode_start_time = Missiontime;
8239                 } else if (((dot_to_enemy > dot_from_enemy - 0.1f)
8240                         && (Missiontime > aip->submode_start_time + i2f(1)))
8241                         || (dist_to_enemy > 150.0f + 2*(Pl_objp->radius + En_objp->radius))) {
8242                         aip->last_attack_time = Missiontime;
8243                         aip->submode = SM_ATTACK;
8244                         aip->submode_start_time = Missiontime;
8245                 } else if (Missiontime - aip->submode_start_time > i2f(2))
8246                         if (dot_from_enemy > 0.8f) {
8247                                 aip->submode = SM_EVADE_SQUIGGLE;
8248                                 aip->submode_start_time = Missiontime;
8249                         }
8250
8251                 break;
8252
8253         case SM_SUPER_ATTACK:
8254                 // if stealth and invisible, enter stealth find mode
8255                 if ( (aip->ai_flags & AIF_STEALTH_PURSIUT) && (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_INVISIBLE) ) {
8256                         aip->submode = SM_STEALTH_FIND;
8257                         aip->submode_start_time = Missiontime;
8258                         aip->submode_parm0 = SM_SF_AHEAD;
8259                 } 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) )) {
8260                         aip->ai_flags &= ~AIF_ATTACK_SLOWLY;    //      Just in case, clear here.
8261
8262                         switch (myrand() % 5) {
8263                         case 0:
8264                                 aip->submode = SM_CONTINUOUS_TURN;
8265                                 aip->submode_start_time = Missiontime;
8266                                 break;
8267                         case 1:
8268                                 aip->submode_start_time = Missiontime;  //      Stay in super attack mode
8269                                 break;
8270                         case 2:
8271                         case 3:
8272                                 if (frand() < (float) 0.5f * (aip->ai_class + Game_skill_level)/(Num_ai_classes + NUM_SKILL_LEVELS)) {
8273                                         aip->submode = SM_GET_AWAY;
8274                                         aip->submode_start_time = Missiontime;
8275                                 } else {
8276                                         aip->submode = SM_EVADE;
8277                                         aip->submode_start_time = Missiontime;
8278                                 }
8279                                 break;
8280                         case 4:
8281                                 if (dot_from_enemy + (NUM_SKILL_LEVELS - Game_skill_level) * 0.1f > dot_to_enemy) {     //      Less likely to GET_AWAY at lower skill levels.
8282                                         aip->submode = SM_EVADE;
8283                                         aip->submode_start_time = Missiontime;
8284                                 } else {
8285                                         aip->submode = SM_GET_AWAY;
8286                                         aip->submode_start_time = Missiontime;
8287                                 }
8288                                 break;
8289                         default:
8290                                 Int3(); //      Impossible!
8291                         }
8292                 }
8293
8294                 aip->last_attack_time = Missiontime;
8295
8296                 break;
8297
8298         case SM_AVOID:
8299                 if ((dot_to_enemy > -0.2f) && (dist_to_enemy / (dot_to_enemy + 0.3f) < 100.0f)) {
8300                         aip->submode_start_time = Missiontime;
8301                 } else if (Missiontime - aip->submode_start_time > i2f(1)/2) {
8302                         if (might_collide_with_ship(Pl_objp, En_objp, dot_to_enemy, dist_to_enemy, 3.0f)) {
8303                                 aip->submode_start_time = Missiontime;
8304                         } else {
8305                                 aip->submode = SM_GET_BEHIND;
8306                                 aip->submode_start_time = Missiontime;
8307                         }
8308                 }
8309
8310                 break;
8311
8312         case SM_GET_BEHIND:
8313                 if ((dot_from_enemy < -0.7f) || (Missiontime - aip->submode_start_time > i2f(2))) {
8314                         aip->submode = SM_ATTACK;
8315                         aip->submode_start_time = Missiontime;
8316                         aip->last_attack_time = Missiontime;
8317                 }
8318                 break;
8319
8320         case SM_GET_AWAY:
8321                 if (Missiontime - aip->submode_start_time > i2f(2)) {
8322                         float   rand_dist;
8323
8324                         rand_dist = ((Missiontime >> 17) & 0x03) * 100.0f + 200.0f;     //      Some value in 200..500
8325                         if ((Missiontime - aip->submode_start_time > i2f(5)) || (dist_to_enemy > rand_dist) || (dot_from_enemy < 0.4f)) {
8326                                 aip->ai_flags |= AIF_ATTACK_SLOWLY;
8327                                 aip->submode = SM_ATTACK;
8328                                 aip->time_enemy_in_range = 2.0f;                //      Cheat.  Presumably if they were running away from you, they were monitoring you!
8329                                 aip->submode_start_time = Missiontime;
8330                                 aip->last_attack_time = Missiontime;
8331                         }
8332                 }
8333                 break;
8334
8335         case SM_EVADE_WEAPON:
8336                 if (aip->danger_weapon_objnum == -1) {
8337                         aip->submode = SM_ATTACK;
8338                         aip->submode_start_time = Missiontime;
8339                         aip->last_attack_time = Missiontime;
8340                 }
8341                 break;
8342
8343         // Either change to SM_ATTACK or AIM_FIND_STEALTH
8344         case SM_STEALTH_FIND:
8345                 // if time > 5 sec change mode to sweep
8346                 if ( !(aip->ai_flags & AIF_STEALTH_PURSIUT) || (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_VISIBLE) ) {
8347                         aip->submode = SM_ATTACK;
8348                         aip->submode_start_time = Missiontime;
8349                         aip->last_attack_time = Missiontime;
8350                         // sweep if I can't find in 5 sec or bail from find
8351                 } else if ( ((Missiontime - aip->submode_start_time) > i2f(5)) || (aip->submode_parm0 == SM_SF_BAIL) ) {
8352                         // begin sweep mode
8353                         aip->submode = SM_STEALTH_SWEEP;
8354                         aip->submode_start_time = Missiontime;
8355                         aip->last_attack_time = Missiontime;
8356                         aip->submode_parm0 = SM_SS_SET_GOAL;
8357                 }
8358                 break;
8359
8360         case SM_STEALTH_SWEEP:
8361                 if ( !(aip->ai_flags & AIF_STEALTH_PURSIUT) || (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_VISIBLE) ) {
8362                         aip->submode = SM_ATTACK;
8363                         aip->submode_start_time = Missiontime;
8364                         aip->last_attack_time = Missiontime;
8365                 } else if ( (timestamp() - aip->stealth_last_visible_stamp) < 5000 ) {
8366                         // go back to find mode
8367                         aip->submode = SM_STEALTH_FIND;
8368                         aip->submode_start_time = Missiontime;
8369                         aip->submode_parm0 = SM_SF_AHEAD;
8370                 } else if ( /*(Missiontime - aip->submode_start_time) > i2f(30) || */ aip->submode_parm0 == SM_SS_DONE ) {
8371                         // set target objnum = -1
8372                         set_target_objnum(aip, -1);
8373
8374                         // set submode to attack
8375                         aip->submode = SM_ATTACK;
8376                         aip->submode_start_time = Missiontime;
8377                         aip->last_attack_time = Missiontime;
8378                 }
8379                 break;
8380
8381         case SM_ATTACK_FOREVER: //      Engines blown, just attack.
8382                 break;
8383
8384         default:
8385                 //Int3();
8386                 aip->submode = SM_ATTACK;
8387                 aip->last_attack_time = Missiontime;
8388
8389                 aip->submode_start_time = Missiontime;
8390         }
8391
8392         //
8393         //      Maybe fire primary weapon and update time_enemy_in_range
8394         //
8395         //nprintf(("AI", "time_enemy_in_range = %7.3f, dot = %7.3f\n", aip->time_enemy_in_range, dot_to_enemy));
8396
8397         if (aip->mode != AIM_EVADE) {
8398                 if (dot_to_enemy > 0.95f - 0.5f * En_objp->radius/max(1.0f, En_objp->radius + dist_to_enemy)) {
8399                         aip->time_enemy_in_range += flFrametime;
8400                         
8401                         //      Chance of hitting ship is based on dot product of firing ship's forward vector with vector to ship
8402                         //      and also the size of the target relative to distance to target.
8403                         if (dot_to_enemy > max(0.5f, 0.90f + aip->ai_accuracy/10.0f - En_objp->radius/max(1.0f,dist_to_enemy))) {
8404
8405                                 ship *temp_shipp;
8406                                 ship_weapon *tswp;
8407
8408                                 temp_shipp = &Ships[Pl_objp->instance];
8409                                 tswp = &temp_shipp->weapons;
8410                                 if ( tswp->num_primary_banks > 0 ) {
8411                                         float   scale;
8412                                         SDL_assert(tswp->current_primary_bank < tswp->num_primary_banks);
8413                                         weapon_info     *pwip = &Weapon_info[tswp->primary_bank_weapons[tswp->current_primary_bank]];
8414
8415                                         //      Less likely to fire if far away and moving.
8416                                         scale = pwip->max_speed/(En_objp->phys_info.speed + pwip->max_speed);
8417                                         if (scale > 0.6f)
8418                                                 scale = (scale - 0.6f) * 1.5f;
8419                                         else
8420                                                 scale = 0.0f;
8421                                         if (dist_to_enemy < pwip->max_speed * (1.0f + scale)) {
8422                                                 ai_fire_primary_weapon(Pl_objp);
8423                                         }
8424
8425                                         //      Don't fire secondaries at a protected ship.
8426                                         if (!(En_objp->flags & OF_PROTECTED)) {
8427                                                 ai_choose_secondary_weapon(Pl_objp, aip, En_objp);
8428                                                 int current_bank = tswp->current_secondary_bank;
8429                                                 weapon_info     *swip = &Weapon_info[tswp->secondary_bank_weapons[tswp->current_secondary_bank]];
8430
8431                                                 if (current_bank > -1) {
8432                                                         if (aip->ai_flags & AIF_UNLOAD_SECONDARIES) {
8433                                                                 if (timestamp_until(swp->next_secondary_fire_stamp[current_bank]) > swip->fire_wait*1000.0f) {
8434                                                                         swp->next_secondary_fire_stamp[current_bank] = timestamp((int) (swip->fire_wait*1000.0f));
8435                                                                 }
8436                                                         }
8437
8438                                                         if (timestamp_elapsed(swp->next_secondary_fire_stamp[current_bank])) {
8439                                                                 if (tswp->current_secondary_bank >= 0) {
8440                                                                         weapon_info     *swip = &Weapon_info[tswp->secondary_bank_weapons[tswp->current_secondary_bank]];
8441                                                                         float firing_range;
8442                                                                         
8443                                                                         if (swip->wi_flags & WIF_BOMB)
8444                                                                                 firing_range = swip->max_speed * swip->lifetime * 0.75f;
8445                                                                         else
8446                                                                                 firing_range = swip->max_speed * swip->lifetime * (Game_skill_level + 1 + aip->ai_class/2)/NUM_SKILL_LEVELS;
8447
8448                                                                         // reduce firing range in nebula
8449                                                                         extern int Nebula_sec_range;
8450                                                                         if ((The_mission.flags & MISSION_FLAG_FULLNEB) && Nebula_sec_range) {
8451                                                                                 firing_range *= 0.8f;
8452                                                                         }
8453
8454                                                                         //      If firing a spawn weapon, distance doesn't matter.
8455                                                                         int     spawn_fire = 0;
8456
8457                                                                         if (swip->wi_flags & WIF_SPAWN) {
8458                                                                                 int     count;
8459
8460                                                                                 count = num_nearby_fighters(get_enemy_team_mask(OBJ_INDEX(Pl_objp)), &Pl_objp->pos, 1000.0f);
8461
8462                                                                                 if (count > 3)
8463                                                                                         spawn_fire = 1;
8464                                                                                 else if (count >= 1) {
8465                                                                                         float hull_percent = Pl_objp->hull_strength/sip->initial_hull_strength;
8466
8467                                                                                         if (hull_percent < 0.01f)
8468                                                                                                 hull_percent = 0.01f;
8469
8470                                                                                         if (frand() < 0.25f/(30.0f*hull_percent) * count)       //      With timestamp below, this means could fire in 30 seconds if one enemy.
8471                                                                                                 spawn_fire = 1;
8472                                                                                 }
8473                                                                         }
8474
8475                                                                         if (spawn_fire || (dist_to_enemy < firing_range)) {
8476                                                                                 if (ai_fire_secondary_weapon(Pl_objp)) {
8477                                                                                         //      Only if weapon was fired do we specify time until next fire.  If not fired, done in ai_fire_secondary...
8478                                                                                         float t;
8479                                                                                         
8480                                                                                         if (aip->ai_flags & AIF_UNLOAD_SECONDARIES) {
8481                                                                                                 t = swip->fire_wait;
8482                                                                                         } else {
8483                                                                                                 t = set_secondary_fire_delay(aip, temp_shipp, swip);
8484                                                                                         }
8485                                                                                         //nprintf(("AI", "Next secondary to be fired in %7.3f seconds.\n", t));
8486                                                                                         swp->next_secondary_fire_stamp[current_bank] = timestamp((int) (t*1000.0f));
8487                                                                                 }
8488                                                                         } else {
8489                                                                                 swp->next_secondary_fire_stamp[current_bank] = timestamp(250);
8490                                                                         }
8491                                                                 }
8492                                                         }
8493                                                 }
8494                                         }
8495                                 }
8496                         }
8497                 } else {
8498                         aip->time_enemy_in_range *= (1.0f - flFrametime);
8499                 }
8500         } else
8501                 aip->time_enemy_in_range *= (1.0f - flFrametime);
8502
8503 }
8504
8505 //      Make the object *objp move so that the point *dp on the object moves towards the point *vp
8506 //      Return distance.
8507 void dock_move_towards_point(object *objp, vector *dp, vector *vp, float speed_scale, float other_obj_speed = 0.0f)
8508 {
8509         physics_info    *pi = &objp->phys_info;
8510         float                           dist;                   //      dist to goal
8511         vector                  v2g;                    //      vector to goal
8512         vector                  abs_pnt;                //      location of dock point, ie objp->pos + db
8513
8514         if (dp == NULL)
8515                 abs_pnt = objp->pos;
8516         else
8517                 vm_vec_add(&abs_pnt, &objp->pos, dp);
8518
8519         dist = vm_vec_dist_quick(vp, &abs_pnt);
8520         if (dist > 0.0f) {
8521                 float   speed;
8522
8523                 dist = vm_vec_normalized_dir(&v2g, vp, &abs_pnt);
8524                 speed = fl_sqrt(dist) * speed_scale;
8525                 if (other_obj_speed < MAX_REPAIR_SPEED*0.75f)
8526                         speed += other_obj_speed;
8527                 else
8528                         speed += MAX_REPAIR_SPEED*0.75f;
8529
8530                 vm_vec_copy_scale(&pi->desired_vel, &v2g, speed);
8531         } else
8532                 vm_vec_zero(&pi->desired_vel);
8533 }
8534
8535 //      Set the orientation in the global reference frame for an object to attain
8536 //      to dock with another object.
8537 //      *dom            resultant global matrix
8538 //      *db_dest        pointer to destination docking bay information
8539 //      *db_src pointer to source docking bay information
8540 //      *dorient        pointer to global orientation of docking bay (ie, the dockee object's orient)
8541 //      *sorient        pointer to global orientation of docker
8542 void set_goal_dock_orient(matrix *dom, dock_bay *db_dest, dock_bay *db_src, matrix *dorient, matrix *sorient)
8543 {
8544         vector  fvec, uvec;
8545         matrix  m1, m2, m3;
8546
8547         //      Compute the global orientation of the docker's (dest) docking bay.
8548         fvec = db_dest->norm[0];
8549         vm_vec_negate(&fvec);
8550
8551         vm_vec_normalized_dir(&uvec, &db_dest->pnt[1], &db_dest->pnt[0]);
8552         vm_vector_2_matrix(&m1, &fvec, &uvec, NULL);
8553
8554         vm_matrix_x_matrix(&m3, dorient, &m1);
8555
8556         //      Compute the matrix given by the source docking bay.
8557         //      Pre-multiply the orientation of the source object (sorient) by the transpose
8558         //      of the docking bay's orientation, ie unrotate the source object's matrix.
8559         fvec = db_src->norm[0];
8560         vm_vec_normalized_dir(&uvec, &db_src->pnt[1], &db_src->pnt[0]);
8561         vm_vector_2_matrix(&m2, &fvec, &uvec, NULL);
8562         vm_transpose(&m2);
8563
8564         vm_matrix_x_matrix(dom, &m3, &m2);
8565 }
8566
8567 #define DOCK_BACKUP_RETURN_VAL  99999.9f
8568
8569 //      Make objp dock with dobjp
8570 //      Returns distance to goal, defined as distance between corresponding dock points, plus 10.0f * rotational velocity vector (DOA_DOCK only)
8571 //      DOA_APPROACH    means   approach point aip->path_cur
8572 //      DOA_DOCK                        means dock
8573 //      DOA_UNDOCK_1    means undock, moving to point nearest dock bay
8574 //      DOA_UNDOCK_2    means undock, moving to point nearest dock bay and facing away from ship
8575 //      DOA_DOCK_STAY   means rigidly maintain position in dock bay.
8576 float dock_orient_and_approach(object *objp, object *dobjp, int dock_mode)
8577 {
8578         ship_info       *sip0, *sip1;
8579         polymodel       *pm0, *pm1;
8580         ai_info         *aip;
8581         matrix          dom, nm;
8582         vector          goal_point, docker_point;
8583         float                   fdist = UNINITIALIZED_VALUE;
8584         int                     docker_index, dockee_index;             // index into docking_bays[] array for objects docking
8585                                                                                                                                 // docker is Pl_objp -- dockee is dobjp
8586         aip = &Ai_info[Ships[objp->instance].ai_index];
8587
8588         //      If dockee has moved much, then path will be recreated.
8589         //      Might need to change state if moved too far.
8590         if ((dock_mode != DOA_DOCK_STAY) && (dock_mode != DOA_DOCK)) {
8591                 if (maybe_recreate_path(objp, &Ai_info[Ships[objp->instance].ai_index], 0) > 5.0f) {
8592 /*                      if (dock_mode == DOA_APPROACH) {
8593                                 return DOCK_BACKUP_RETURN_VAL;
8594                         } else if (dock_mode == DOA_DOCK) {
8595                                 return DOCK_BACKUP_RETURN_VAL;          
8596                         }
8597 */              }
8598         }
8599
8600         objp->phys_info.forward_thrust = 0.0f;          //      Kill thrust so we don't have a sputtering thruster.
8601
8602         sip0 = &Ship_info[Ships[objp->instance].ship_info_index];
8603         sip1 = &Ship_info[Ships[dobjp->instance].ship_info_index];
8604         pm0 = model_get( sip0->modelnum );
8605         pm1 = model_get( sip1->modelnum );
8606
8607         docker_index = aip->dock_index;
8608         dockee_index = aip->dockee_index;
8609
8610         SDL_assert( docker_index >= 0 );
8611         SDL_assert( dockee_index >= 0 );
8612
8613         SDL_assert(pm0->docking_bays[docker_index].num_slots == 2);
8614         SDL_assert(pm1->docking_bays[dockee_index].num_slots == 2);
8615
8616         float speed_scale = 1.0f;
8617         if (sip0->flags & SIF_SUPPORT) {
8618                 speed_scale = 3.0f;
8619         }
8620
8621         switch (dock_mode) {
8622         case DOA_APPROACH:
8623                 {
8624                 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8625                         return 9999.9f;
8626                 }
8627                 
8628                 //      Compute the desired global orientation matrix for the docker's station.
8629                 //      That is, the normal vector of the docking station must be the same as the
8630                 //      forward vector and the vector between its two points must be the uvec.
8631                 set_goal_dock_orient(&dom, &pm1->docking_bays[dockee_index], &pm0->docking_bays[docker_index], &dobjp->orient, &objp->orient);
8632
8633                 //      Compute new orientation matrix and update rotational velocity.
8634                 vector  w_in, w_out, vel_limit, acc_limit;
8635                 float           tdist, mdist, ss1;
8636
8637                 w_in = objp->phys_info.rotvel;
8638                 vel_limit = objp->phys_info.max_rotvel;
8639                 vm_vec_copy_scale(&acc_limit, &vel_limit, 0.3f);
8640                 
8641                 if (sip0->flags & SIF_SUPPORT)
8642                         vm_vec_scale(&acc_limit, 2.0f);
8643
8644                 // 1 at end of line prevent overshoot
8645                 vm_matrix_interpolate(&dom, &objp->orient, &w_in, flFrametime, &nm, &w_out, &vel_limit, &acc_limit, 1);
8646                 objp->phys_info.rotvel = w_out;
8647                 objp->orient = nm;
8648
8649                 //      Translate towards goal and note distance to goal.
8650                 goal_point = Path_points[aip->path_cur].pos;
8651                 mdist = ai_matrix_dist(&objp->orient, &dom);
8652                 tdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8653
8654                 //      If translation is badly lagging rotation, speed up translation.
8655                 if (mdist > 0.1f) {
8656                         ss1 = tdist/(10.0f * mdist);
8657                         if (ss1 > 2.0f)
8658                                 ss1 = 2.0f;
8659                 } else
8660                         ss1 = 2.0f;
8661
8662                 // nprintf(("AI", "speed scale = %7.3f\n", ss1));
8663                 speed_scale *= 1.0f + ss1;
8664
8665                 dock_move_towards_point(objp, NULL, &goal_point, speed_scale, dobjp->phys_info.speed);
8666
8667                 fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8668
8669                 //      Note, we're interested in distance from goal, so if we're still turning, bash that into return value.
8670                 // nprintf(("AI", "matrix dist = %7.3f, threshold = %7.3f\n", mdist, 2*flFrametime));
8671                 fdist += 2.0f * mdist;
8672
8673                 break;
8674         }
8675         case DOA_DOCK:
8676                 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8677                         return 9999.9f;
8678                 }
8679         case DOA_DOCK_STAY:
8680                 //      Compute the desired global orientation matrix for the docker's station.
8681                 //      That is, the normal vector of the docking station must be the same as the
8682                 //      forward vector and the vector between its two points must be the uvec.
8683                 set_goal_dock_orient(&dom, &pm1->docking_bays[dockee_index], &pm0->docking_bays[docker_index], &dobjp->orient, &objp->orient);
8684
8685                 //      Compute distance between dock bay points.
8686                 vector  db0, db1, db2, db3;
8687
8688                 vm_vec_unrotate(&db0, &pm0->docking_bays[docker_index].pnt[0], &objp->orient);
8689                 vm_vec_add2(&db0, &objp->pos);
8690
8691                 vm_vec_unrotate(&db1, &pm0->docking_bays[docker_index].pnt[1], &objp->orient);
8692                 vm_vec_add2(&db1, &objp->pos);
8693
8694                 vm_vec_unrotate(&db2, &pm1->docking_bays[dockee_index].pnt[0], &dobjp->orient);
8695                 vm_vec_add2(&db2, &dobjp->pos);
8696
8697                 vm_vec_unrotate(&db3, &pm1->docking_bays[dockee_index].pnt[1], &dobjp->orient);
8698                 vm_vec_add2(&db3, &dobjp->pos);
8699
8700                 vm_vec_avg(&goal_point, &db2, &db3);
8701
8702                 vm_vec_avg(&docker_point, &db0, &db1);
8703                 vm_vec_sub2(&docker_point, &objp->pos);
8704
8705                 if (dock_mode == DOA_DOCK) {
8706                         vector  t1, t2;
8707                         vector  w_in, w_out, vel_limit, acc_limit;
8708
8709                         fdist = vm_vec_dist_quick(vm_vec_avg(&t1, &db0, &db1), vm_vec_avg(&t2, &db2, &db3));
8710
8711                         //      Compute new orientation matrix and update rotational velocity.
8712                         w_in = objp->phys_info.rotvel;
8713                         vel_limit = objp->phys_info.max_rotvel;
8714                         vm_vec_copy_scale(&acc_limit, &vel_limit, 0.3f);
8715
8716                         if (sip0->flags & SIF_SUPPORT)
8717                                 vm_vec_scale(&acc_limit, 2.0f);
8718
8719                         vm_matrix_interpolate(&dom, &objp->orient, &w_in, flFrametime, &nm, &w_out, &vel_limit, &acc_limit);
8720                         objp->phys_info.rotvel = w_out;
8721                         objp->orient = nm;
8722
8723                         //      Note, we're interested in distance from goal, so if we're still turning, bash that into return value.
8724                         fdist += 10.0f * vm_vec_mag_quick(&w_out);
8725
8726                         dock_move_towards_point(objp, &docker_point, &goal_point, speed_scale, dobjp->phys_info.speed);
8727                 } else {
8728                         SDL_assert(dock_mode == DOA_DOCK_STAY);
8729                         objp->orient = dom;
8730                         vector  temp;
8731                         vm_vec_sub(&temp, &goal_point, &docker_point);
8732                         vm_vec_sub(&objp->pos, &goal_point, &docker_point);
8733                 }
8734
8735                 break;
8736         case DOA_UNDOCK_1: {
8737                 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8738                         return 9999.9f;
8739                 }
8740
8741                 //      Undocking.
8742                 //      Move to point on dock path nearest to dock station.
8743                 SDL_assert(aip->path_length >= 2);
8744                 goal_point = Path_points[aip->path_start + aip->path_length-2].pos;
8745
8746                 vm_vec_zero(&docker_point);
8747                 fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8748
8749                 dock_move_towards_point(objp, &docker_point, &goal_point, speed_scale);
8750
8751                 break;
8752                           }
8753
8754         case DOA_UNDOCK_2: {
8755                 //      Undocking.
8756                 //      Move to point on dock path nearest to dock station and orient away from big ship.
8757                 int             desired_index;
8758
8759                 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8760                         return 9999.9f;
8761                 }
8762
8763                 SDL_assert(aip->path_length >= 2);
8764 //              if (aip->path_length >= 3)
8765 //                      desired_index = aip->path_length-3;
8766 //              else
8767                         desired_index = aip->path_length-2;
8768
8769                 goal_point = Path_points[aip->path_start + desired_index].pos;
8770
8771                 dock_move_towards_point(objp, NULL, &goal_point, speed_scale);
8772
8773                 fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8774                 break;
8775                           }
8776         case DOA_UNDOCK_3: {
8777                 float           dist, goal_dist;
8778                 vector  away_vec;
8779
8780                 goal_dist = objp->radius + dobjp->radius + 25.0f;
8781
8782                 dist = vm_vec_normalized_dir(&away_vec, &objp->pos, &dobjp->pos);
8783                 vm_vec_scale_add(&goal_point, &dobjp->pos, &away_vec, goal_dist);
8784                 if (vm_vec_dist_quick(&goal_point, &dobjp->pos) < vm_vec_dist_quick(&objp->pos, &dobjp->pos))
8785                         fdist = 0.0f;
8786                 else {
8787                         float   dot, accel;
8788                         float turn_time = Ship_info[Ships[objp->instance].ship_info_index].srotation_time;
8789                         ai_turn_towards_vector(&goal_point, objp, flFrametime, turn_time, NULL, NULL, 0.0f, 0);
8790
8791                         dot = vm_vec_dot(&objp->orient.v.fvec, &away_vec);
8792                         accel = 0.1f;
8793                         if (dot > accel)
8794                                 accel = dot;
8795                         if (dist > goal_dist/2)
8796                                 accel *= 1.2f - 0.5f*goal_dist/dist;
8797
8798                         accelerate_ship(aip, accel);
8799                         fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8800                 }
8801
8802                 break;
8803                                                          }
8804         }
8805
8806 #ifndef NDEBUG
8807         //      For debug purposes, compute global orientation of both dock vectors and show
8808         //      how close they are.
8809         vector  d0, d1;
8810
8811         vm_vec_unrotate(&d0, &pm0->docking_bays[docker_index].norm[0], &objp->orient);
8812         vm_vec_unrotate(&d1, &pm1->docking_bays[dockee_index].norm[0], &dobjp->orient);
8813
8814         //nprintf(("AI", "or/app: dist = %7.3f/%7.3f, dot = %7.3f, global dot = %7.3f\n", 
8815         //      vm_vec_dist_quick(&goal_point, &objp->pos), fdist,
8816         //      vm_vec_dot(&objp->orient.v.fvec, &dom.v.fvec), 
8817         //      vm_vec_dot(&d0, &d1)));
8818 #endif
8819
8820         // -- Note, A lot of callers don't care about fdist, so OK to return ERROR value: SDL_assert(fdist != UNINITIALIZED_VALUE);
8821         return fdist;
8822
8823 }
8824
8825 void debug_find_guard_object()
8826 {
8827         ship                    *shipp = &Ships[Pl_objp->instance];     
8828         object          *objp;
8829
8830         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
8831                 if ((Pl_objp != objp) && (objp->type == OBJ_SHIP)) {
8832                         if (objp->instance != -1) {
8833                                 if (Ships[objp->instance].team == shipp->team)  {
8834                                         // nprintf(("AI", "Setting guard object for %s to %s\n", shipp->ship_name, Ships[objp->instance].ship_name));
8835                                         ai_set_guard_object(Pl_objp, objp);
8836                                 }
8837                         }
8838                 }
8839         }
8840
8841 }
8842
8843 //      Given an object number, return the number of ships attacking it.
8844 int num_ships_attacking(int objnum)
8845 {
8846         object  *objp;
8847         ship_obj        *so;
8848         int             count = 0;
8849
8850         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
8851                 objp = &Objects[so->objnum];
8852                 if (objp->instance != -1) {
8853                         ai_info *aip;
8854                         aip = &Ai_info[Ships[objp->instance].ai_index];
8855
8856                         if ((aip->mode == AIM_CHASE) && (aip->target_objnum == objnum))
8857                                 if (Ships[objp->instance].team != Ships[Objects[objnum].instance].team)
8858                                         count++;
8859                 }
8860         }
8861
8862         return count;
8863 }
8864
8865 //      For all objects attacking object #objnum, remove the one that is farthest away.
8866 //      Do this by resuming previous behavior, if any.  If not, set target_objnum to -1.
8867 void remove_farthest_attacker(int objnum)
8868 {
8869         object  *objp, *objp2, *farthest_objp;
8870         ship_obj        *so;
8871         float           farthest_dist;
8872
8873         objp2 = &Objects[objnum];
8874
8875         farthest_dist = 9999999.9f;
8876         farthest_objp = NULL;
8877
8878         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
8879                 objp = &Objects[so->objnum];
8880                 if ( !(objp->flags & OF_PLAYER_SHIP)) {
8881                         if (objp->instance != -1) {
8882                                 ai_info *aip2;
8883
8884                                 aip2 = &Ai_info[Ships[objp->instance].ai_index];
8885
8886                                 if ((aip2->mode == AIM_CHASE) && (aip2->target_objnum == objnum)) {
8887                                         if (Ships[objp->instance].team != Ships[Objects[objnum].instance].team) {
8888                                                 float   dist;
8889
8890                                                 dist = vm_vec_dist_quick(&objp->pos, &objp2->pos);
8891                                                 if (dist < farthest_dist) {
8892                                                         farthest_dist = dist;
8893                                                         farthest_objp = objp;
8894                                                 }
8895                                         }
8896                                 }
8897                         }
8898                 }
8899         }
8900
8901         if (farthest_objp != NULL) {
8902                 ai_info *aip;
8903                 SDL_assert(farthest_objp->type == OBJ_SHIP);
8904                 SDL_assert((farthest_objp->instance > -1) && (farthest_objp->instance < MAX_SHIPS));
8905                 SDL_assert(Ships[farthest_objp->instance].ai_index > -1);
8906
8907                 aip = &Ai_info[Ships[farthest_objp->instance].ai_index];
8908
8909                 if (!maybe_resume_previous_mode(Pl_objp, aip)) {
8910                         //      If already ignoring something under player's orders, don't ignore current target.
8911                         if ((aip->ignore_objnum == UNUSED_OBJNUM) || (aip->ai_flags & AIF_TEMPORARY_IGNORE)) {
8912                                 aip->ignore_objnum = aip->target_objnum;
8913                                 aip->ignore_signature = Objects[aip->target_objnum].signature;
8914                                 aip->ai_flags |= AIF_TEMPORARY_IGNORE;
8915                                 aip->ignore_expire_timestamp = timestamp(((myrand() % 10) + 20) * 1000);        //      OK to attack again in 20 to 24 seconds.
8916                         }
8917                         aip->target_objnum = -1;
8918                         ai_do_default_behavior(farthest_objp);
8919                 }
8920         }
8921 }
8922
8923 // Maybe limit the number of attackers on attack_objnum.  For now, only limit attackers
8924 // in attacked_objnum is the player
8925 // input:       attacked_objnum =>              object index for ship we want to limit attacks on
8926 //
8927 //      exit:                   1       =>      num attackers exceeds maximum, abort
8928 //                                      0       =>      removed the farthest attacker
8929 //                                      -1      =>      nothing was done
8930 int ai_maybe_limit_attackers(int attacked_objnum)
8931 {
8932         int rval=-1;
8933
8934         // limit the number of ships attacking the _player_ only
8935 //      if ( attacked_objnum == OBJ_INDEX(Player_obj) ) {
8936         if ( Objects[attacked_objnum].flags & OF_PLAYER_SHIP) {
8937                 int num_attacking;
8938                 num_attacking = num_ships_attacking(attacked_objnum);
8939
8940                 if (num_attacking == Skill_level_max_attackers[Game_skill_level]) {
8941                         remove_farthest_attacker(attacked_objnum);
8942                         rval=0;
8943                 } else if (num_attacking > Skill_level_max_attackers[Game_skill_level]) {
8944                         rval=1;
8945                 }
8946                 //nprintf(("AI", "Num attacking player = %i\n", num_attacking));
8947         }
8948
8949         return rval;
8950 }
8951
8952 //      Object being guarded by object *guard_objp was hit by object *hitter_objp
8953 void guard_object_was_hit(object *guard_objp, object *hitter_objp)
8954 {
8955         int             hitter_objnum;
8956         ai_info *aip;
8957
8958         aip = &Ai_info[Ships[guard_objp->instance].ai_index];
8959
8960         if (guard_objp == hitter_objp) {
8961                 // Int3();      //      Bogus!  Who tried to get me to attack myself!  Trace out and fix!
8962                 return;
8963         }
8964
8965         if (guard_objp->type == OBJ_GHOST || hitter_objp->type == OBJ_GHOST)
8966                 return;
8967
8968         if (aip->ai_flags & AIF_NO_DYNAMIC)     //      Not allowed to pursue dynamic goals.  So, why are we guarding?
8969                 return;
8970
8971         SDL_assert( (hitter_objp->type == OBJ_SHIP) || (hitter_objp->type == OBJ_ASTEROID) || (hitter_objp->type == OBJ_WEAPON) );
8972
8973         hitter_objnum = OBJ_INDEX(hitter_objp);
8974
8975         if ( hitter_objp->type == OBJ_SHIP ) {
8976                 //      If the hitter object is the ignore object, don't attack it.
8977                 if (is_ignore_object(aip, hitter_objp-Objects))
8978                         return;
8979
8980                 //      If hitter is on same team as me, don't attack him.
8981                 if (Ships[guard_objp->instance].team == Ships[hitter_objp->instance].team)
8982                         return;
8983
8984                 // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
8985                 if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
8986                         return;
8987                 }
8988
8989                 // dont attack if you can't see him
8990                 if ( awacs_get_level(hitter_objp, &Ships[aip->shipnum], 1) < 1 ) {
8991                         // if he's a stealth and visible, but not targetable, ok to attack.
8992                         if ( is_object_stealth_ship(hitter_objp) ) {
8993                                 if ( ai_is_stealth_visible(guard_objp, hitter_objp) != STEALTH_VISIBLE ) {
8994                                         return;
8995                                 }
8996                         }
8997                 }
8998         }
8999
9000         if (aip->target_objnum == -1) {
9001                 aip->ok_to_target_timestamp = timestamp(0);
9002         }
9003
9004         if ((aip->submode == AIS_GUARD_PATROL) || (aip->submode == AIS_GUARD_STATIC)) {
9005
9006                 if ( hitter_objp->type == OBJ_SHIP ) {
9007                         if (!(Ship_info[Ships[guard_objp->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
9008                                 return;
9009                         }
9010
9011                         // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
9012                         if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
9013                                 return;
9014                         }
9015                 }
9016
9017                 if (aip->target_objnum != hitter_objnum) {
9018                         aip->aspect_locked_time = 0.0f;
9019                 }
9020
9021                 aip->ok_to_target_timestamp = timestamp(0);
9022
9023                 set_target_objnum(aip, hitter_objnum);
9024                 //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));
9025                 aip->previous_mode = AIM_GUARD;
9026                 aip->previous_submode = aip->submode;
9027                 aip->mode = AIM_CHASE;
9028                 aip->submode = SM_ATTACK;
9029                 aip->submode_start_time = Missiontime;
9030                 aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
9031         } else if (aip->previous_mode == AIM_GUARD) {
9032                 if (aip->target_objnum == -1) {
9033
9034                         if ( hitter_objp->type == OBJ_SHIP ) {
9035                                 // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
9036                                 if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
9037                                         return;
9038                                 }
9039                         }
9040
9041                         set_target_objnum(aip, hitter_objnum);
9042                 //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));
9043                         aip->mode = AIM_CHASE;
9044                         aip->submode = SM_ATTACK;
9045                         aip->submode_start_time = Missiontime;
9046                         aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
9047                 } else {
9048                         int     num_attacking_cur, num_attacking_new;
9049
9050                         num_attacking_cur = num_ships_attacking(aip->target_objnum);
9051                         if (num_attacking_cur > 1) {
9052                                 num_attacking_new = num_ships_attacking(hitter_objnum);
9053
9054                                 if (num_attacking_new < num_attacking_cur) {
9055
9056                                         if ( hitter_objp->type == OBJ_SHIP ) {
9057                                                 // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
9058                                                 if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
9059                                                         return;
9060                                                 }
9061                                         }
9062                                         set_target_objnum(aip, hitter_objp-Objects);
9063                 //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));
9064                                         aip->mode = AIM_CHASE;
9065                                         aip->submode = SM_ATTACK;
9066                                         aip->submode_start_time = Missiontime;
9067                                         aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
9068                                 }
9069                         }
9070                 }
9071         }
9072 }
9073
9074 //      Ship object *hit_objp was hit by ship object *hitter_objp.
9075 //      See if anyone is guarding hit_objp and, if so, do something useful.
9076 void maybe_update_guard_object(object *hit_objp, object *hitter_objp)
9077 {
9078         object  *objp;
9079         ship_obj        *so;
9080
9081         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
9082                 objp = &Objects[so->objnum];
9083                 if (objp->instance != -1) {
9084                         ai_info *aip;
9085                         aip = &Ai_info[Ships[objp->instance].ai_index];
9086
9087                         if ((aip->mode == AIM_GUARD) || (aip->active_goal == AI_ACTIVE_GOAL_DYNAMIC)) {
9088                                 if (aip->guard_objnum == hit_objp-Objects) {
9089                                         guard_object_was_hit(objp, hitter_objp);
9090                                 } else if ((aip->guard_wingnum != -1) && (aip->guard_wingnum == Ai_info[Ships[hit_objp->instance].ai_index].wing)) {
9091                                         guard_object_was_hit(objp, hitter_objp);
9092                                 }
9093                         }
9094                 }
9095         }
9096 }
9097
9098 // Scan missile list looking for bombs homing on guarded_objp
9099 // return 1 if bomb is found (and targeted by guarding_objp), otherwise return 0
9100 int ai_guard_find_nearby_bomb(object *guarding_objp, object *guarded_objp)
9101 {       
9102         missile_obj     *mo;
9103         object          *bomb_objp, *closest_bomb_objp=NULL;
9104         float                   dist, dist_to_guarding_obj,closest_dist_to_guarding_obj=999999.0f;
9105         weapon          *wp;
9106         weapon_info     *wip;
9107
9108         for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
9109                 SDL_assert(mo->objnum >= 0 && mo->objnum < MAX_OBJECTS);
9110                 bomb_objp = &Objects[mo->objnum];
9111
9112                 wp = &Weapons[bomb_objp->instance];
9113                 wip = &Weapon_info[wp->weapon_info_index];
9114
9115                 if ( !(wip->wi_flags & WIF_BOMB) ) {
9116                         continue;
9117                 }
9118
9119                 if ( wp->homing_object != guarded_objp ) {
9120                         continue;
9121                 }
9122
9123                 dist = vm_vec_dist_quick(&bomb_objp->pos, &guarded_objp->pos);
9124
9125                 if (dist < (MAX_GUARD_DIST + guarded_objp->radius)*3) {
9126                         dist_to_guarding_obj = vm_vec_dist_quick(&bomb_objp->pos, &guarding_objp->pos);
9127                         if ( dist_to_guarding_obj < closest_dist_to_guarding_obj ) {
9128                                 closest_dist_to_guarding_obj = dist_to_guarding_obj;
9129                                 closest_bomb_objp = bomb_objp;
9130                         }
9131                 }
9132         }
9133
9134         if ( closest_bomb_objp ) {
9135                 guard_object_was_hit(guarding_objp, closest_bomb_objp);
9136                 return 1;
9137         }
9138
9139         return 0;
9140 }
9141
9142 //      Scan enemy ships and see if one is near enough to guard object to be pursued.
9143 void ai_guard_find_nearby_ship(object *guarding_objp, object *guarded_objp)
9144 {
9145         ship            *guarding_shipp = &Ships[guarding_objp->instance];
9146         ai_info *guarding_aip = &Ai_info[guarding_shipp->ai_index];
9147         ship_obj        *so;
9148         object  *enemy_objp;
9149         float           dist;
9150
9151         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
9152                 enemy_objp = &Objects[so->objnum];
9153
9154                 if (enemy_objp->instance < 0) {
9155                         continue;
9156                 }
9157
9158                 ship    *eshipp = &Ships[enemy_objp->instance];
9159
9160                 //      Don't attack a cargo container or other harmless ships
9161                 if (!(Ship_info[eshipp->ship_info_index].flags & SIF_HARMLESS)) {
9162                         if (guarding_shipp->team != eshipp->team)       {
9163                                 dist = vm_vec_dist_quick(&enemy_objp->pos, &guarded_objp->pos);
9164                                 if (dist < (MAX_GUARD_DIST + guarded_objp->radius)*3) {
9165                                         guard_object_was_hit(guarding_objp, enemy_objp);
9166                                 } else if ((dist < 3000.0f) && (Ai_info[eshipp->ai_index].target_objnum == guarding_aip->guard_objnum)) {
9167                                         //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));
9168                                         guard_object_was_hit(guarding_objp, enemy_objp);
9169                                 }
9170                         }
9171                 }
9172         }
9173 }
9174
9175 // Scan for nearby asteroids.  Favor asteroids which have their collide_objnum set to that of the
9176 // guarded ship.  Also, favor asteroids that are closer to the guarding ship, since it looks cooler
9177 // when a ship blows up an asteroid then goes after the pieces that break off.
9178 void ai_guard_find_nearby_asteroid(object *guarding_objp, object *guarded_objp)
9179 {       
9180         float           dist;
9181
9182         object  *closest_asteroid_objp=NULL, *danger_asteroid_objp=NULL, *asteroid_objp;
9183         float           dist_to_self, closest_danger_asteroid_dist=999999.0f, closest_asteroid_dist=999999.0f;
9184
9185         for ( asteroid_objp = GET_FIRST(&obj_used_list); asteroid_objp != END_OF_LIST(&obj_used_list); asteroid_objp = GET_NEXT(asteroid_objp) ) {
9186                 if ( asteroid_objp->type == OBJ_ASTEROID ) {
9187                         // Attack asteroid if near guarded ship
9188                         dist = vm_vec_dist_quick(&asteroid_objp->pos, &guarded_objp->pos);
9189                         if ( dist < (MAX_GUARD_DIST + guarded_objp->radius)*2) {
9190                                 dist_to_self = vm_vec_dist_quick(&asteroid_objp->pos, &guarding_objp->pos);
9191                                 if ( OBJ_INDEX(guarded_objp) == asteroid_collide_objnum(asteroid_objp) ) {
9192                                         if( dist_to_self < closest_danger_asteroid_dist ) {
9193                                                 danger_asteroid_objp=asteroid_objp;
9194                                                 closest_danger_asteroid_dist=dist_to_self;
9195                                         }
9196                                 } 
9197                                 if ( dist_to_self < closest_asteroid_dist ) {
9198                                         // only attack if moving slower than own max speed
9199                                         if ( vm_vec_mag_quick(&asteroid_objp->phys_info.vel) < guarding_objp->phys_info.max_vel.xyz.z ) {
9200                                                 closest_asteroid_dist = dist_to_self;
9201                                                 closest_asteroid_objp = asteroid_objp;
9202                                         }
9203                                 }
9204                         }
9205                 }
9206         }
9207
9208         if ( danger_asteroid_objp ) {
9209                 guard_object_was_hit(guarding_objp, danger_asteroid_objp);
9210         } else if ( closest_asteroid_objp ) {
9211                 guard_object_was_hit(guarding_objp, closest_asteroid_objp);
9212         }
9213 }
9214
9215 //      Scan potential harmful objects and see if one is near enough to guard object to be pursued.
9216 void ai_guard_find_nearby_object()
9217 {
9218         ship                    *shipp = &Ships[Pl_objp->instance];
9219         ai_info         *aip = &Ai_info[shipp->ai_index];
9220         object          *guardobjp;
9221         int                     bomb_found=0;
9222
9223         guardobjp = &Objects[aip->guard_objnum];
9224         
9225         // highest priority is a bomb fired on guarded ship
9226         bomb_found = ai_guard_find_nearby_bomb(Pl_objp, guardobjp);
9227
9228         if ( !bomb_found ) {
9229                 // check for ships if there are no bombs fired at guarded ship
9230                 ai_guard_find_nearby_ship(Pl_objp, guardobjp);
9231
9232                 // if not attacking anything, go for asteroid close to guarded ship
9233                 if ( (aip->target_objnum == -1) && asteroid_count() ) {
9234                         ai_guard_find_nearby_asteroid(Pl_objp, guardobjp);
9235                 }
9236         }
9237 }
9238
9239 // gets closest point on extended axis of cylinder, r_vec, and radius of cylinder
9240 // returns z of axis_point in cyl_objp reference frame
9241 float get_cylinder_points(object *other_objp, object *cyl_objp, vector *axis_pt, vector *r_vec, float *radius)
9242 {
9243         SDL_assert(other_objp->type == OBJ_SHIP);
9244         SDL_assert(cyl_objp->type == OBJ_SHIP);
9245
9246         // get radius of cylinder
9247         polymodel *pm = model_get(Ships[cyl_objp->instance].modelnum);
9248         float tempx, tempy;
9249         tempx = max(-pm->mins.xyz.x, pm->maxs.xyz.x);
9250         tempy = max(-pm->mins.xyz.y, pm->maxs.xyz.y);
9251         *radius = max(tempx, tempy);
9252
9253         // get vec from cylinder to other_obj
9254         vector r_sph;
9255         vm_vec_sub(&r_sph, &other_objp->pos, &cyl_objp->pos);
9256
9257         // get point on axis and on cylinder
9258         // extended_cylinder_z is along extended cylinder
9259         // cylinder_z is capped within cylinder
9260         float extended_cylinder_z = vm_vec_dotprod(&r_sph, &cyl_objp->orient.v.fvec);
9261
9262         // get pt on axis of extended cylinder
9263         vm_vec_scale_add(axis_pt, &cyl_objp->pos, &cyl_objp->orient.v.fvec, extended_cylinder_z);
9264
9265         // get r_vec (pos - axis_pt) normalized
9266         vm_vec_normalized_dir(r_vec, &other_objp->pos, axis_pt);
9267
9268         return extended_cylinder_z;
9269 }
9270
9271 // handler for guard behavior when guarding BIG ships
9272 //      When someone has attacked guarded ship, then attack that ship.
9273 // To attack another ship, switch out of guard mode into chase mode.
9274 void ai_big_guard()
9275 {
9276         
9277         ship                    *shipp = &Ships[Pl_objp->instance];
9278         ai_info         *aip = &Ai_info[shipp->ai_index];
9279         object          *guard_objp;
9280
9281         // sanity checks already done in ai_guard()
9282         guard_objp = &Objects[aip->guard_objnum];
9283
9284         switch (aip->submode) {
9285         case AIS_GUARD_STATIC:
9286         case AIS_GUARD_PATROL:
9287                 {
9288                 vector axis_pt, r_vec, theta_vec;
9289                 float radius, extended_z;
9290
9291                 // get random [0 to 1] based on OBJNUM
9292                 float objval = static_randf(Pl_objp-Objects);
9293
9294                 // get position relative to cylinder of guard_objp              
9295                 extended_z = get_cylinder_points(Pl_objp, guard_objp, &axis_pt, &r_vec, &radius);
9296                 vm_vec_crossprod(&theta_vec, &guard_objp->orient.v.fvec, &r_vec);
9297
9298                 // half ships circle each way
9299                 if (objval > 0.5f) {
9300                         vm_vec_negate(&theta_vec);
9301                 }
9302
9303                 float min_guard_dist = radius + Pl_objp->radius + 50.0f;
9304                 float desired_guard_dist = min_guard_dist + 0.5f * ((1.0f + objval) * MAX_GUARD_DIST);
9305                 float max_guard_dist =     min_guard_dist + 1.0f * ((1.0f + objval) * MAX_GUARD_DIST);
9306
9307                 // get z extents
9308                 float min_z, max_z, length;
9309                 polymodel *pm = model_get(Ships[guard_objp->instance].modelnum);
9310                 min_z = pm->mins.xyz.z;
9311                 max_z = pm->maxs.xyz.z;
9312                 length = max_z - min_z;
9313
9314                 // get desired z
9315                 // how often to choose new desired_z
9316                 // 1*(64) sec < 2000, 2*(64) < 2-4000 3*(64) > 4-8000, etc (Missiontime >> 22 is 64 sec intervals)
9317                 int time_choose = int(floor(log(length * 0.001) / log(2.0)));
9318                 float desired_z = min_z + length * static_randf( (Pl_objp-Objects) ^ (Missiontime >> (22 + time_choose)) );
9319
9320                 // get r from guard_ship
9321                 float cur_guard_rad = vm_vec_dist(&Pl_objp->pos, &axis_pt);
9322
9323                 // is ship within extents of cylinder of ship it is guarding
9324                 int inside = (extended_z > min_z) && (extended_z < min_z + length);
9325
9326                 vector goal_pt;
9327                 // maybe go into orbit mode
9328                 if (cur_guard_rad < max_guard_dist) {
9329                         if ( cur_guard_rad > min_guard_dist ) {
9330                                 if (inside) {
9331                                         // orbit
9332                                         vm_vec_scale_add(&goal_pt, &axis_pt, &r_vec, desired_guard_dist);
9333                                         vm_vec_scale_add2(&goal_pt, &theta_vec, desired_guard_dist);
9334                                 } else {
9335                                         // move to where I can orbit
9336                                         if (extended_z < min_z) {
9337                                                 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, min_z);
9338                                         } else {
9339                                                 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, max_z);
9340                                         }
9341                                         vm_vec_scale_add2(&goal_pt, &r_vec, desired_guard_dist);
9342                                         vm_vec_scale_add2(&goal_pt, &theta_vec, desired_guard_dist);
9343                                 }
9344                         } else {
9345                                 // too close for orbit mode
9346                                 if (inside) {
9347                                         // inside (fly straight out and return circle)
9348                                         vm_vec_scale_add(&goal_pt, &axis_pt, &r_vec, max_guard_dist);
9349                                 } else {
9350                                         // outside (fly to edge and circle)
9351                                         if (extended_z < min_z) {
9352                                                 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, min_z);
9353                                         } else {
9354                                                 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, max_z);
9355                                         }
9356                                         vm_vec_scale_add2(&goal_pt, &r_vec, max_guard_dist);
9357                                         vm_vec_scale_add2(&goal_pt, &theta_vec, desired_guard_dist);
9358                                 }
9359                         }
9360
9361                         if (Pl_objp->phys_info.fspeed > 0) {
9362                                 // modify goal_pt to take account moving guard objp
9363                                 float dist = vm_vec_dist_quick(&Pl_objp->pos, &goal_pt);
9364                                 float time = dist / Pl_objp->phys_info.fspeed;
9365                                 vm_vec_scale_add2(&goal_pt, &guard_objp->phys_info.vel, time);
9366
9367                                 // now modify to move to desired z (at a max of 20 m/s)
9368                                 float delta_z = desired_z - extended_z;
9369                                 float v_z = delta_z * 0.2f;
9370                                 if (v_z < -20) {
9371                                         v_z = -20.0f;
9372                                 } else if (v_z > 20) {
9373                                         v_z = 20.0f;
9374                                 }
9375
9376                                 vm_vec_scale_add2(&goal_pt, &guard_objp->orient.v.fvec, v_z*time);
9377                         }
9378
9379                 } else {
9380                         // cast vector to center of guard_ship adjusted by desired_z
9381                         float delta_z = desired_z - extended_z;
9382                         vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, delta_z);
9383                 }
9384
9385                 // try not to bump into things along the way
9386                 if ( (cur_guard_rad > max_guard_dist) || (extended_z < min_z) || (extended_z > max_z) ) {
9387                         if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_pt, 5.0f)) {
9388                                 return;
9389                         }
9390
9391                         if (avoid_player(Pl_objp, &goal_pt)) {
9392                                 return;
9393                         }
9394                 } else {
9395                         if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_pt, 5.0f)) {
9396                                 return;
9397                         }
9398                 }
9399
9400                 // got the point, now let's go there
9401                 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);
9402 //              aip->goal_point = goal_pt;
9403                 accelerate_ship(aip, 1.0f);
9404
9405                 //      Periodically, scan for a nearby ship to attack.
9406                 if (((AI_FrameCount ^ (Pl_objp-Objects)) & 0x07) == 0) {
9407                         ai_guard_find_nearby_object();
9408                 }
9409                 }
9410                 break;
9411
9412         case AIS_GUARD_ATTACK:
9413                 //      The guarded ship has been attacked.  Do something useful!
9414                 ai_chase();
9415                 break;
9416
9417         default:
9418                 //Int3();       //      Illegal submode for Guard mode.
9419                 // AL 06/03/97 comment out Int3() to allow milestone to get out the door
9420                 aip->submode = AIS_GUARD_PATROL;
9421                 break;
9422         }
9423 }
9424
9425 //      Main handler for guard behavior.
9426 //      When someone has attacked guarded ship, then attack that ship.
9427 // To attack another ship, switch out of guard mode into chase mode.
9428 void ai_guard()
9429 {
9430         ship                    *shipp = &Ships[Pl_objp->instance];
9431         ai_info         *aip = &Ai_info[shipp->ai_index];
9432         object          *guard_objp;    
9433         float                   dist_to_guardobj;
9434         vector          vec_to_guardobj;
9435
9436         /*      //      Debug code, find an object to guard.
9437         int finding_guard_objnum = 0;   //      Debug code, to see if body of "if" below gets executed. 
9438         if (aip->guard_objnum == -1) {
9439                 finding_guard_objnum = 1;
9440                 debug_find_guard_object();
9441                 if (aip->guard_objnum == -1)
9442                         return;
9443         }
9444 */
9445         if (aip->guard_objnum == -1) {
9446                 aip->mode = AIM_NONE;
9447                 return;
9448         }
9449
9450         SDL_assert(aip->guard_objnum != -1);
9451
9452         guard_objp = &Objects[aip->guard_objnum];
9453
9454         if (guard_objp == Pl_objp) {
9455                 Int3();         //      This seems illegal.  Why is a ship guarding itself?
9456                 aip->guard_objnum = -1;
9457                 return;
9458         }
9459
9460         // check that I have someone to guard
9461         if (guard_objp->instance == -1) {
9462                 return;
9463         }
9464
9465         //      Not sure whether this should be impossible, or a reasonable cleanup condition.
9466         //      For now (3/31/97), it's getting trapped by an SDL_assert, so clean it up.
9467         if (guard_objp->type != OBJ_SHIP) {
9468                 aip->guard_objnum = -1;
9469                 return;
9470         }
9471
9472         // handler for gurad object with BIG radius
9473         if (guard_objp->radius > BIG_GUARD_RADIUS) {
9474                 ai_big_guard();
9475                 return;
9476         }
9477
9478         float                   objval;
9479         vector          goal_point;
9480         vector          rel_vec;
9481         float                   dist_to_goal_point, dot_to_goal_point, accel_scale;
9482         vector          v2g, rvec;
9483
9484         // get random [0 to 1] based on OBJNUM
9485         objval = static_randf(Pl_objp-Objects);
9486
9487         switch (aip->submode) {
9488         case AIS_GUARD_STATIC:
9489         case AIS_GUARD_PATROL:
9490                 //      Stay near ship
9491                 dist_to_guardobj = vm_vec_normalized_dir(&vec_to_guardobj, &guard_objp->pos, &Pl_objp->pos);
9492
9493                 rel_vec = aip->guard_vec;
9494                 vm_vec_add(&goal_point, &guard_objp->pos, &rel_vec);
9495
9496                 vm_vec_normalized_dir(&v2g, &goal_point, &Pl_objp->pos);
9497                 dist_to_goal_point = vm_vec_dist_quick(&goal_point, &Pl_objp->pos);
9498                 dot_to_goal_point = vm_vec_dot(&v2g, &Pl_objp->orient.v.fvec);
9499                 accel_scale = (1.0f + dot_to_goal_point)/2.0f;
9500
9501                 //      If far away, get closer
9502                 if (dist_to_goal_point > MAX_GUARD_DIST + 1.5 * (Pl_objp->radius + guard_objp->radius)) {
9503                         if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_point, 5.0f)) {
9504                                 return;
9505                         }
9506
9507                         if (avoid_player(Pl_objp, &goal_point)) {
9508                                 return;
9509                         }
9510
9511                         // quite far away, so try to go straight to 
9512                         compute_desired_rvec(&rvec, &goal_point, &Pl_objp->pos);
9513                         ai_turn_towards_vector(&goal_point, Pl_objp, flFrametime, Ship_info[shipp->ship_info_index].srotation_time, NULL, NULL, 0.0f, 0, &rvec);
9514
9515                         accelerate_ship(aip, accel_scale * (0.25f + dist_to_goal_point/700.0f));
9516                 } else {
9517                         if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_point, 2.0f)) {
9518                                 return;
9519                         }
9520
9521                         // get max of guard_objp (1) normal speed (2) dock speed
9522                         float speed = guard_objp->phys_info.speed;
9523
9524                         if (guard_objp->type == OBJ_SHIP) {
9525                                 ai_info *guard_aip = &Ai_info[Ships[guard_objp->instance].ai_index];
9526
9527                                 if (guard_aip->dock_objnum != -1) {
9528                                         speed = max(speed, Objects[guard_aip->dock_objnum].phys_info.speed);
9529                                 }
9530                         }
9531                         
9532                         //      Deal with guarding a small object.
9533                         //      If going to guard_vec might cause a collision with guarded object, pick a new guard point.
9534                         if (vm_vec_dot(&v2g, &vec_to_guardobj) > 0.8f) {
9535                                 if (dist_to_guardobj < dist_to_goal_point) {
9536                                         ai_set_guard_vec(Pl_objp, guard_objp);  //      OK to return here.
9537                                         return;
9538                                 }
9539                         } 
9540
9541                         if (speed > 10.0f) {
9542                                 //      If goal ship is moving more than a tiny bit, don't orbit it, get near it.
9543                                 if (vm_vec_dist_quick(&goal_point, &Pl_objp->pos) > 40.0f) {
9544                                         if (vm_vec_dot(&Pl_objp->orient.v.fvec, &v2g) < 0.0f) {
9545                                                 //      Just slow down, don't turn.
9546                                                 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed - dist_to_goal_point/10.0f);
9547                                         } else {
9548                                                 //      Goal point is in front.
9549
9550                                                 //      If close to goal point, don't change direction, just change speed.
9551                                                 if (dist_to_goal_point > Pl_objp->radius + 10.0f) {
9552                                                         turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
9553                                                 }
9554                                                 
9555                                                 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed + (dist_to_goal_point-40.0f)/20.0f);
9556                                         }
9557                                 } else {
9558                                         if (dot_to_goal_point > 0.8f) {
9559                                                 turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
9560                                                 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed + dist_to_goal_point*0.1f);
9561                                         } else {
9562                                                 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed - dist_to_goal_point*0.1f - 1.0f);
9563                                         }
9564                                 }
9565                         // consider guard object STILL
9566                         } else if (guard_objp->radius < 50.0f) {
9567                                 if (dist_to_goal_point > 15.0f) {
9568                                         turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
9569                                         set_accel_for_target_speed(Pl_objp, (dist_to_goal_point-10.0f)/2.0f);
9570                                 } else if (Pl_objp->phys_info.speed < 1.0f) {
9571                                         turn_away_from_point(Pl_objp, &guard_objp->pos, 0.0f);
9572                                 }
9573                                 //      It's a big ship
9574                         } else if (dist_to_guardobj > MAX_GUARD_DIST + Pl_objp->radius + guard_objp->radius) {
9575                                 //      Orbiting ship, too far away
9576                                 float dot = turn_towards_tangent(Pl_objp, &guard_objp->pos, (1.0f + objval/2) * guard_objp->radius);
9577                                 accelerate_ship(aip, (1.0f + dot)/2.0f);
9578                         } else if (dist_to_guardobj < Pl_objp->radius + guard_objp->radius) {
9579                                 //      Orbiting ship, got too close
9580                                 turn_away_from_point(Pl_objp, &guard_objp->pos, 0.0f);
9581                                 if ((dist_to_guardobj > guard_objp->radius + Pl_objp->radius + 50.0f) && (guard_objp->phys_info.speed > Pl_objp->phys_info.speed - 1.0f))
9582                                         change_acceleration(aip, 0.25f);
9583                                 else
9584                                         accelerate_ship(aip, 0.5f + objval/4.0f);
9585                         } else {
9586                                 //      Orbiting ship, about the right distance away.
9587                                 float dot = turn_towards_tangent(Pl_objp, &guard_objp->pos, (1.5f + objval/2.0f)*guard_objp->radius);
9588                                 if ((dist_to_guardobj > guard_objp->radius + Pl_objp->radius + 50.0f) && (guard_objp->phys_info.speed > Pl_objp->phys_info.speed - 1.0f))
9589                                         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));
9590                                 else
9591                                         accelerate_ship(aip, 0.5f * (1.0f + dot) * (0.3f + objval/3.0f));
9592                         }
9593                 }
9594
9595                 //      Periodically, scan for a nearby ship to attack.
9596                 if (((AI_FrameCount ^ (Pl_objp-Objects)) & 0x07) == 0) {
9597                         ai_guard_find_nearby_object();
9598                 }
9599                 break;
9600
9601         case AIS_GUARD_ATTACK:
9602                 //      The guarded ship has been attacked.  Do something useful!
9603                 ai_chase();
9604
9605                 break;
9606         default:
9607                 //Int3();       //      Illegal submode for Guard mode.
9608                 // AL 06/03/97 comment out Int3() to allow milestone to get out the door
9609                 aip->submode = AIS_GUARD_PATROL;
9610                 break;
9611         }
9612
9613 }
9614
9615 // Return the object of the ship that the given object is docked
9616 // with.  Currently, we know a ship is docked when his ai_mode is AIM_DOCK,
9617 // and his submode is AIS_DOCK_3.  I suppose that this is likely to change though.
9618 // Also, the objnum that was is passed in may not be the object that actually
9619 // performed the docking maneuver.  This code will account for that case.
9620 object *ai_find_docked_object( object *docker )
9621 {
9622         ai_info *aip;
9623
9624         // we are trying to find the dockee of docker.  (Note that that these terms
9625         // are totally relative to what is passed in as a parameter.)
9626
9627         // first thing to attempt is to check and see if this object is docked with something.
9628         SDL_assert( docker->type == OBJ_SHIP );         // this had probably better be a ship!!!
9629         aip = &Ai_info[Ships[docker->instance].ai_index];
9630         if ( !(aip->ai_flags & AIF_DOCKED) )            // flag not set if not docked with anything
9631                 return NULL;
9632
9633         if ( aip->dock_objnum == -1 ) {
9634                 Int3();                                                                                 // mwa says this is wrong wrong wrong
9635                 ai_do_objects_undocked_stuff( docker, NULL );
9636                 return NULL;
9637         }
9638
9639         return &Objects[aip->dock_objnum];
9640
9641 }
9642
9643
9644 // define for the points subtracted from score for a rearm started on a player.
9645 #define REPAIR_PENALTY          50
9646
9647
9648 // function to clean up ai flags, variables, and other interesting information
9649 // for a ship that was getting repaired.  The how parameter is useful for multiplayer
9650 // only in that it tells us why the repaired ship is being cleaned up.
9651 void ai_do_objects_repairing_stuff( object *repaired_objp, object *repair_objp, int how )
9652 {
9653         ai_info *aip, *repair_aip;
9654         int             stamp = -1;
9655
9656         SDL_assert( repaired_objp->type == OBJ_SHIP);
9657         aip = &Ai_info[Ships[repaired_objp->instance].ai_index];
9658
9659         // multiplayer
9660         int p_index;
9661         p_index = -1;
9662         if(Game_mode & GM_MULTIPLAYER){
9663                 p_index = multi_find_player_by_object(repaired_objp);           
9664         }               
9665         else {          
9666                 if(repaired_objp == Player_obj){
9667                         p_index = Player_num;
9668                 }
9669         }
9670
9671         switch( how ) {
9672         case REPAIR_INFO_BEGIN:
9673                 aip->ai_flags |= AIF_BEING_REPAIRED;
9674                 aip->ai_flags &= ~AIF_AWAITING_REPAIR;
9675                 stamp = timestamp(-1);
9676
9677                 // if this is a player ship, then subtract the repair penalty from this player's score
9678                 if ( repaired_objp->flags & OF_PLAYER_SHIP ) {
9679                         if ( !(Game_mode & GM_MULTIPLAYER) ) {
9680                                 Player->stats.m_score -= (int)(REPAIR_PENALTY * scoring_get_scale_factor());                    // subtract the penalty
9681                         } else {
9682                                 /*
9683                                 int pnum;
9684
9685                                 // multiplayer game -- find the player, then subtract the score
9686                                 pnum = multi_find_player_by_object( repaired_objp );
9687                                 if ( pnum != -1 ) {
9688                                         Net_players[pnum].player->stats.m_score -= (int)(REPAIR_PENALTY * scoring_get_scale_factor());
9689
9690                                         // squad war
9691                                         multi_team_maybe_add_score(-(int)(REPAIR_PENALTY * scoring_get_scale_factor()), Net_players[pnum].p_info.team);
9692                                 } else {
9693                                         nprintf(("Network", "Couldn't find player for ship %s for repair penalty\n", Ships[repaired_objp->instance].ship_name));
9694                                 }
9695                                 */
9696                         }
9697                 }
9698                 break;
9699
9700         case REPAIR_INFO_BROKEN:
9701                 aip->ai_flags &= ~AIF_BEING_REPAIRED;
9702                 aip->ai_flags |= AIF_AWAITING_REPAIR;
9703                 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9704                 break;
9705
9706         case REPAIR_INFO_END:
9707                 // when only awaiting repair, and the repair is ended, then set dock_objnum to -1.
9708                 if ( aip->ai_flags & AIF_AWAITING_REPAIR ){
9709                         aip->dock_objnum = -1;
9710                 }
9711                 aip->ai_flags &= ~(AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED );
9712                 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9713                 break;
9714
9715         case REPAIR_INFO_QUEUE:
9716                 aip->ai_flags |= AIF_AWAITING_REPAIR;
9717                 if ( aip == Player_ai ){
9718                         hud_support_view_start();
9719                 }
9720                 stamp = timestamp(-1);
9721                 break;
9722
9723         case REPAIR_INFO_ABORT:
9724         case REPAIR_INFO_KILLED:
9725                 // 5/4/98 -- MWA -- Need to set dock objnum to -1 to let code know this guy who was getting
9726                 // repaired (or queued for repair), isn't really going to be docked with anyone anymore.
9727                 aip->dock_objnum = -1;
9728                 aip->ai_flags &= ~AIF_DOCKED;
9729                 aip->ai_flags &= ~(AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED );
9730                 if (repair_objp != NULL) {
9731                         repair_aip = &Ai_info[Ships[repair_objp->instance].ai_index];
9732                         repair_aip->ai_flags &= ~(AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED );
9733                 }               
9734
9735                 if ( p_index >= 0 ) {
9736                         hud_support_view_abort();
9737
9738                         // send appropriate message to player here
9739                         if ( how == REPAIR_INFO_KILLED ){
9740                                 message_send_builtin_to_player( MESSAGE_SUPPORT_KILLED, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_SOON, 0, 0, p_index, -1 );
9741                         } else {
9742                                 if ( repair_objp ){
9743                                         message_send_builtin_to_player( MESSAGE_REPAIR_ABORTED, &Ships[repair_objp->instance], MESSAGE_PRIORITY_NORMAL, MESSAGE_TIME_SOON, 0, 0, p_index, -1 );
9744                                 }
9745                         }
9746                 }
9747
9748                 // add log entry if this is a player
9749                 if ( repaired_objp->flags & OF_PLAYER_SHIP ){
9750                         mission_log_add_entry(LOG_PLAYER_REARM_ABORT, Ships[repaired_objp->instance].ship_name, NULL);
9751                 }
9752
9753                 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9754                 break;
9755
9756         case REPAIR_INFO_COMPLETE:
9757                 // clear the being repaired flag -- and 
9758                 if ( p_index >= 0 ) {
9759                         SDL_assert( repair_objp );
9760                         
9761                         hud_support_view_stop();                        
9762
9763                         message_send_builtin_to_player(MESSAGE_REPAIR_DONE, &Ships[repair_objp->instance], MESSAGE_PRIORITY_LOW, MESSAGE_TIME_SOON, 0, 0, p_index, -1);
9764                 }
9765                 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9766                 break;
9767
9768         case REPAIR_INFO_ONWAY:
9769                 // need to set the dock_signature so that clients in multiplayer games rearm correctly
9770                 SDL_assert( repair_objp );
9771                 aip->dock_signature = repair_objp->signature; 
9772                 aip->dock_objnum = OBJ_INDEX(repair_objp);
9773                 stamp = timestamp(-1);
9774                 break;
9775
9776         default:
9777                 Int3();                 // bogus type of repair info
9778         }
9779
9780         if (repair_objp){
9781                 Ai_info[Ships[repair_objp->instance].ai_index].warp_out_timestamp = stamp;
9782         }
9783
9784         // repair_objp might be NULL is we are cleaning up this mode because of the support ship
9785         // getting killed.
9786         if ( repair_objp ) {
9787                 aip = &Ai_info[Ships[repair_objp->instance].ai_index];
9788                 switch ( how ) {
9789                 case REPAIR_INFO_ONWAY:
9790                         SDL_assert( repaired_objp != NULL );
9791                         aip->goal_objnum = OBJ_INDEX(repaired_objp);
9792                         aip->ai_flags |= AIF_REPAIRING;
9793                         break;
9794
9795                 case REPAIR_INFO_BROKEN:
9796                         break;
9797
9798                 case REPAIR_INFO_END:
9799                 case REPAIR_INFO_ABORT:
9800                 case REPAIR_INFO_KILLED:
9801                         if ( how == REPAIR_INFO_ABORT )
9802                                 aip->goal_objnum = -1;
9803
9804                         aip->ai_flags &= ~AIF_REPAIRING;
9805                         break;
9806                         
9807                 case REPAIR_INFO_QUEUE:
9808                         ai_add_rearm_goal( repaired_objp, repair_objp );
9809                         break;
9810
9811                 case REPAIR_INFO_BEGIN:
9812                 case REPAIR_INFO_COMPLETE:
9813                         break;
9814
9815                 default:
9816                         Int3();         // bogus type of repair info
9817                 }
9818         }
9819
9820         multi_maybe_send_repair_info( repaired_objp, repair_objp, how );
9821 }
9822
9823 //      Cleanup AI stuff for when a ship was supposed to dock with another, but the ship
9824 //      it was supposed to dock with is no longer valid.
9825 void ai_cleanup_dock_mode(ai_info *aip, ship *shipp)
9826 {
9827         object *objp;
9828
9829         objp = &Objects[shipp->objnum];
9830         aip->mode = AIM_NONE;
9831
9832         if (aip->ai_flags & AIF_REPAIRING) {
9833                 SDL_assert( aip->goal_objnum != -1 );
9834                 ai_do_objects_repairing_stuff( &Objects[aip->goal_objnum], &Objects[shipp->objnum], REPAIR_INFO_KILLED );
9835         } else if ( aip->ai_flags & AIF_BEING_REPAIRED ) {
9836                 // MWA -- note that we have to use dock_objnum here instead of goal_objnum.
9837                 SDL_assert( aip->dock_objnum != -1 );
9838                 ai_do_objects_repairing_stuff( &Objects[shipp->objnum], &Objects[aip->dock_objnum], REPAIR_INFO_KILLED );
9839         } else if ( aip->ai_flags & AIF_AWAITING_REPAIR ) {
9840                 // need to find the support ship that has me as a goal_objnum
9841                 // MWA -- note that we have to use dock_objnum here instead of goal_objnum.
9842                 // MWA -- 3/38/98  Check to see if this guy is queued for a support ship, or there is already
9843                 // one in the mission
9844                 if ( mission_is_repair_scheduled(objp) ) {
9845                         mission_remove_scheduled_repair( objp );                        // this function will notify multiplayer clients.
9846                 } else {
9847                         if ( aip->dock_objnum != -1 )
9848                                 ai_do_objects_repairing_stuff( objp, &Objects[aip->dock_objnum], REPAIR_INFO_ABORT );
9849                         else
9850                                 ai_do_objects_repairing_stuff( objp, NULL, REPAIR_INFO_ABORT );
9851                 }
9852         }
9853
9854         if ( aip->ai_flags & AIF_DOCKED ) {
9855                 ai_info *other_aip;
9856
9857                 SDL_assert( aip->dock_objnum != -1 );
9858
9859                 // if docked, and the dock_objnum is not undocking, force them to near last stage
9860                 other_aip = &Ai_info[Ships[Objects[aip->dock_objnum].instance].ai_index];
9861                 if ( (other_aip->mode == AIM_DOCK) && (other_aip->submode < AIS_UNDOCK_3) )
9862                         other_aip->submode = AIS_UNDOCK_3;
9863                 ai_do_objects_undocked_stuff( objp, &Objects[aip->dock_objnum] );
9864         }
9865 }
9866
9867 /*
9868 //      Make dockee_objp shake a bit due to docking.
9869 void ai_dock_shake(object *docker_objp, object *dockee_objp)
9870 {
9871         vector  tangles;
9872         matrix  rotmat, tmp;
9873         float           scale;
9874         angles  *ap;
9875
9876         scale = 0.25f;          //      Compute this based on mass and speed at time of docking.
9877
9878         vm_vec_rand_vec_quick(&tangles);
9879         vm_vec_scale(&tangles, scale);
9880
9881         ap = (angles *) &tangles;
9882
9883         vm_angles_2_matrix(&rotmat, ap);
9884         vm_matrix_x_matrix( &tmp, &dockee_objp->orient, &rotmat );
9885         dockee_objp->orient = tmp;
9886
9887         vm_orthogonalize_matrix(&dockee_objp->orient);
9888
9889         dock_orient_and_approach(docker_objp, dockee_objp, DOA_DOCK_STAY);
9890
9891 }
9892 */
9893
9894 //      Make Pl_objp point at aip->goal_point.
9895 void ai_still()
9896 {
9897         ship    *shipp;
9898         ai_info *aip;
9899
9900         SDL_assert(Pl_objp->type == OBJ_SHIP);
9901         SDL_assert((Pl_objp->instance >= 0) && (Pl_objp->instance < MAX_OBJECTS));
9902
9903         shipp = &Ships[Pl_objp->instance];
9904         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
9905
9906         aip = &Ai_info[shipp->ai_index];
9907
9908         turn_towards_point(Pl_objp, &aip->goal_point, NULL, 0.0f);
9909 }
9910
9911 //      Make *Pl_objp stay near another ship.
9912 void ai_stay_near()
9913 {
9914         ai_info *aip;
9915         int             goal_objnum;
9916
9917         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
9918
9919         goal_objnum = aip->goal_objnum;
9920
9921         if ((goal_objnum < 0) || (Objects[goal_objnum].type != OBJ_SHIP) || (Objects[goal_objnum].signature != aip->goal_signature)) {
9922                 aip->mode = AIM_NONE;
9923         } else {
9924                 float           dist, max_dist, scale;
9925                 vector  rand_vec, goal_pos, vec_to_goal;
9926                 object  *goal_objp;
9927
9928                 goal_objp = &Objects[goal_objnum];
9929
9930                 //      Make not all ships pursue same point.
9931                 static_randvec(Pl_objp-Objects, &rand_vec);
9932
9933                 //      Make sure point is in front hemisphere (relative to Pl_objp's position.
9934                 vm_vec_sub(&vec_to_goal, &goal_objp->pos, &Pl_objp->pos);
9935                 if (vm_vec_dot(&rand_vec, &vec_to_goal) > 1.0f) {
9936                         vm_vec_negate(&rand_vec);
9937                 }
9938
9939                 //      Scale the random vector by an amount proportional to the distance from Pl_objp to the true goal.
9940                 dist = vm_vec_dist_quick(&goal_objp->pos, &Pl_objp->pos);
9941                 max_dist = aip->stay_near_distance;
9942                 scale = dist - max_dist/2;
9943                 if (scale < 0.0f)
9944                         scale = 0.0f;
9945
9946                 vm_vec_scale_add(&goal_pos, &goal_objp->pos, &rand_vec, scale);
9947
9948                 if (max_dist < Pl_objp->radius + goal_objp->radius + 25.0f)
9949                         max_dist = Pl_objp->radius + goal_objp->radius + 25.0f;
9950
9951                 if (dist > max_dist) {
9952                         turn_towards_point(Pl_objp, &goal_pos, NULL, 0.0f);
9953                         accelerate_ship(aip, dist / max_dist - 0.8f);
9954                 }
9955         
9956         }
9957
9958 }
9959
9960 //      Warn player if dock path is obstructed.
9961 int maybe_dock_obstructed(object *cur_objp, object *goal_objp, int big_only_flag)
9962 {
9963         vector  *goalpos, *curpos;
9964         float           radius;
9965         ai_info *aip;
9966         int             collide_objnum;
9967
9968         aip = &Ai_info[Ships[cur_objp->instance].ai_index];
9969
9970         Ai_info[Ships[goal_objp->instance].ai_index].ai_flags &= ~AIF_REPAIR_OBSTRUCTED;
9971
9972         if (goal_objp != Player_obj)
9973                 return -1;
9974
9975         curpos = &cur_objp->pos;
9976         radius = cur_objp->radius;
9977         goalpos = &Path_points[aip->path_cur].pos;
9978         collide_objnum = pp_collide_any(curpos, goalpos, radius, cur_objp, goal_objp, big_only_flag);
9979
9980         if (collide_objnum != -1)
9981                 Ai_info[Ships[goal_objp->instance].ai_index].ai_flags |= AIF_REPAIR_OBSTRUCTED;
9982
9983         return collide_objnum;
9984 }
9985
9986
9987 int Dock_path_warning_given = 0;
9988
9989 //      Docking behavior.
9990 //      Approach a ship, follow path to docking platform, approach platform, after awhile,
9991 //      undock.
9992 void ai_dock()
9993 {
9994         ship                    *shipp = &Ships[Pl_objp->instance];
9995         ai_info         *aip = &Ai_info[shipp->ai_index];
9996         object          *goal_objp;
9997         ship_info       *sip = &Ship_info[shipp->ship_info_index];
9998
9999         //      Make sure object we're supposed to dock with still exists.
10000         if ((aip->goal_objnum == -1) || (Objects[aip->goal_objnum].signature != aip->goal_signature)) {
10001                 ai_cleanup_dock_mode(aip, shipp);
10002                 return;
10003         }
10004
10005         goal_objp = &Objects[aip->goal_objnum];
10006
10007         //      For docking submodes (ie, not undocking), follow path.  Once at second last
10008         //      point on path (point just before point on dock platform), orient into position.
10009         // For undocking, first mode pushes docked ship straight back from docking point
10010         // second mode turns ship and moves to point on docking radius
10011         switch (aip->submode) {
10012
10013                 //      This mode means to find the path to the docking point.
10014         case AIS_DOCK_0:
10015                 //aip->path_start = -1;
10016                 //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10017                 ai_path();
10018                 if (!Dock_path_warning_given && (aip->path_length < 4)) {
10019                         Warning( LOCATION, "Ship '%s' has only %i points on dock path.  Docking will look strange.  Contact Adam.", shipp->ship_name, aip->path_length );
10020                         Dock_path_warning_given = 1;            //      This is on a mission-wide basis, but it's just a hack for now...
10021                 }
10022
10023                 aip->submode = AIS_DOCK_1;
10024                 aip->path_start = -1;
10025                 aip->submode_start_time = Missiontime;
10026                 break;
10027
10028                 //      This mode means to follow the path until just before the end.
10029         case AIS_DOCK_1: {
10030         //      float   dist;
10031                 int     r;
10032
10033                 if ((r = maybe_dock_obstructed(Pl_objp, goal_objp, 1)) != -1) {
10034                         int     r1;
10035                         if ((r1 = maybe_avoid_big_ship(Pl_objp, goal_objp, aip, &goal_objp->pos, 7.0f)) != 0) {
10036                                 nprintf(("AI", "Support ship %s avoiding large ship %s\n", Ships[Pl_objp->instance].ship_name, Ships[Objects[r1].instance].ship_name));
10037                                 break;
10038                         } /*else {
10039                                 nprintf(("AI", "Dock 1: Obstructed by %s\n", Ships[Objects[r].instance].ship_name));
10040                                 accelerate_ship(aip, 0.0f);
10041                                 aip->submode = AIS_DOCK_0;
10042                         } */
10043                 } //else {
10044                 {
10045                         /*dist =*/ ai_path();
10046                         //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10047                         //nprintf(("AI", "Dock 1: Frame: %i, goal point = %i, dist = %7.3f\n", Framecount, aip->path_cur-aip->path_start, dist));
10048
10049                         if (aip->path_cur-aip->path_start >= aip->path_length-1) {              //      If got this far, advance no matter what.
10050                                 aip->submode = AIS_DOCK_2;
10051                                 aip->submode_start_time = Missiontime;
10052                                 aip->path_cur--;
10053                                 SDL_assert(aip->path_cur-aip->path_start >= 0);
10054                         } else if (aip->path_cur-aip->path_start >= aip->path_length-2) {
10055                                 if (Pl_objp->phys_info.speed > goal_objp->phys_info.speed + 1.5f) {
10056                                         set_accel_for_target_speed(Pl_objp, goal_objp->phys_info.speed);
10057                                 } else {
10058                                         aip->submode = AIS_DOCK_2;
10059                                         aip->submode_start_time = Missiontime;
10060                                 }
10061                         }
10062                 }
10063                 break;
10064                                           }
10065         //      This mode means to drag oneself right to the second last point on the path.
10066         //      Path code allows it to overshoot.
10067         case AIS_DOCK_2: {
10068                 float           dist;
10069                 int     r;
10070
10071                 if ((r = maybe_dock_obstructed(Pl_objp, goal_objp,0)) != -1) {
10072                         nprintf(("AI", "Dock 2: Obstructed by %s\n", Ships[Objects[r].instance].ship_name));
10073                         accelerate_ship(aip, 0.0f);
10074                         aip->submode = AIS_DOCK_1;
10075                 } else {
10076                         //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10077                         dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_APPROACH);
10078                         SDL_assert(dist != UNINITIALIZED_VALUE);
10079
10080                         if (dist == DOCK_BACKUP_RETURN_VAL) {
10081                                 int path_num;
10082                                 aip->submode = AIS_DOCK_1;
10083                                 path_num = ai_return_path_num_from_dockbay(&Objects[aip->goal_objnum], aip->dockee_index);
10084                                 SDL_assert(aip->goal_objnum >= 0 && aip->goal_objnum < MAX_OBJECTS);
10085                                 ai_find_path(Pl_objp, aip->goal_objnum, path_num, 0);
10086                                 break;
10087                         }
10088
10089                         //nprintf(("AI", "Dock 2: dist = %7.3f\n", vm_vec_dist_quick(&Pl_objp->pos, &goal_point)));
10090                         float   tolerance;
10091                         if (Objects[aip->goal_objnum].flags & OF_PLAYER_SHIP)
10092                                 tolerance = 6*flFrametime + 1.0f;
10093                         else
10094                                 tolerance = 4*flFrametime + 0.5f;
10095
10096                         if ( dist < tolerance) {
10097                                 aip->submode = AIS_DOCK_3;
10098                                 aip->submode_start_time = Missiontime;
10099                                 aip->path_cur++;
10100                         }
10101                 }
10102                 break;
10103                                                   }
10104
10105         case AIS_DOCK_3:
10106         case AIS_DOCK_3A:
10107                 {
10108                 SDL_assert(aip->goal_objnum != -1);
10109                 int     r;
10110
10111                 if ((r = maybe_dock_obstructed(Pl_objp, goal_objp,0)) != -1) {
10112                         nprintf(("AI", "Dock 1: Obstructed by %s\n", Ships[Objects[r].instance].ship_name));
10113                         accelerate_ship(aip, 0.0f);
10114                         aip->submode = AIS_DOCK_2;
10115                 } else {
10116
10117                         //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10118                         float dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_DOCK);
10119                         SDL_assert(dist != UNINITIALIZED_VALUE);
10120
10121                         if (dist == DOCK_BACKUP_RETURN_VAL) {
10122                                 aip->submode = AIS_DOCK_2;
10123                                 break;
10124                         }
10125
10126                         //nprintf(("AI", "Dock 3: dist = %7.3f\n", dist));
10127
10128                         if (dist < 2*flFrametime * (1.0f + fl_sqrt(goal_objp->phys_info.speed))) {
10129                                 // - Removed by MK on 11/7/97, causes errors for ships docked at mission start: maybe_recreate_path(Pl_objp, aip, 1);
10130                                 dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_DOCK);
10131                                 SDL_assert(dist != UNINITIALIZED_VALUE);
10132
10133                                 physics_ship_init(Pl_objp);
10134
10135                                 ai_do_objects_docked_stuff( Pl_objp, goal_objp );
10136
10137                                 if (aip->submode == AIS_DOCK_3) {
10138                                         snd_play_3d( &Snds[SND_DOCK_ATTACH], &Pl_objp->pos, &View_position );
10139                                         hud_maybe_flash_docking_text(Pl_objp);
10140                                         // ai_dock_shake(Pl_objp, goal_objp);
10141
10142                                         if ((Pl_objp == Player_obj) || (goal_objp == Player_obj))
10143                                                 joy_ff_docked();  // shake player's joystick a little
10144                                 }
10145
10146                                 //      If this ship is repairing another ship...
10147                                 if (aip->ai_flags & AIF_REPAIRING) {
10148                                         aip->submode = AIS_DOCK_4;                      //      Special rearming only dock mode.
10149                                         aip->submode_start_time = Missiontime;
10150                                 } else {
10151                                         aip->submode = AIS_DOCK_4A;
10152                                         aip->submode_start_time = Missiontime;
10153                                 }
10154                         }
10155                 }
10156                 break;
10157                 }
10158
10159                 //      Yes, we just sit here.  We wait for further orders.  No, it's not a bug.
10160         case AIS_DOCK_4A:
10161                 //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10162                 //nprintf(("AI", "."));
10163                 if (aip->active_goal >= 0) {
10164                         mission_log_add_entry(LOG_SHIP_DOCK, Ships[Pl_objp->instance].ship_name, Ships[goal_objp->instance].ship_name);
10165
10166                         if (aip->goals[aip->active_goal].ai_mode == AI_GOAL_DOCK) {
10167                                 ai_mission_goal_complete( aip );                                        // Note, this calls ai_set_default_behavior().
10168                         } 
10169                 } else {        //      Can happen for initially docked ships.
10170                         ai_do_default_behavior( &Objects[Ships[aip->shipnum].objnum] );         // do the default behavior
10171                 }
10172                 
10173                 break;
10174
10175         case AIS_DOCK_4: {
10176                 //      This mode is only for rearming/repairing.
10177                 //      The ship that is performing the rearm enters this mode after it docks.
10178                 SDL_assert((aip->goal_objnum >= -1) && (aip->goal_objnum < MAX_OBJECTS));
10179
10180                 //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10181                 float dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_DOCK);
10182                 SDL_assert(dist != UNINITIALIZED_VALUE);
10183
10184                 object  *goal_objp = &Objects[aip->goal_objnum];
10185                 SDL_assert(goal_objp->type == OBJ_SHIP);
10186                 ship                    *goal_shipp = &Ships[goal_objp->instance];              
10187                 ai_info         *goal_aip = &Ai_info[goal_shipp->ai_index];
10188
10189                 //nprintf(("AI", "Dock 4: dist = %7.3f\n", dist));
10190
10191                 //      Make sure repair has not broken off.
10192                 if (dist > 5.0f) {      //      Oops, too far away!
10193                         if ( goal_aip->ai_flags & AIF_BEING_REPAIRED )
10194                                 ai_do_objects_repairing_stuff( goal_objp, Pl_objp, REPAIR_INFO_BROKEN);
10195
10196                         if (dist > Pl_objp->radius*2 + goal_objp->radius*2) {
10197                                 //      Got real far away from goal, so move back a couple modes and try again.
10198                                 aip->submode = AIS_DOCK_2;
10199                                 aip->submode_start_time = Missiontime;
10200                         }
10201                 } else {
10202                         if ( goal_aip->ai_flags & AIF_AWAITING_REPAIR )
10203                                 ai_do_objects_repairing_stuff( goal_objp, Pl_objp, REPAIR_INFO_BEGIN );
10204                 }
10205
10206                 break;
10207                                                   }
10208
10209         case AIS_UNDOCK_0: {
10210                 int path_num;
10211                 //      First stage of undocking.
10212
10213                 //nprintf(("AI", "Undock 0:\n"));
10214
10215                 aip->submode = AIS_UNDOCK_1;
10216                 aip->submode_start_time = Missiontime;
10217                 if (aip->dock_objnum == -1) {
10218                         aip->submode = AIS_UNDOCK_3;
10219                 } else {
10220
10221                         // set up the path points for the undocking procedure.  dock_path_index member should
10222                         // have gotten set in the docking code.
10223                         SDL_assert( aip->dock_path_index != -1 );
10224                         path_num = ai_return_path_num_from_dockbay(goal_objp, aip->dock_path_index);
10225                         ai_find_path(Pl_objp, goal_objp-Objects, path_num, 0);
10226
10227                         // Play a ship docking detach sound
10228                         snd_play_3d( &Snds[SND_DOCK_DETACH], &Pl_objp->pos, &View_position );
10229                 }
10230                 break;
10231                                                          }
10232         case AIS_UNDOCK_1: {
10233                 //      Using thrusters, exit from dock station to nearest next dock path point.
10234                 float   dist;
10235                 
10236                 //nprintf(("AI", "Undock 1: time in this mode = %7.3f\n", f2fl(Missiontime - aip->submode_start_time)));
10237
10238                 if (Missiontime - aip->submode_start_time < REARM_BREAKOFF_DELAY) {
10239                         break;          //      Waiting for one second to elapse to let detach sound effect play out.
10240                 }
10241                 else {  // AL - added 05/16/97.  Hack to play depart sound.  Will probably take out.
10242                                         // Assumes that the submode_start_time is not used for AIS_UNDOCK_1 anymore
10243                         if ( aip->submode_start_time != 0 )
10244                                 snd_play_3d( &Snds[SND_DOCK_DEPART], &Pl_objp->pos, &View_position );
10245                         aip->submode_start_time = 0;
10246                 }
10247
10248                 dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_UNDOCK_1);
10249                 SDL_assert(dist != UNINITIALIZED_VALUE);
10250
10251                 float dist_to_dock_obj = vm_vec_dist_quick(&Pl_objp->pos, &Objects[aip->goal_objnum].pos);
10252
10253                 //      Move to within 0.1 units of second last point on path before orienting, or just plain far away from docked-to ship.
10254                 //      This allows undock to complete if first ship flies away.
10255                 if ((dist < 2*flFrametime) || (dist_to_dock_obj > 2*Pl_objp->radius)) {
10256                         aip->submode = AIS_UNDOCK_2;
10257                         aip->submode_start_time = Missiontime;
10258                 }
10259                 break;
10260                                                          }
10261         case AIS_UNDOCK_2: {
10262                 float dist;
10263                 //ai_info *other_aip;
10264
10265                 // get pointer to docked object's aip to reset flags, etc
10266                 SDL_assert( aip->dock_objnum != -1 );
10267                 //other_aip = &Ai_info[Ships[Objects[aip->dock_objnum].instance].ai_index];
10268
10269                 //      Second stage of undocking.
10270                 dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_UNDOCK_2);
10271                 SDL_assert(dist != UNINITIALIZED_VALUE);
10272
10273
10274                 //nprintf(("AI", "Undock 2: dist = %7.3f\n", dist));
10275                 
10276                 //      If at goal point, or quite far away from dock object
10277                 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) ) {
10278                         // reset the dock flags.  If rearm/repair, reset rearm repair flags for those ships as well.
10279                         if ( sip->flags & SIF_SUPPORT ) {
10280                                 ai_do_objects_repairing_stuff( &Objects[aip->dock_objnum], Pl_objp, REPAIR_INFO_END );
10281                         }
10282
10283                         // clear out flags for AIF_DOCKED for both objects.
10284                         ai_do_objects_undocked_stuff( Pl_objp, goal_objp );
10285                         physics_ship_init(Pl_objp);
10286                         aip->submode = AIS_UNDOCK_3;                            //      The do-nothing mode, until another order is issued
10287
10288                         //aip->ai_flags &= ~AIF_DOCKED;         //      @MK, 9/18/97
10289                         //other_aip->ai_flags &= ~AIF_DOCKED;
10290                         //aip->dock_objnum = -1;                                        // invalidate who obj is docked with
10291                         //other_aip->dock_objnum = -1;                  // MWA 10/07/97 invalide docked objects dock_objnum value as well
10292
10293                         // don't add undock log entries for support ships.
10294                         if ( !(sip->flags & SIF_SUPPORT) )
10295                                 mission_log_add_entry(LOG_SHIP_UNDOCK, Ships[Pl_objp->instance].ship_name, Ships[goal_objp->instance].ship_name);
10296
10297                 }
10298                 break;
10299                 }
10300         case AIS_UNDOCK_3: {
10301                 float dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_UNDOCK_3);
10302                 SDL_assert(dist != UNINITIALIZED_VALUE);
10303
10304                 if (dist < Pl_objp->radius/2 + 5.0f) {
10305                         aip->submode = AIS_UNDOCK_4;
10306                 }
10307
10308                 // possible that this flag hasn't been cleared yet.  When aborting a rearm, this submode might
10309                 // be entered directly.
10310                 if ( (sip->flags & SIF_SUPPORT) && (aip->ai_flags & AIF_REPAIRING) ) {
10311                         ai_do_objects_repairing_stuff( &Objects[aip->goal_objnum], Pl_objp, REPAIR_INFO_ABORT );
10312                 }
10313
10314                 break;
10315                                                  }
10316         case AIS_UNDOCK_4: {
10317                 //ai_info *other_aip;
10318
10319                 // MWA 10/07/97  I'm slightly confused by the dual use of goal_objnum and dock_objnum.  Seems to me
10320                 // that goal_objnum and dock_objnum are the same through this whole docking/undocking process, although
10321                 // I could be wrong.  dock_objnum was reset in undock_2 submode so try to use goal_objnum here to
10322                 // get other ships ai_info pointer
10323                 //SDL_assert( aip->goal_objnum != -1 );
10324                 //other_aip = &Ai_info[Ships[Objects[aip->goal_objnum].instance].ai_index];
10325
10326                 aip->mode = AIM_NONE;
10327                 aip->dock_path_index = -1;              // invalidate the docking path index
10328
10329                 // these flags should have been cleared long ago!
10330                 // Get Allender if you hit one of these!!!!!
10331                 // removed by allender on 2/16 since a ship may be docked with some other ship, but still be the
10332                 // goal_objnum of this ship ending it's undocking mode.
10333                 //SDL_assert( !(aip->ai_flags & AIF_DOCKED) );
10334                 //SDL_assert( !(other_aip->ai_flags & AIF_DOCKED) );
10335                 //SDL_assert( !(aip->ai_flags & AIF_REPAIRING) );
10336                 //SDL_assert( !(other_aip->ai_flags & AIF_BEING_REPAIRED) );
10337                 //SDL_assert( !(other_aip->ai_flags & AIF_AWAITING_REPAIR) );
10338
10339                 // only call mission goal complete if this was indeed an undock goal
10340                 if ( aip->active_goal > -1 ) {
10341                         if ( aip->goals[aip->active_goal].ai_mode == AI_GOAL_UNDOCK )
10342                                 ai_mission_goal_complete( aip );                        // this call should reset the AI mode
10343                         //else
10344                         //      aip->active_goal = -1;                                          // this ensures that this ship might get new goal
10345                 }
10346
10347                 break;
10348                                                          }
10349         default:
10350                 Int3(); //      Error, bogus submode
10351         }
10352
10353 }
10354
10355 // TURRET BEGIN
10356
10357 //      Given an object and a turret on that object, return the global position and forward vector
10358 //      of the turret.   The gun normal is the unrotated gun normal, (the center of the FOV cone), not
10359 // the actual gun normal given using the current turret heading.  But it _is_ rotated into the model's orientation
10360 //      in global space.
10361 void ship_get_global_turret_info(object *objp, model_subsystem *tp, vector *gpos, vector *gvec)
10362 {
10363         matrix  m;
10364         vm_copy_transpose_matrix(&m, &objp->orient);
10365 //      vm_vec_rotate(gpos, &tp->turret_avg_firing_point, &m);
10366         vm_vec_rotate(gpos, &tp->pnt, &m);
10367         vm_vec_add2(gpos, &objp->pos);
10368         vm_vec_rotate(gvec, &tp->turret_norm, &m);      
10369 }
10370
10371 // Given an object and a turret on that object, return the actual firing point of the gun
10372 // and its normal.   This uses the current turret angles.  We are keeping track of which
10373 // gun to fire next in the ship specific info for this turret subobject.  Use this info
10374 // to determine which position to fire from next.
10375 //      Stuffs:
10376 //              *gpos: absolute position of gun firing point
10377 //              *gvec: vector fro *gpos to *targetp
10378 void ship_get_global_turret_gun_info(object *objp, ship_subsys *ssp, vector *gpos, vector *gvec, int use_angles, vector *targetp)
10379 {
10380         vector * gun_pos;
10381         model_subsystem *tp = ssp->system_info;
10382
10383         ship_model_start(objp);
10384
10385         gun_pos = &tp->turret_firing_point[ssp->turret_next_fire_pos % tp->turret_num_firing_points];
10386
10387         model_find_world_point(gpos, gun_pos, tp->model_num, tp->turret_gun_sobj, &objp->orient, &objp->pos );
10388
10389         if (use_angles)
10390                 model_find_world_dir(gvec, &tp->turret_norm, tp->model_num, tp->turret_gun_sobj, &objp->orient, &objp->pos );
10391         else {
10392                 //vector        gun_pos2;
10393                 //vm_vec_add(&gun_pos2, gpos, gun_pos);
10394                 vm_vec_normalized_dir(gvec, targetp, gpos);
10395         }
10396
10397         ship_model_stop(objp);  
10398 }
10399
10400 //      Rotate a turret towards an enemy.
10401 //      Return TRUE if caller should use angles in subsequent rotations.
10402 //      Some obscure model thing only John Slagel knows about.
10403 //      Sets predicted enemy position.
10404 //      If the turret (*ss) has a subsystem targeted, the subsystem is used as the predicted point.
10405 int aifft_rotate_turret(ship *shipp, int parent_objnum, ship_subsys *ss, object *objp, object *lep, vector *predicted_enemy_pos, vector *gvec)
10406 {
10407         if (ss->turret_enemy_objnum != -1)      {
10408                 model_subsystem *tp = ss->system_info;
10409                 vector  gun_pos, gun_vec;
10410                 float           weapon_speed;
10411                 float           weapon_system_strength;
10412
10413                 //      weapon_system_strength scales time enemy in range in 0..1.  So, the lower this is, the worse the aiming will be.
10414                 weapon_system_strength = ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS);
10415
10416                 ship_get_global_turret_info(&Objects[parent_objnum], tp, &gun_pos, &gun_vec);
10417
10418                 weapon_speed = Weapon_info[tp->turret_weapon_type].max_speed;
10419                 float weapon_travel_dist = weapon_speed * Weapon_info[tp->turret_weapon_type].lifetime;
10420
10421                 vector  enemy_point;
10422                 if (ss->targeted_subsys != NULL) {
10423                         if (ss->turret_enemy_objnum != -1) {
10424                                 vm_vec_unrotate(&enemy_point, &ss->targeted_subsys->system_info->pnt, &Objects[ss->turret_enemy_objnum].orient);
10425                                 vm_vec_add2(&enemy_point, &Objects[ss->turret_enemy_objnum].pos);
10426                         }
10427                 } else {
10428                         if ((lep->type == OBJ_SHIP) && (Ship_info[Ships[lep->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
10429                                 ai_big_pick_attack_point_turret(lep, ss, &gun_pos, &gun_vec, &enemy_point, tp->turret_fov, min(weapon_travel_dist, Weapon_info[tp->turret_weapon_type].weapon_range));
10430                         } else {
10431                                 enemy_point = lep->pos;
10432                         }
10433                 }
10434
10435                 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);
10436
10437                 if (weapon_system_strength < 0.7f) {
10438                         vector  rand_vec;
10439
10440                         static_randvec(Missiontime >> 18, &rand_vec);   //      Return same random number for two seconds.
10441                         //      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.
10442                         vm_vec_scale_add2(predicted_enemy_pos, &rand_vec, (1.0f - weapon_system_strength)*1.5f * lep->radius);
10443                 }
10444
10445                 vector  v2e;
10446                 vm_vec_normalized_dir(&v2e, predicted_enemy_pos, &gun_pos);
10447                 if (vm_vec_dot(&v2e, gvec) > tp->turret_fov) {
10448                         model_rotate_gun(shipp->modelnum, ss->system_info, &Objects[parent_objnum].orient,
10449                                 &ss->submodel_info_1.angs, &ss->submodel_info_2.angs,
10450                                 &Objects[parent_objnum].pos, predicted_enemy_pos);
10451                 }
10452         }
10453
10454         return 0;
10455 }
10456
10457 //      Determine if subsystem *enemy_subsysp is hittable from objp.
10458 //      If so, return dot product of vector from point abs_gunposp to *enemy_subsysp
10459 float   aifft_compute_turret_dot(object *objp, object *enemy_objp, vector *abs_gunposp, ship_subsys *turret_subsysp, ship_subsys *enemy_subsysp)
10460 {
10461         float   dot_out;
10462         vector  subobj_pos, vector_out;
10463
10464         vm_vec_unrotate(&subobj_pos, &enemy_subsysp->system_info->pnt, &enemy_objp->orient);
10465         vm_vec_add2(&subobj_pos, &enemy_objp->pos);
10466
10467         if (ship_subsystem_in_sight(enemy_objp, enemy_subsysp, abs_gunposp, &subobj_pos, 1, &dot_out, &vector_out)) {
10468                 vector  turret_norm;
10469
10470                 vm_vec_rotate(&turret_norm, &turret_subsysp->system_info->turret_norm, &objp->orient);
10471                 return vm_vec_dot(&turret_norm, &vector_out);
10472         } else
10473                 return -1.0f;
10474
10475 }
10476
10477 #define MAX_AIFFT_TURRETS                       60
10478 ship_subsys *aifft_list[MAX_AIFFT_TURRETS];
10479 float aifft_rank[MAX_AIFFT_TURRETS];
10480 int aifft_list_size = 0;
10481 int aifft_max_checks = 5;
10482 DCF(mf, "")
10483 {
10484         dc_get_arg(ARG_INT);
10485         aifft_max_checks = Dc_arg_int;
10486 }
10487
10488
10489 //      Pick a subsystem to attack on enemy_objp.
10490 //      Only pick one if enemy_objp is a big ship or a capital ship.
10491 //      Returns dot product from turret to subsystem in *dot_out
10492 ship_subsys *aifft_find_turret_subsys(object *objp, ship_subsys *ssp, object *enemy_objp, float *dot_out)
10493 {
10494         ship    *eshipp;
10495         ship_info       *esip;
10496         ship_subsys     *best_subsysp = NULL;
10497         float dot;
10498
10499         SDL_assert(enemy_objp->type == OBJ_SHIP);
10500
10501         eshipp = &Ships[enemy_objp->instance];
10502         esip = &Ship_info[eshipp->ship_info_index];
10503
10504         float   best_dot = 0.0f;
10505         *dot_out = best_dot;
10506
10507         //      Compute absolute gun position.
10508         vector  abs_gun_pos;
10509         vm_vec_unrotate(&abs_gun_pos, &ssp->system_info->pnt, &objp->orient);
10510         vm_vec_add2(&abs_gun_pos, &objp->pos);
10511
10512         //      Only pick a turret to attack on large ships.
10513         if (!(esip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)))
10514                 return best_subsysp;
10515
10516         // Make sure big or huge ship *actually* has subsystems  (ie, knossos)
10517         if (esip->n_subsystems == 0) {
10518                 return best_subsysp;
10519         }
10520
10521         // first build up a list subsystems to traverse
10522         ship_subsys     *pss;
10523         aifft_list_size = 0;
10524         for ( pss = GET_FIRST(&eshipp->subsys_list); pss !=END_OF_LIST(&eshipp->subsys_list); pss = GET_NEXT(pss) ) {
10525                 model_subsystem *psub = pss->system_info;
10526
10527                 // if we've reached max turrets bail
10528                 if(aifft_list_size >= MAX_AIFFT_TURRETS){
10529                         break;
10530                 }
10531
10532                 // Don't process destroyed objects
10533                 if ( pss->current_hits <= 0.0f ){
10534                         continue;
10535                 }
10536                 
10537                 switch (psub->type) {
10538                 case SUBSYSTEM_WEAPONS:
10539                         aifft_list[aifft_list_size] = pss;
10540                         aifft_rank[aifft_list_size++] = 1.4f;
10541                         break;
10542
10543                 case SUBSYSTEM_TURRET:
10544                         aifft_list[aifft_list_size] = pss;
10545                         aifft_rank[aifft_list_size++] = 1.2f;
10546                         break;
10547
10548                 case SUBSYSTEM_SENSORS:
10549                 case SUBSYSTEM_ENGINE:
10550                         aifft_list[aifft_list_size] = pss;
10551                         aifft_rank[aifft_list_size++] = 1.0f;
10552                         break;
10553                 }
10554         }
10555
10556         // DKA:  6/28/99 all subsystems can be destroyed.
10557         //SDL_assert(aifft_list_size > 0);
10558         if (aifft_list_size == 0) {
10559                 return best_subsysp;
10560         }
10561
10562         // determine a stride value so we're not checking too many turrets
10563         int stride = aifft_list_size > aifft_max_checks ? aifft_list_size / aifft_max_checks : 1;
10564         if(stride <= 0){
10565                 stride = 1;
10566         }
10567         int offset = (int)frand_range(0.0f, (float)(aifft_list_size % stride));
10568         int idx;
10569         for(idx=offset; idx<aifft_list_size; idx+=stride){
10570                 dot = aifft_compute_turret_dot(objp, enemy_objp, &abs_gun_pos, ssp, aifft_list[idx]);                   
10571
10572                 if (dot* aifft_rank[idx] > best_dot) {
10573                         best_dot = dot*aifft_rank[idx];
10574                         best_subsysp = aifft_list[idx];
10575                 }
10576         }
10577
10578         SDL_assert(best_subsysp != &eshipp->subsys_list);
10579
10580         *dot_out = best_dot;
10581         return best_subsysp;
10582 }
10583
10584 // Set active weapon for turret
10585 void ai_turret_select_default_weapon(ship_subsys *turret)
10586 {
10587         ship_weapon *twp;
10588
10589         twp = &turret->weapons;
10590
10591         // If a primary weapon is available, select it
10592         if ( twp->num_primary_banks > 0 ) {
10593                 turret->system_info->turret_weapon_type = twp->primary_bank_weapons[0];
10594         } else if ( twp->num_secondary_banks > 0 ) {
10595                 turret->system_info->turret_weapon_type = twp->secondary_bank_weapons[0];
10596         }
10597 }
10598
10599 // return !0 if the specified target should scan for a new target, otherwise return 0
10600 int turret_should_pick_new_target(ship_subsys *turret)
10601 {
10602 //      int target_type;
10603
10604         if ( timestamp_elapsed(turret->turret_next_enemy_check_stamp) ) {
10605                 return 1;
10606         }
10607
10608         return 0;
10609
10610 /*
10611         if ( turret->turret_enemy_objnum == -1 ) {
10612                 return 1;
10613         }
10614                 
10615         target_type = Objects[turret->turret_enemy_objnum].type;
10616         if ( (target_type != OBJ_SHIP) && (target_type != OBJ_ASTEROID) ) {
10617                 return 1;
10618         }
10619
10620         return 0;
10621 */
10622 }
10623
10624 // Set the next fire timestamp for a turret, based on weapon type and ai class
10625 void turret_set_next_fire_timestamp(ship_subsys *turret, ai_info *aip)
10626 {
10627         float   wait;
10628         int     weapon_id;
10629
10630         weapon_id = turret->system_info->turret_weapon_type;
10631
10632         wait = Weapon_info[weapon_id].fire_wait * 1000.0f;
10633
10634         // make side even for team vs. team
10635         if ((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_TEAM)) {
10636                 // flak guns need to fire more rapidly
10637                 if (Weapon_info[weapon_id].wi_flags & WIF_FLAK) {
10638                         wait *= Ship_fire_delay_scale_friendly[Game_skill_level] * 0.5f;
10639                         wait += (Num_ai_classes - aip->ai_class - 1) * 40.0f;
10640                 } else {
10641                         wait *= Ship_fire_delay_scale_friendly[Game_skill_level];
10642                         wait += (Num_ai_classes - aip->ai_class - 1) * 100.0f;
10643                 }
10644         } else {
10645                 // flak guns need to fire more rapidly
10646                 if (Weapon_info[weapon_id].wi_flags & WIF_FLAK) {
10647                         if (Ships[aip->shipnum].team == TEAM_FRIENDLY) {
10648                                 wait *= Ship_fire_delay_scale_friendly[Game_skill_level] * 0.5f;
10649                         } else {
10650                                 wait *= Ship_fire_delay_scale_hostile[Game_skill_level] * 0.5f;
10651                         }       
10652                         wait += (Num_ai_classes - aip->ai_class - 1) * 40.0f;
10653
10654                 } else if (Weapon_info[weapon_id].wi_flags & WIF_HUGE) {
10655                         // make huge weapons fire independently of team
10656                         wait *= Ship_fire_delay_scale_friendly[Game_skill_level];
10657                         wait += (Num_ai_classes - aip->ai_class - 1) * 100.0f;
10658                 } else {
10659                         // give team friendly an advantage
10660                         if (Ships[aip->shipnum].team == TEAM_FRIENDLY) {
10661                                 wait *= Ship_fire_delay_scale_friendly[Game_skill_level];
10662                         } else {
10663                                 wait *= Ship_fire_delay_scale_hostile[Game_skill_level];
10664                         }       
10665                         wait += (Num_ai_classes - aip->ai_class - 1) * 100.0f;
10666                 }
10667         }
10668
10669         // vary wait time +/- 10%
10670         wait *= frand_range(0.9f, 1.1f);
10671         turret->turret_next_fire_stamp = timestamp((int) wait);
10672 }
10673
10674 // Decide  if a turret should launch an aspect seeking missile
10675 int turret_should_fire_aspect(ship_subsys *turret, float dot, int weapon_class)
10676 {
10677         weapon_info *wip;
10678
10679         wip = &Weapon_info[weapon_class];
10680
10681         if ( (dot > AICODE_TURRET_DUMBFIRE_ANGLE) && (turret->turret_time_enemy_in_range >= min(wip->min_lock_time,AICODE_TURRET_MAX_TIME_IN_RANGE)) ) {
10682                 return 1;
10683         }
10684
10685         return 0;
10686 }
10687
10688 // Update how long current target has been in this turrets range
10689 void turret_update_enemy_in_range(ship_subsys *turret, float seconds)
10690 {
10691         turret->turret_time_enemy_in_range += seconds;
10692
10693         if ( turret->turret_time_enemy_in_range < 0.0f ) {
10694                 turret->turret_time_enemy_in_range = 0.0f;
10695         }
10696
10697         if ( turret->turret_time_enemy_in_range > AICODE_TURRET_MAX_TIME_IN_RANGE ) {
10698                 turret->turret_time_enemy_in_range = AICODE_TURRET_MAX_TIME_IN_RANGE;
10699         }
10700 }
10701
10702
10703
10704 // Fire a weapon from a turret
10705 void turret_fire_weapon(ship_subsys *turret, int parent_objnum, vector *turret_pos, vector *turret_fvec, vector *predicted_pos = NULL)
10706 {
10707         matrix  turret_orient;
10708         int             turret_weapon_class, weapon_objnum;
10709         ai_info *parent_aip;
10710         ship            *parent_ship;
10711         beam_fire_info fire_info;
10712         float flak_range = 0.0f;
10713
10714         parent_aip = &Ai_info[Ships[Objects[parent_objnum].instance].ai_index];
10715         parent_ship = &Ships[Objects[parent_objnum].instance];
10716         turret_weapon_class = turret->system_info->turret_weapon_type;
10717
10718         if (check_ok_to_fire(parent_objnum, turret->turret_enemy_objnum, &Weapon_info[turret_weapon_class])) {
10719                 vm_vector_2_matrix(&turret_orient, turret_fvec, NULL, NULL);
10720                 turret->turret_last_fire_direction = *turret_fvec;
10721
10722                 // set next fire timestamp for the turret
10723                 turret_set_next_fire_timestamp(turret, parent_aip);
10724
10725                 // if this weapon is a beam weapon, handle it specially
10726                 if(Weapon_info[turret_weapon_class].wi_flags & WIF_BEAM){
10727                         // if this beam isn't free to fire
10728                         if (!(turret->weapons.flags & SW_FLAG_BEAM_FREE)) {
10729                                 Int3(); // should never get this far
10730                                 return;
10731                         }
10732
10733                         // stuff beam firing info
10734                         memset(&fire_info, 0, sizeof(beam_fire_info));
10735                         fire_info.accuracy = 1.0f;
10736                         fire_info.beam_info_index = turret_weapon_class;
10737                         fire_info.beam_info_override = NULL;
10738                         fire_info.shooter = &Objects[parent_objnum];
10739                         fire_info.target = &Objects[turret->turret_enemy_objnum];
10740                         fire_info.target_subsys = NULL;
10741                         fire_info.turret = turret;
10742
10743                         // fire a beam weapon
10744                         beam_fire(&fire_info);
10745                 } else {
10746
10747                         // don't fire swarm, but set up swarm info
10748                         if (Weapon_info[turret_weapon_class].wi_flags & WIF_SWARM) {
10749                                 turret_swarm_set_up_info(parent_objnum, turret, turret_weapon_class);
10750                                 return;
10751                         } else {
10752                                 weapon_objnum = weapon_create( turret_pos, &turret_orient, turret_weapon_class, parent_objnum, 0, -1, 1);
10753                                 weapon_set_tracking_info(weapon_objnum, parent_objnum, turret->turret_enemy_objnum, 1, turret->targeted_subsys);                
10754                         }
10755
10756                         //nprintf(("AI", "Turret_time_enemy_in_range = %7.3f\n", ss->turret_time_enemy_in_range));              
10757                         if (weapon_objnum != -1) {
10758                                 Weapons[Objects[weapon_objnum].instance].target_num = turret->turret_enemy_objnum;
10759                                 // AL 1-6-97: Store pointer to turret subsystem
10760                                 Weapons[Objects[weapon_objnum].instance].turret_subsys = turret;
10761
10762                                 if ( Weapon_info[turret_weapon_class].launch_snd != -1 ) {
10763                                         // Don't play turret firing sound if turret sits on player ship... it gets annoying.
10764                                         if ( parent_objnum != OBJ_INDEX(Player_obj) ) {                                         
10765                                                 snd_play_3d( &Snds[Weapon_info[turret_weapon_class].launch_snd], turret_pos, &View_position );                                          
10766                                         }
10767                                 }               
10768
10769                                 // if the gun is a flak gun
10770                                 if(Weapon_info[turret_weapon_class].wi_flags & WIF_FLAK){                       
10771                                         // show a muzzle flash
10772                                         flak_muzzle_flash(turret_pos, turret_fvec, turret_weapon_class);
10773
10774                                         // pick a firing range so that it detonates properly                    
10775                                         flak_pick_range(&Objects[weapon_objnum], predicted_pos, ship_get_subsystem_strength(parent_ship, SUBSYSTEM_WEAPONS));
10776
10777                                         // determine what that range was
10778                                         flak_range = flak_get_range(&Objects[weapon_objnum]);
10779                                 }
10780
10781                                 // in multiplayer (and the master), then send a turret fired packet.
10782                                 if ( MULTIPLAYER_MASTER && (weapon_objnum != -1) ) {
10783                                         int subsys_index;
10784
10785                                         subsys_index = ship_get_index_from_subsys(turret, parent_objnum );
10786                                         SDL_assert( subsys_index != -1 );
10787                                         if(Weapon_info[turret_weapon_class].wi_flags & WIF_FLAK){                       
10788                                                 send_flak_fired_packet( parent_objnum, subsys_index, weapon_objnum, flak_range );
10789                                         } else {
10790                                                 send_turret_fired_packet( parent_objnum, subsys_index, weapon_objnum );
10791                                         }
10792                                 }
10793                         }
10794                 }
10795         } else {
10796                 float wait = 1000.0f * frand_range(0.9f, 1.1f);
10797                 turret->turret_next_fire_stamp = timestamp((int) wait);
10798         }
10799 }
10800
10801 void turret_swarm_fire_from_turret(ship_subsys *turret, int parent_objnum, int target_objnum, ship_subsys *target_subsys)
10802 {
10803         int turret_weapon_class, weapon_objnum;
10804         matrix turret_orient;
10805         vector turret_pos, turret_fvec;
10806
10807         // parent not alive, quick out.
10808         if (Objects[parent_objnum].type != OBJ_SHIP) {
10809                 return;
10810         }
10811
10812         //      change firing point
10813         ship_get_global_turret_gun_info(&Objects[parent_objnum], turret, &turret_pos, &turret_fvec, 1, NULL);
10814         turret->turret_next_fire_pos++;
10815
10816         // get class [index into Weapon_info array
10817         turret_weapon_class = turret->system_info->turret_weapon_type;
10818         SDL_assert(Weapon_info[turret_weapon_class].wi_flags & WIF_SWARM);
10819
10820         // make turret_orient from turret_fvec -- turret->turret_last_fire_direction
10821         vm_vector_2_matrix(&turret_orient, &turret_fvec, NULL, NULL);
10822
10823         // create weapon and homing info
10824         weapon_objnum = weapon_create(&turret_pos, &turret_orient, turret_weapon_class, parent_objnum, 0, -1, 1);
10825         weapon_set_tracking_info(weapon_objnum, parent_objnum, target_objnum, 1, target_subsys);
10826
10827         // do other cool stuff if weapon is created.
10828         if (weapon_objnum > -1) {
10829                 Weapons[Objects[weapon_objnum].instance].turret_subsys = turret;
10830                 Weapons[Objects[weapon_objnum].instance].target_num = turret->turret_enemy_objnum;
10831
10832                 // maybe sound
10833                 if ( Weapon_info[turret_weapon_class].launch_snd != -1 ) {
10834                         // Don't play turret firing sound if turret sits on player ship... it gets annoying.
10835                         if ( parent_objnum != OBJ_INDEX(Player_obj) ) {
10836                                 snd_play_3d( &Snds[Weapon_info[turret_weapon_class].launch_snd], &turret_pos, &View_position );
10837                         }
10838                 }
10839                 
10840                 // in multiplayer (and the master), then send a turret fired packet.
10841                 if ( MULTIPLAYER_MASTER && (weapon_objnum != -1) ) {
10842                         int subsys_index;
10843
10844                         subsys_index = ship_get_index_from_subsys(turret, parent_objnum );
10845                         SDL_assert( subsys_index != -1 );
10846                         send_turret_fired_packet( parent_objnum, subsys_index, weapon_objnum );
10847                 }
10848         }
10849 }
10850
10851 int Num_ai_firing = 0;
10852 int Num_find_turret_enemy = 0;
10853 int Num_turrets_fired = 0;
10854 //      Given a turret tp and its parent parent_objnum, fire from the turret at its enemy.
10855 void ai_fire_from_turret(ship *shipp, ship_subsys *ss, int parent_objnum)
10856 {
10857         float           weapon_firing_range;
10858         vector  v2e;
10859         object  *lep;           //      Last enemy pointer
10860         model_subsystem *tp = ss->system_info;
10861         int             use_angles, turret_weapon_class;
10862         vector  predicted_enemy_pos;
10863         object  *objp;
10864         ai_info *aip;
10865
10866         if (!Ai_firing_enabled) {
10867                 return;
10868         }
10869
10870         if (ss->current_hits < 0.0f) {
10871                 return;
10872         }
10873
10874         if ( ship_subsys_disrupted(ss) ){               // AL 1/19/98: Make sure turret isn't suffering disruption effects
10875                 return;
10876         }
10877
10878         // Check turret free
10879         if (ss->weapons.flags & SW_FLAG_TURRET_LOCK) {
10880                 return;
10881         }
10882
10883         // If beam weapon, check beam free
10884         if ( (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM) && !(ss->weapons.flags & SW_FLAG_BEAM_FREE) ) {
10885                 return;
10886         }
10887
10888         SDL_assert( shipp->objnum == parent_objnum );
10889
10890         if ( tp->turret_weapon_type < 0 ){
10891                 return;
10892         }
10893
10894         // Monitor number of calls to ai_fire_from_turret
10895         Num_ai_firing++;
10896
10897         turret_weapon_class = tp->turret_weapon_type;
10898
10899         // AL 09/14/97: ensure ss->turret_enemy_objnum != -1 before setting lep
10900         if ( (ss->turret_enemy_objnum >= 0 && ss->turret_enemy_objnum < MAX_OBJECTS) && (ss->turret_enemy_sig == Objects[ss->turret_enemy_objnum].signature)) {
10901                 lep = &Objects[ss->turret_enemy_objnum];
10902
10903                 // MK -- here is where turret is targeting a bomb.  I simply return for now.  We should force
10904                 // a target change -- or better yet, never pick a weapon when this turret has a "huge" weapon
10905                 // loaded.
10906
10907                 // we only care about targets which are ships.
10908                 //if ( lep->type != OBJ_SHIP )
10909                 //      return;
10910
10911                 //      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.
10912                 if ( Weapon_info[turret_weapon_class].wi_flags & WIF_HUGE ) {
10913                         if ( lep->type != OBJ_SHIP ) {
10914                                 return;
10915                         }
10916                         if ( !(Ship_info[Ships[lep->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) ) {
10917                                 return;
10918                         }
10919                 }
10920
10921                 // If targeting protected or beam protected ship, don't fire.  Reset enemy objnum
10922                 if (lep->type == OBJ_SHIP) {
10923                         // Check if we're targeting a protected ship
10924                         if (lep->flags & OF_PROTECTED) {
10925                                 ss->turret_enemy_objnum = -1;
10926                                 ss->turret_time_enemy_in_range = 0.0f;
10927                                 return;
10928                         }
10929
10930                         // Check if we're targeting a beam protected ship with a beam weapon
10931                         if ( (lep->flags & OF_BEAM_PROTECTED) && (Weapon_info[turret_weapon_class].wi_flags & WIF_BEAM) ) {
10932                                 ss->turret_enemy_objnum = -1;
10933                                 ss->turret_time_enemy_in_range = 0.0f;
10934                                 return;
10935                         }
10936                 }
10937         } else {
10938                 ss->turret_enemy_objnum = -1;
10939                 lep = NULL;
10940         }
10941         
10942         SDL_assert((parent_objnum >= 0) && (parent_objnum < MAX_OBJECTS));
10943         objp = &Objects[parent_objnum];
10944         SDL_assert(objp->type == OBJ_SHIP);
10945         aip = &Ai_info[Ships[objp->instance].ai_index];
10946
10947         // Use the turret info for all guns, not one gun in particular.
10948         vector   gvec, gpos;
10949         ship_get_global_turret_info(&Objects[parent_objnum], tp, &gpos, &gvec);
10950
10951         // Rotate the turret even if time hasn't elapsed, since it needs to turn to face its target.
10952         use_angles = aifft_rotate_turret(shipp, parent_objnum, ss, objp, lep, &predicted_enemy_pos, &gvec);
10953
10954         if ( !timestamp_elapsed(ss->turret_next_fire_stamp)){
10955                 return;
10956         }
10957
10958         // Don't try to fire beyond weapon_limit_range
10959         weapon_firing_range = min(Weapon_info[tp->turret_weapon_type].lifetime * Weapon_info[tp->turret_weapon_type].max_speed, Weapon_info[tp->turret_weapon_type].weapon_range);
10960
10961         // if beam weapon in nebula and target not tagged, decrase firing range
10962         extern int Nebula_sec_range;
10963         if (Weapon_info[turret_weapon_class].wi_flags & WIF_BEAM) {
10964                 if ( !((shipp->tag_left > 0) || (shipp->level2_tag_left > 0)) ) {
10965                         if (Nebula_sec_range) {
10966                                 weapon_firing_range *= float(BEAM_NEBULA_RANGE_REDUCE_FACTOR);
10967                         }
10968                 }
10969         }
10970
10971         if (ss->turret_enemy_objnum != -1) {
10972                 float dist_to_enemy = vm_vec_normalized_dir(&v2e, &predicted_enemy_pos, &gpos) - lep->radius;
10973                 if (dist_to_enemy > weapon_firing_range) {
10974                         ss->turret_enemy_objnum = -1;           //      Force picking of new enemy.
10975                 }
10976         }
10977
10978         // Turret spawn weapons are a special case.  They fire if there are enough enemies in the 
10979         // immediate area (not necessarily in the turret fov).
10980         if ( Weapon_info[turret_weapon_class].wi_flags & WIF_SPAWN ) {
10981                 int num_ships_nearby;
10982                 num_ships_nearby = num_nearby_fighters(get_enemy_team_mask(parent_objnum), &gpos, 1500.0f);
10983                 if (( num_ships_nearby >= 3 ) || ((num_ships_nearby >= 2) && (frand() < 0.1f))) {
10984                         turret_fire_weapon(ss, parent_objnum, &gpos, &ss->turret_last_fire_direction);
10985                 } else {
10986                         ss->turret_next_fire_stamp = timestamp(1000);   //      Regardless of firing rate, don't check whether should fire for awhile.
10987                 }
10988                 return;
10989         }
10990
10991         //      Maybe pick a new enemy.
10992         if ( turret_should_pick_new_target(ss) ) {
10993                 Num_find_turret_enemy++;
10994                 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);
10995                 SDL_assert(objnum < 0 || is_target_beam_valid(ss, objnum));
10996
10997                 if (objnum != -1) {
10998                         if (ss->turret_enemy_objnum == -1) {
10999                                 ss->turret_enemy_objnum = objnum;
11000                                 ss->turret_enemy_sig = Objects[objnum].signature;
11001                                 // why return?
11002                                 return;
11003                         } else {
11004                                 ss->turret_enemy_objnum = objnum;
11005                                 ss->turret_enemy_sig = Objects[objnum].signature;
11006                         }
11007                 } else {
11008                         ss->turret_enemy_objnum = -1;
11009                 }
11010
11011                 if (ss->turret_enemy_objnum != -1) {
11012                         float   dot = 1.0f;
11013                         lep = &Objects[ss->turret_enemy_objnum];
11014                         if ( lep->type == OBJ_SHIP ) {
11015                                 ss->targeted_subsys = aifft_find_turret_subsys(objp, ss, lep, &dot);                            
11016                         }
11017                         ss->turret_next_enemy_check_stamp = timestamp((int) (max(dot, 0.5f)*2000.0f) + 1000);
11018                 } else {
11019                         ss->turret_next_enemy_check_stamp = timestamp((int) (2000.0f * frand_range(0.9f, 1.1f)));       //      Check every two seconds
11020                 }
11021         }
11022
11023         //      If still don't have an enemy, return.  Or, if enemy is protected, return.
11024         if (ss->turret_enemy_objnum != -1) {
11025                 //      Don't shoot at ship we're going to dock with.
11026                 if (ss->turret_enemy_objnum == aip->dock_objnum) {
11027                         ss->turret_enemy_objnum = -1;
11028                         return;
11029                 }
11030
11031                 if (Objects[ss->turret_enemy_objnum].flags & OF_PROTECTED) {
11032                         //      This can happen if the enemy was selected before it became protected.
11033                         ss->turret_enemy_objnum = -1;
11034                         return;
11035                 }
11036                 lep = &Objects[ss->turret_enemy_objnum];
11037         } else {
11038                 if (timestamp_until(ss->turret_next_fire_stamp) < 500) {
11039                         ss->turret_next_fire_stamp = timestamp(500);
11040                 }
11041                 return;
11042         }
11043
11044         if ( lep == NULL ){
11045                 return;
11046         }
11047
11048         SDL_assert(ss->turret_enemy_objnum != -1);
11049
11050         float dot = vm_vec_dot(&v2e, &gvec);
11051
11052         if (dot > tp->turret_fov ) {
11053                 // Ok, the turret is lined up... now line up a particular gun.
11054                 int ok_to_fire = 0;
11055                 float dist_to_enemy;
11056
11057                 // We're ready to fire... now get down to specifics, like where is the
11058                 // actual gun point and normal, not just the one for whole turret.
11059                 ship_get_global_turret_gun_info(&Objects[parent_objnum], ss, &gpos, &gvec, use_angles, &predicted_enemy_pos);
11060                 ss->turret_next_fire_pos++;
11061
11062                 // Fire in the direction the turret is facing, not right at the target regardless of turret dir.
11063                 vm_vec_sub(&v2e, &predicted_enemy_pos, &gpos);
11064                 dist_to_enemy = vm_vec_normalize(&v2e);
11065                 dot = vm_vec_dot(&v2e, &gvec);
11066
11067                 // 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
11068                 // and make them less lethal
11069                 if(Weapon_info[turret_weapon_class].wi_flags & WIF_FLAK){
11070                         flak_jitter_aim(&v2e, dist_to_enemy, ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS));
11071                 }
11072
11073                 // Fire if:
11074                 //              dumbfire and nearly pointing at target.
11075                 //              heat seeking and target in a fairly wide cone.
11076                 //              aspect seeking and target is locked.
11077                 turret_weapon_class = tp->turret_weapon_type;
11078
11079                 // if dumbfire (lasers and non-homing missiles)
11080                 if ( !(Weapon_info[turret_weapon_class].wi_flags & WIF_HOMING) ) {
11081                         if ((dist_to_enemy < 75.0f) || (dot > AICODE_TURRET_DUMBFIRE_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_HEAT ) {     // if heat seekers
11086                         if ((dist_to_enemy < 50.0f) || (dot > AICODE_TURRET_HEATSEEK_ANGLE )) {
11087                                 turret_update_enemy_in_range(ss, 2*Weapon_info[turret_weapon_class].fire_wait);
11088                                 ok_to_fire = 1;
11089                         }
11090                 } else if ( Weapon_info[turret_weapon_class].wi_flags & WIF_HOMING_ASPECT ) {   // if aspect seeker
11091                         if ((dist_to_enemy < 50.0f) || (dot > AICODE_TURRET_DUMBFIRE_ANGLE )) {
11092                                 turret_update_enemy_in_range(ss, 2*Weapon_info[turret_weapon_class].fire_wait);
11093                         }
11094                         if ( turret_should_fire_aspect(ss, dot, turret_weapon_class) ) {
11095                                 ok_to_fire = 1;
11096                         }
11097                 }
11098
11099                 if ( ok_to_fire ) {
11100                         Num_turrets_fired++;
11101                         
11102                         turret_fire_weapon(ss, parent_objnum, &gpos, &v2e, &predicted_enemy_pos);                                               
11103                 } else {
11104                         turret_update_enemy_in_range(ss, -4*Weapon_info[tp->turret_weapon_type].fire_wait);
11105                         ss->turret_next_fire_stamp = timestamp(500);
11106                 }
11107         } else {
11108                 // Lost him!
11109                 ss->turret_enemy_objnum = -1;           //      Reset enemy objnum, find a new one next frame.
11110                 ss->turret_time_enemy_in_range = 0.0f;
11111         }
11112 }
11113
11114 // TURRET END
11115
11116 #ifndef NDEBUG
11117 #define MAX_AI_DEBUG_RENDER_STUFF       100
11118 typedef struct ai_render_stuff {
11119         ship_subsys     *ss;
11120         int                     parent_objnum;
11121 } ai_render_stuff;
11122
11123 ai_render_stuff AI_debug_render_stuff[MAX_AI_DEBUG_RENDER_STUFF];
11124
11125 int     Num_AI_debug_render_stuff = 0;
11126
11127 void ai_debug_render_stuff()
11128 {
11129         vertex  vert1, vert2;
11130         vector  gpos2;
11131         int             i;
11132
11133         for (i=0; i<Num_AI_debug_render_stuff; i++) {
11134                 ship_subsys     *ss;
11135                 int     parent_objnum;
11136                 vector  gpos, gvec;
11137                 model_subsystem *tp;
11138
11139                 ss = AI_debug_render_stuff[i].ss;
11140                 tp = ss->system_info;
11141
11142                 parent_objnum = AI_debug_render_stuff[i].parent_objnum;
11143
11144                 ship_get_global_turret_info(&Objects[parent_objnum], tp, &gpos, &gvec);
11145                 g3_rotate_vertex(&vert1, &gpos);
11146                 vm_vec_scale_add(&gpos2, &gpos, &gvec, 20.0f);
11147                 g3_rotate_vertex(&vert2, &gpos2);
11148                 gr_set_color(0, 0, 255);
11149                 g3_draw_sphere(&vert1, 2.0f);
11150                 gr_set_color(255, 0, 255);
11151                 g3_draw_sphere(&vert2, 2.0f);
11152                 g3_draw_line(&vert1, &vert2);
11153         }
11154
11155         // draw from beta to its goal point
11156 /*      for (i=0; i<6; i++) {
11157                 ai_info *aip = &Ai_info[i];
11158                 gr_set_color(0, 0, 255);
11159                 g3_rotate_vertex(&vert1, &Objects[i].pos);
11160                 g3_rotate_vertex(&vert2, &aip->goal_point);
11161                 g3_draw_line(&vert1, &vert2);
11162         } */
11163         
11164
11165         Num_AI_debug_render_stuff = 0;
11166 }
11167
11168 #endif
11169
11170 #ifndef NDEBUG
11171 int     Msg_count_4996 = 0;
11172 #endif
11173
11174 //      --------------------------------------------------------------------------
11175 // Process subobjects of object objnum.
11176 //      Deal with engines disabled.
11177 void process_subobjects(int objnum)
11178 {
11179         model_subsystem *psub;
11180         ship_subsys     *pss;
11181         object  *objp = &Objects[objnum];
11182         ship            *shipp = &Ships[objp->instance];
11183         ai_info *aip = &Ai_info[shipp->ai_index];
11184         ship_info       *sip = &Ship_info[shipp->ship_info_index];
11185
11186         for ( pss = GET_FIRST(&shipp->subsys_list); pss !=END_OF_LIST(&shipp->subsys_list); pss = GET_NEXT(pss) ) {
11187                 psub = pss->system_info;
11188
11189                 // Don't process destroyed objects
11190                 if ( pss->current_hits <= 0.0f ) 
11191                         continue;
11192
11193                 switch (psub->type) {
11194                 case SUBSYSTEM_TURRET:
11195                         if ( psub->turret_num_firing_points > 0 )       {
11196                                 ai_fire_from_turret(shipp, pss, objnum);
11197                         } else {
11198 #ifndef NDEBUG
11199                                 if (!Msg_count_4996) {
11200                                         Warning( LOCATION, "Ship '%s' has turrets with no guns!\nProbably a model problem, so get an artist!", shipp->ship_name );
11201                                         Msg_count_4996++;
11202                                 }
11203 #endif
11204                                 }
11205                         break;
11206
11207                 case SUBSYSTEM_ENGINE:
11208                 case SUBSYSTEM_NAVIGATION:
11209                 case SUBSYSTEM_COMMUNICATION:
11210                 case SUBSYSTEM_WEAPONS:
11211                 case SUBSYSTEM_SENSORS:
11212                 case SUBSYSTEM_UNKNOWN:
11213                         break;
11214
11215                 // next set of subsystems may rotation
11216                 case SUBSYSTEM_RADAR:
11217                 case SUBSYSTEM_SOLAR:
11218                 case SUBSYSTEM_GAS_COLLECT:
11219                 case SUBSYSTEM_ACTIVATION:
11220                         break;
11221                 default:
11222                         Error(LOCATION, "Illegal subsystem type.\n");
11223                 }
11224
11225                 // do solar/radar/gas/activator rotation here
11226                 if ( psub->flags & MSS_FLAG_ROTATES )   {
11227                         if (psub->flags & MSS_FLAG_STEPPED_ROTATE       ) {
11228                                 submodel_stepped_rotate(psub, &pss->submodel_info_1);
11229                         } else {
11230                                 submodel_rotate(psub, &pss->submodel_info_1 );
11231                         }
11232                 }
11233
11234         }
11235
11236         //      Deal with a ship with blown out engines.
11237         if (ship_get_subsystem_strength(shipp, SUBSYSTEM_ENGINE) == 0.0f) {
11238                 if (sip->flags & (SIF_FIGHTER | SIF_BOMBER)) {
11239                         // AL: Only attack forever if not trying to depart to a docking bay.  Need to have this in, since
11240                         //     a ship may get repaired... and it should still try to depart.  Since docking bay departures
11241                         //     are not handled as goals, we don't want to leave the AIM_BAY_DEPART mode.
11242                         if ( aip->mode != AIM_BAY_DEPART ) {
11243                                 ai_attack_object(objp, NULL, 99, NULL);         //      Regardless of current mode, enter attack mode.
11244                                 aip->submode = SM_ATTACK_FOREVER;                               //      Never leave attack submode, don't avoid, evade, etc.
11245                         }
11246                 }
11247         }
11248
11249
11250 }
11251
11252 //      Given an object and the wing it's in, return its index in the wing list.
11253 //      This defines its location in the wing formation.
11254 //      If the object can't be found in the wing, return -1.
11255 //      *objp           object of interest
11256 //      wingnum the wing *objp is in
11257 int get_wing_index(object *objp, int wingnum)
11258 {
11259         wing    *wingp;
11260         int     i;
11261
11262         SDL_assert((wingnum >= 0) && (wingnum < MAX_WINGS));
11263
11264         wingp = &Wings[wingnum];
11265
11266         for (i=wingp->current_count-1; i>=0; i--)
11267                 if ( objp->instance == wingp->ship_index[i] )
11268                         break;
11269
11270         return i;               //      Note, returns -1 if string not found.
11271 }
11272
11273 //      Given a wing, return a pointer to the object of its leader.
11274 //      Asserts if object not found.
11275 //      Currently, the wing leader is defined as the first object in the wing.
11276 //      wingnum         Wing number in Wings array.
11277 //      If wing leader is disabled, swap it with another ship.
11278 object * get_wing_leader(int wingnum)
11279 {
11280         wing            *wingp;
11281         int             ship_num;
11282
11283         SDL_assert((wingnum >= 0) && (wingnum < MAX_WINGS));
11284
11285         wingp = &Wings[wingnum];
11286
11287         SDL_assert(wingp->current_count != 0);                  //      Make sure there is a leader
11288
11289         ship_num = wingp->ship_index[0];
11290
11291         //      If this ship is disabled, try another ship in the wing.
11292         int n = 0;
11293         while (ship_get_subsystem_strength(&Ships[ship_num], SUBSYSTEM_ENGINE) == 0.0f) {
11294                 n++;
11295                 if (n >= wingp->current_count)
11296                         break;  
11297                 ship_num = wingp->ship_index[n];
11298         }
11299
11300         if (( n != 0) && (n != wingp->current_count)) {
11301                 int t = wingp->ship_index[0];
11302                 wingp->ship_index[0] = wingp->ship_index[n];
11303                 wingp->ship_index[n] = t;
11304         }
11305
11306         return &Objects[Ships[ship_num].objnum];
11307 }
11308
11309 #define DEFAULT_WING_X_DELTA            1.0f
11310 #define DEFAULT_WING_Y_DELTA            0.25f
11311 #define DEFAULT_WING_Z_DELTA            0.75f
11312 #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))
11313 // next constant is higher that MAX_SHIPS_IN_WINGS to deal with forming on player's wing
11314 #define MAX_FORMATION_ROWS              4
11315
11316 //      Given a position in a wing, return the desired location of the ship relative to the leader
11317 //      *_delta_vec             OUTPUT.  delta vector based on wing_index
11318 //      wing_index              position in wing.
11319 void get_wing_delta(vector *_delta_vec, int wing_index)
11320 {
11321         int     wi0;
11322
11323         SDL_assert(wing_index >= 0);
11324
11325         int     k, row, column;
11326
11327         int bank = wing_index / (MAX_FORMATION_ROWS*(MAX_FORMATION_ROWS+1)/2);
11328         wi0 = wing_index % (MAX_FORMATION_ROWS * (MAX_FORMATION_ROWS+1)/2);
11329
11330         k = 0;
11331         for (row=1; row<MAX_FORMATION_ROWS+1; row++) {
11332                 k += row;
11333                 if (wi0 < k)
11334                         break;
11335         }
11336
11337         row--;
11338         column = wi0 - k + row + 1;
11339
11340         _delta_vec->xyz.x = ((float) column - (float) row/2.0f) * DEFAULT_WING_X_DELTA/DEFAULT_WING_MAG;
11341         _delta_vec->xyz.y = ((float)row + (float)bank*2.25f) * DEFAULT_WING_Y_DELTA/DEFAULT_WING_MAG;
11342         _delta_vec->xyz.z = - ((float)row + 0.5f * (float) bank) * DEFAULT_WING_Z_DELTA/DEFAULT_WING_MAG;
11343 }
11344
11345 //      Compute the largest radius of a ship in a *objp's wing.
11346 float gwlr_1(object *objp, ai_info *aip)
11347 {
11348         int             wingnum = aip->wing;
11349         float           max_radius;
11350         object  *o;
11351         ship_obj        *so;
11352
11353         SDL_assert(wingnum >= 0);
11354
11355         max_radius = objp->radius;
11356
11357         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11358                 o = &Objects[so->objnum];
11359                 if (Ai_info[Ships[o->instance].ai_index].wing == wingnum)
11360                         if (o->radius > max_radius)
11361                                 max_radius = o->radius;
11362         }
11363
11364         return max_radius;
11365 }
11366
11367 //      Compute the largest radius of a ship forming on *objp's wing.
11368 float gwlr_object_1(object *objp, ai_info *aip)
11369 {
11370         float           max_radius;
11371         object  *o;
11372         ship_obj        *so;
11373
11374         max_radius = objp->radius;
11375
11376         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11377                 o = &Objects[so->objnum];
11378                 if (Ai_info[Ships[o->instance].ai_index].goal_objnum == OBJ_INDEX(objp))
11379                         if (o->radius > max_radius)
11380                                 max_radius = o->radius;
11381         }
11382
11383         return max_radius;
11384 }
11385
11386 //      For the wing that *objp is part of, return the largest ship radius in that wing.
11387 float get_wing_largest_radius(object *objp, int formation_object_flag)
11388 {
11389         ship            *shipp;
11390         ai_info *aip;
11391
11392         SDL_assert(objp->type == OBJ_SHIP);
11393         SDL_assert((objp->instance >= 0) && (objp->instance < MAX_OBJECTS));
11394         shipp = &Ships[objp->instance];
11395         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11396         aip = &Ai_info[shipp->ai_index];
11397
11398         if (formation_object_flag) {
11399                 return gwlr_object_1(objp, aip);
11400         } else {
11401                 return gwlr_1(objp, aip);
11402         }
11403
11404 }
11405
11406 float Wing_y_scale = 2.0f;
11407 float Wing_scale = 1.0f;
11408 DCF(wing_y_scale, "")
11409 {
11410         dc_get_arg(ARG_FLOAT);
11411         Wing_y_scale = Dc_arg_float;
11412 }
11413
11414 DCF(wing_scale, "")
11415 {
11416         dc_get_arg(ARG_FLOAT);
11417         Wing_scale = Dc_arg_float;
11418 }
11419
11420 // Given a wing leader and a position in the wing formation, return the desired absolute location to fly to.
11421 //      Returns result in *result_pos.
11422 void get_absolute_wing_pos(vector *result_pos, object *leader_objp, int wing_index, int formation_object_flag)
11423 {
11424         vector  wing_delta, rotated_wing_delta;
11425         float           wing_spread_size;
11426
11427         get_wing_delta(&wing_delta, wing_index);                //      Desired location in leader's reference frame
11428
11429         wing_spread_size = max(50.0f, 3.0f * get_wing_largest_radius(leader_objp, formation_object_flag) + 15.0f);
11430
11431         // for player obj (1) move ships up 20% (2) scale formation up 20%
11432         if (leader_objp->flags & OF_PLAYER_SHIP) {
11433                 wing_delta.xyz.y *= Wing_y_scale;
11434                 wing_spread_size *= Wing_scale;
11435         }
11436
11437         vm_vec_scale(&wing_delta, wing_spread_size * (1.0f + leader_objp->phys_info.speed/70.0f));
11438
11439         vm_vec_unrotate(&rotated_wing_delta, &wing_delta, &leader_objp->orient);        //      Rotate into leader's reference.
11440
11441         vm_vec_add(result_pos, &leader_objp->pos, &rotated_wing_delta); //      goal_point is absolute 3-space point.
11442 }
11443
11444 #ifndef NDEBUG
11445 int Debug_render_wing_phantoms;
11446
11447 void render_wing_phantoms(object *objp)
11448 {
11449         int             i;
11450         ship            *shipp;
11451         ai_info *aip;
11452         int             wingnum;
11453         int             wing_index;             //      Index in wing struct, defines 3-space location in wing.
11454         vector  goal_point;
11455         
11456         SDL_assert(objp->type == OBJ_SHIP);
11457         SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11458
11459         shipp = &Ships[objp->instance];
11460         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11461
11462         aip = &Ai_info[shipp->ai_index];
11463
11464         wingnum = aip->wing;
11465
11466         if (wingnum == -1)
11467                 return;
11468
11469         wing_index = get_wing_index(objp, wingnum);
11470
11471         //      If this ship is NOT the leader, abort.
11472         if (wing_index != 0)
11473                 return;
11474
11475         for (i=0; i<32; i++)
11476                 if (Debug_render_wing_phantoms & (1 << i)) {
11477                         get_absolute_wing_pos(&goal_point, objp, i, 0);
11478         
11479                         vertex  vert;
11480                         gr_set_color(255, 0, 128);
11481                         g3_rotate_vertex(&vert, &goal_point);
11482                         g3_draw_sphere(&vert, 2.0f);
11483                 }
11484
11485         Debug_render_wing_phantoms = 0;
11486
11487 }
11488
11489 void render_wing_phantoms_all()
11490 {
11491         object  *objp;
11492         ship_obj        *so;
11493
11494         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11495                 ship            *shipp;
11496                 ai_info *aip;
11497                 int             wingnum;
11498                 int             wing_index;             //      Index in wing struct, defines 3-space location in wing.
11499
11500                 objp = &Objects[so->objnum];
11501                 
11502                 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11503                 shipp = &Ships[objp->instance];
11504                 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11505
11506                 aip = &Ai_info[shipp->ai_index];
11507
11508                 wingnum = aip->wing;
11509
11510                 if (wingnum == -1)
11511                         continue;
11512
11513                 wing_index = get_wing_index(objp, wingnum);
11514
11515                 //      If this ship is NOT the leader, abort.
11516                 if (wing_index != 0)
11517                         continue;
11518                 
11519                 render_wing_phantoms(objp);
11520
11521                 return;
11522         }
11523 }
11524
11525 #endif
11526
11527 //      Hook from goals code to AI.
11528 //      Force a wing to fly in formation.
11529 //      Sets AIF_FORMATION bit in ai_flags.
11530 //      wingnum         Wing to force to fly in formation
11531 void ai_fly_in_formation(int wingnum)
11532 {
11533         object  *objp;
11534         ship            *shipp;
11535         ship_obj        *so;
11536
11537         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11538                 objp = &Objects[so->objnum];
11539                 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11540
11541                 shipp = &Ships[objp->instance];
11542                 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11543
11544                 if (Ai_info[shipp->ai_index].wing == wingnum) {
11545                         Ai_info[shipp->ai_index].ai_flags |= AIF_FORMATION_WING;
11546                         Ai_info[shipp->ai_index].ai_flags &= ~AIF_FORMATION_OBJECT;
11547                 }
11548         }
11549 }
11550
11551 //      Hook from goals code to AI.
11552 //      Force a wing to abandon formation flying.
11553 //      Clears AIF_FORMATION bit in ai_flags.
11554 //      wingnum         Wing to force to fly in formation
11555 void ai_disband_formation(int wingnum)
11556 {
11557         object  *objp;
11558         ship            *shipp;
11559         ship_obj        *so;
11560
11561         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11562                 objp = &Objects[so->objnum];
11563                 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11564
11565                 shipp = &Ships[objp->instance];
11566                 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11567
11568                 if (Ai_info[shipp->ai_index].wing == wingnum) {
11569                         Ai_info[shipp->ai_index].ai_flags &= ~AIF_FORMATION_WING;
11570                 }
11571         }
11572 }
11573
11574 float   Leader_chaos = 0.0f;
11575 int Chaos_frame = -1;
11576
11577 //      Return true if objp is flying in an erratic manner
11578 //      Only true if objp is a player
11579 int formation_is_leader_chaotic(object *objp)
11580 {
11581         if (Game_mode & GM_MULTIPLAYER)
11582                 return 0;
11583
11584         if (objp != Player_obj)
11585                 return 0;
11586
11587         if (Framecount != Chaos_frame) {
11588                 float   speed_scale;
11589                 float   fdot, udot;
11590
11591                 speed_scale = 3.0f + objp->phys_info.speed * 0.1f;
11592
11593                 fdot = 5.0f * (1.0f - vm_vec_dot(&objp->orient.v.fvec, &objp->last_orient.v.fvec)) * flFrametime;
11594                 udot = 8.0f * (1.0f - vm_vec_dot(&objp->orient.v.uvec, &objp->last_orient.v.uvec)) * flFrametime;
11595
11596                 Leader_chaos += fdot * speed_scale + udot * speed_scale;
11597
11598                 Leader_chaos *= (1.0f - flFrametime*0.2f);
11599
11600                 if (Leader_chaos < 0.0f)
11601                         Leader_chaos = 0.0f;
11602                 else if (Leader_chaos > 1.7f)
11603                         Leader_chaos = 1.7f;
11604
11605                 //nprintf(("AI", "Frame %i: chaos = %7.4f\n", Framecount, Leader_chaos));
11606
11607                 Chaos_frame = Framecount;
11608         }
11609
11610         return (Leader_chaos > 1.0f);
11611 }
11612
11613 // Fly in formation.
11614 //      Make Pl_objp assume its proper place in formation.
11615 //      If the leader of the wing is doing something stupid, like fighting a battle,
11616 //      then the poor sap wingmates will be in for a "world of hurt"
11617 //      Return TRUE if we need to process this object's normal mode
11618 int ai_formation()
11619 {
11620         object  *leader_objp;
11621         ship            *shipp;
11622         ai_info *aip, *laip;
11623         int             wingnum;
11624         int             wing_index;             //      Index in wing struct, defines 3-space location in wing.
11625         int             player_wing;    // index of the players wingnum
11626         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;
11627         float           dot_to_goal, dist_to_goal, leader_speed;
11628
11629         SDL_assert(Pl_objp->type == OBJ_SHIP);
11630         SDL_assert((Pl_objp->instance >= 0) && (Pl_objp->instance < MAX_SHIPS));
11631
11632         shipp = &Ships[Pl_objp->instance];
11633
11634         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11635
11636         aip = &Ai_info[shipp->ai_index];
11637
11638         SDL_assert((aip->ai_flags & AIF_FORMATION) != AIF_FORMATION);   //      Make sure not both types of formation flying in effect.
11639
11640         //      Determine which kind of formation flying.
11641         //      If tracking an object, not in waypoint mode:
11642         if (aip->ai_flags & AIF_FORMATION_OBJECT) {
11643                 if ((aip->goal_objnum < 0) || (aip->goal_objnum >= MAX_OBJECTS)) {
11644                         aip->ai_flags &= ~AIF_FORMATION_OBJECT;
11645                         return 1;
11646                 }
11647                 
11648                 wing_index = ai_formation_object_get_slotnum(aip->goal_objnum, Pl_objp);
11649                 leader_objp = &Objects[aip->goal_objnum];
11650         } else {        //      Formation flying in waypoint mode.
11651                 SDL_assert(aip->ai_flags & AIF_FORMATION_WING);
11652                 if (aip->mode != AIM_WAYPOINTS) {
11653                         aip->ai_flags &= ~AIF_FORMATION_WING;
11654                         return 1;
11655                 }
11656
11657                 wingnum = aip->wing;
11658
11659                 if (wingnum == -1)
11660                         return 1;
11661
11662                 // disable formation flying for any ship in the players wing
11663                 player_wing = Ships[Player_obj->instance].wingnum;
11664                 if ( (player_wing != -1) && (wingnum == player_wing) )
11665                         return 1;
11666
11667                 wing_index = get_wing_index(Pl_objp, wingnum);
11668
11669                 leader_objp = get_wing_leader(wingnum);
11670
11671         }
11672
11673         //      If docked with a ship in this wing, only the more massive one actually flies in formation.
11674         if (aip->dock_objnum != -1) {
11675                 object  *other_objp = &Objects[aip->dock_objnum];
11676                 ai_info *other_aip = &Ai_info[Ships[other_objp->instance].ai_index];
11677
11678                 if (aip->wing == other_aip->wing) {
11679                         if (Pl_objp->phys_info.mass < other_objp->phys_info.mass)
11680                                 return 0;
11681                         else if (Pl_objp->phys_info.mass == other_objp->phys_info.mass) {
11682                                 if (Pl_objp->signature < other_objp->signature)
11683                                         return 0;
11684                         }
11685                 }
11686         }
11687
11688         SDL_assert(leader_objp != NULL);
11689         laip = &Ai_info[Ships[leader_objp->instance].ai_index];
11690
11691         //      Make sure we're really in this wing.
11692         if (wing_index == -1)
11693                 return 1;
11694
11695         //      If this ship is the leader, abort, as he doesn't have to follow anyone.
11696         if (wing_index == 0) {
11697                 // nprintf(("AI", "Hmm, wing leader %s in ai_formation for no good reason.\n", shipp->ship_name));
11698                 return 1;
11699         }
11700
11701         if (aip->mode == AIM_WAYPOINTS) {
11702                 aip->wp_list = laip->wp_list;
11703                 if (laip->wp_index < Waypoint_lists[laip->wp_list].count)
11704                         aip->wp_index = laip->wp_index;
11705                 else
11706                         aip->wp_index = Waypoint_lists[laip->wp_list].count - 1;
11707                 aip->wp_flags = laip->wp_flags;
11708                 aip->wp_dir = laip->wp_dir;
11709         }
11710
11711         #ifndef NDEBUG
11712         Debug_render_wing_phantoms |= (1 << wing_index);
11713         #endif
11714
11715         leader_speed = leader_objp->phys_info.speed;
11716         vector leader_vec = leader_objp->phys_info.vel;
11717
11718         get_absolute_wing_pos(&goal_point, leader_objp, wing_index, aip->ai_flags & AIF_FORMATION_OBJECT);
11719         vm_vec_scale_add(&future_goal_point_5, &goal_point, &leader_vec, 10.0f);
11720         vm_vec_scale_add(&future_goal_point_2, &goal_point, &leader_vec, 5.0f);
11721         vm_vec_scale_add(&future_goal_point_x, &goal_point, &leader_objp->orient.v.fvec, 10.0f);        //      used when very close to destination
11722         vm_vec_scale_add(&future_goal_point_1000x, &goal_point, &leader_objp->orient.v.fvec, 1000.0f);  //      used when very close to destination
11723
11724         //      Now, get information telling this object how to turn and accelerate to get to its
11725         //      desired location.
11726         vm_vec_sub(&vec_to_goal, &goal_point, &Pl_objp->pos);
11727         if ( vm_vec_mag_quick(&vec_to_goal) < AICODE_SMALL_MAGNITUDE )
11728                 vec_to_goal.xyz.x += 0.1f;
11729
11730         vm_vec_copy_normalize(&dir_to_goal, &vec_to_goal);
11731         //dot_to_goal = vm_vec_dot(&dir_to_goal, &leader_objp->orient.v.fvec);
11732         dot_to_goal = vm_vec_dot(&dir_to_goal, &Pl_objp->orient.v.fvec);
11733         dist_to_goal = vm_vec_dist_quick(&Pl_objp->pos, &goal_point);
11734         float   dist_to_goal_2 = vm_vec_dist_quick(&Pl_objp->pos, &future_goal_point_2);
11735
11736         // 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));
11737
11738         int     chaotic_leader = 0;
11739
11740         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.
11741
11742         if (dist_to_goal > 500.0f) {
11743                 turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
11744                 accelerate_ship(aip, 1.0f);
11745         } else if (dist_to_goal > 200.0f) {
11746                 if (dot_to_goal > -0.5f) {
11747                         turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
11748                         float range_speed = shipp->current_max_speed - leader_speed;
11749                         if (range_speed > 0.0f)
11750                                 set_accel_for_target_speed(Pl_objp, leader_speed + range_speed * (dist_to_goal+100.0f)/500.0f);
11751                         else
11752                                 set_accel_for_target_speed(Pl_objp, shipp->current_max_speed);
11753                 } else {
11754                         turn_towards_point(Pl_objp, &future_goal_point_5, NULL, 0.0f);
11755                         if (leader_speed > 10.0f)
11756                                 set_accel_for_target_speed(Pl_objp, leader_speed *(1.0f + dot_to_goal));
11757                         else
11758                                 set_accel_for_target_speed(Pl_objp, 10.0f);
11759                 }
11760         } else {
11761                 vector  v2f2;
11762                 float   dot_to_f2;
11763
11764                 vm_vec_normalized_dir(&v2f2, &future_goal_point_2, &Pl_objp->pos);
11765                 dot_to_f2 = vm_vec_dot(&v2f2, &Pl_objp->orient.v.fvec);
11766
11767                 //      Leader flying like a maniac.  Don't try hard to form on wing.
11768                 if (chaotic_leader) {
11769                         turn_towards_point(Pl_objp, &future_goal_point_2, NULL, 0.0f);
11770                         set_accel_for_target_speed(Pl_objp, min(leader_speed*0.8f, 20.0f));
11771                 } else if (dist_to_goal > 75.0f) {
11772                         turn_towards_point(Pl_objp, &future_goal_point_2, NULL, 0.0f);
11773                         float   delta_speed;
11774                         float range_speed = shipp->current_max_speed - leader_speed;
11775                         if (range_speed > 0.0f)
11776                                 delta_speed = dist_to_goal_2/500.0f * range_speed;
11777                         else
11778                                 delta_speed = shipp->current_max_speed - leader_speed;
11779                         if (dot_to_goal < 0.0f) {
11780                                 delta_speed = -delta_speed;
11781                                 if (-delta_speed > leader_speed/2)
11782                                         delta_speed = -leader_speed/2;
11783                         }
11784
11785                         if (leader_speed < 5.0f)
11786                                 if (delta_speed < 5.0f)
11787                                         delta_speed = 5.0f;
11788
11789                         float scale = dot_to_f2;
11790                         if (scale < 0.1f)
11791                                 scale = 0.0f;
11792                         else
11793                                 scale *= scale;
11794
11795                         set_accel_for_target_speed(Pl_objp, scale * (leader_speed + delta_speed));
11796                 } else {
11797                         //nprintf(("AI", "Dot = %7.3f\n", dot_to_goal));
11798
11799                         if (leader_speed < 5.0f) {
11800                                 //      Leader very slow.  If not close to goal point, get very close.  Note, keep trying to get close unless
11801                                 //      moving very slowly, else momentum can carry far away from goal.
11802
11803                                 if ((dist_to_goal > 10.0f) || ((Pl_objp->phys_info.speed > leader_speed + 2.5f) && (dot_to_goal > 0.5f))) {
11804                                         //nprintf(("MK", "(1) "));
11805                                         turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
11806                                         set_accel_for_target_speed(Pl_objp, leader_speed + dist_to_goal/10.0f);
11807                                 } else {
11808                                         if (Pl_objp->phys_info.speed < 0.5f) {
11809                                                 //nprintf(("MK", "(2) "));
11810                                                 turn_towards_point(Pl_objp, &future_goal_point_1000x, NULL, 0.0f);
11811                                         } else {
11812                                                 //nprintf(("MK", "(3) "));
11813                                         }
11814                                         set_accel_for_target_speed(Pl_objp, leader_speed);
11815                                 }
11816                                 //nprintf(("MK", "dist: %7.3f, dot: %6.3f, speed: %7.3f\n", dist_to_goal, dot_to_goal, Pl_objp->phys_info.speed));
11817                         } else if (dist_to_goal > 10.0f) {
11818                                 float   dv;
11819
11820                                 //future_goal_point_2;
11821
11822                                 turn_towards_point(Pl_objp, &future_goal_point_2, NULL, 0.0f);
11823
11824                                 if (dist_to_goal > 25.0f) {
11825                                         if (dot_to_goal < 0.3f)
11826                                                 dv = -0.1f;
11827                                         else
11828                                                 dv = dot_to_goal - 0.2f;
11829
11830                                         set_accel_for_target_speed(Pl_objp, leader_speed + dist_to_goal/5.0f * dv);
11831                                 } else {
11832                                         set_accel_for_target_speed(Pl_objp, leader_speed + 1.5f * dot_to_goal - 1.0f);
11833                                 }
11834                         } else {
11835                                 if (Pl_objp->phys_info.speed < 0.1f)
11836                                         turn_towards_point(Pl_objp, &future_goal_point_1000x, NULL, 0.0f);
11837                                 else
11838                                         turn_towards_point(Pl_objp, &future_goal_point_x, NULL, 0.0f);
11839                                 set_accel_for_target_speed(Pl_objp, 0.0f);
11840                         }
11841                 }
11842
11843         }
11844
11845         //      See how different this ship's bank is relative to wing leader
11846         float   up_dot = vm_vec_dot(&leader_objp->orient.v.uvec, &Pl_objp->orient.v.uvec);
11847         if (up_dot < 0.996f) {
11848                 vector  w_out;
11849                 matrix  new_orient;
11850                 vector  angular_accel;
11851
11852                 vm_vec_copy_scale(&angular_accel, &Pl_objp->phys_info.max_rotvel, 0.2f);
11853                 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);
11854
11855         //      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)));
11856                 Pl_objp->orient = new_orient;
11857                 Pl_objp->phys_info.rotvel = w_out;
11858         //      Pl_objp->phys_info.desired_rotvel = w_out;
11859         } else {
11860                 Pl_objp->phys_info.rotvel.xyz.z = 0.0f;
11861         }
11862
11863         return 0;
11864 }
11865
11866 //      Return index of object repairing object objnum.
11867 int find_repairing_objnum(int objnum)
11868 {
11869         object          *objp;
11870         ship                    *shipp;
11871         ship_info       *sip;
11872         ship_obj                *so;
11873
11874         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11875                 objp = &Objects[so->objnum];
11876
11877                 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11878
11879                 shipp = &Ships[objp->instance];
11880                 sip = &Ship_info[shipp->ship_info_index];
11881
11882                 if (sip->flags & SIF_SUPPORT) {
11883                         ai_info *aip;
11884
11885                         aip = &Ai_info[shipp->ai_index];
11886
11887                         if (aip->goal_objnum == objnum) {
11888                                 return objp-Objects;
11889                         }
11890                 }
11891         }
11892
11893         return -1;
11894 }
11895
11896 //      If object *objp is being repaired, deal with it!
11897 void ai_do_repair_frame(object *objp, ai_info *aip, float frametime)
11898 {
11899         if (Ships[objp->instance].team == TEAM_TRAITOR) {
11900                 ai_abort_rearm_request(objp);
11901                 return;
11902         }
11903
11904         if (aip->ai_flags & (AIF_BEING_REPAIRED | AIF_AWAITING_REPAIR)) {
11905                 int     dock_objnum;
11906                 ai_info *repair_aip;
11907
11908                 dock_objnum = aip->dock_objnum; // find_repairing_objnum(objp-Objects);
11909                 //SDL_assert(dock_objnum != -1);
11910                 if (dock_objnum == -1)
11911                         return;
11912                 if (Objects[dock_objnum].signature != aip->dock_signature) {
11913                         Int3();         //      Curious -- object numbers match, but signatures do not.
11914                                                         //      Must mean original repair ship died and was replaced by current ship.
11915                         return;
11916                 }
11917         
11918                 repair_aip = &Ai_info[Ships[Objects[dock_objnum].instance].ai_index];
11919                 //SDL_assert(repair_aip->mode == AIM_DOCK);
11920
11921                 if (aip->ai_flags & AIF_BEING_REPAIRED) {
11922                         // SDL_assert(repair_aip->submode == AIS_DOCK_4);
11923
11924                         //      Wait awhile into the mode to synchronize with sound effect.
11925                         if (Missiontime - repair_aip->submode_start_time > REARM_SOUND_DELAY) {
11926                                 int repaired;
11927
11928                                 repaired = ship_do_rearm_frame( objp, frametime );              // hook to do missile rearming
11929
11930                                 //      See if fully repaired.  If so, cause process to stop.
11931                                 if ( repaired && (repair_aip->submode == AIS_DOCK_4)) {
11932
11933                                         repair_aip->submode = AIS_UNDOCK_0;
11934                                         repair_aip->submode_start_time = Missiontime;
11935
11936                                         // if repairing player object -- tell him done with repair
11937                                         if ( !MULTIPLAYER_CLIENT ){
11938                                                 ai_do_objects_repairing_stuff( objp, &Objects[dock_objnum], REPAIR_INFO_COMPLETE );
11939                                         }
11940                                 }
11941                         }
11942                 } else if (aip->ai_flags & AIF_AWAITING_REPAIR) {
11943                         //      If this ship has been awaiting repair for 90+ seconds, abort.
11944                         if ( !MULTIPLAYER_CLIENT ) {
11945                                 if ((Game_mode & GM_MULTIPLAYER) || (objp != Player_obj)) {
11946                                         if ((repair_aip->goal_objnum == OBJ_INDEX(objp)) && (timestamp_elapsed(aip->abort_rearm_timestamp))) {
11947                                                 ai_abort_rearm_request(objp);
11948                                                 aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP);
11949                                         }
11950                                 }
11951                         }
11952                 }
11953         } else {
11954                 // AL 11-24-97: If this is the player ship, ensure the repair sound isn't playing.  We need to
11955                 //              do this check, since this is a looping sound, and may continue on if rearm/repair
11956                 //              finishes abnormally once sound begins looping.
11957                 if ( objp == Player_obj ) {
11958                         player_stop_repair_sound();
11959                 }
11960         }
11961 }
11962
11963 //      Shell around dock_orient_and_approach to detect whether dock process should be aborted.
11964 //      obj1 is the ship performing the repair.
11965 //      obj2 is the ship being repaired.
11966 void call_doa(object *obj1, object *obj2, ship_info *sip1)
11967 {
11968         if (sip1->flags & SIF_SUPPORT) {
11969                 if (obj2->phys_info.speed > MAX_REPAIR_SPEED) {
11970
11971                         // call the ai_abort rearm request code
11972                         ai_abort_rearm_request( obj2 );
11973                 } else
11974                         dock_orient_and_approach(obj1, obj2, DOA_DOCK_STAY);
11975         } else {
11976                 if (Ship_info[Ships[obj1->instance].ship_info_index].flags & SIF_CARGO)
11977                         dock_orient_and_approach(obj1, obj2, DOA_DOCK_STAY);
11978                 else if (Ship_info[Ships[obj2->instance].ship_info_index].flags & SIF_CARGO)
11979                         dock_orient_and_approach(obj2, obj1, DOA_DOCK_STAY);
11980                 else {
11981                         //mprintf(("Warning: Not sure, but making %s [%s] move to stay docked with %s [%s]\n",
11982                         //      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));
11983                         dock_orient_and_approach(obj1, obj2, DOA_DOCK_STAY);
11984
11985                 }
11986         }
11987
11988 }
11989
11990 //      Maybe launch a countermeasure.
11991 //      Also, detect a supposed homing missile that no longer exists.
11992 void ai_maybe_launch_cmeasure(object *objp, ai_info *aip)
11993 {
11994         float                   dist;
11995         ship_info       *sip;
11996         ship                    *shipp;
11997
11998         shipp = &Ships[objp->instance];
11999         sip = &Ship_info[shipp->ship_info_index];
12000
12001         if (!(sip->flags & (SIF_SMALL_SHIP | SIF_TRANSPORT)))
12002                 return;
12003
12004         if (!shipp->cmeasure_count)
12005                 return;
12006
12007         if ( !timestamp_elapsed(shipp->cmeasure_fire_stamp) )
12008                 return;
12009
12010         //      If not on player's team and Skill_level + ai_class is low, never fire a countermeasure.  The ship is too dumb.
12011         if (shipp->team != Player_ship->team) {
12012                 if (Game_skill_level + aip->ai_class < 4){
12013                         return;
12014                 }
12015         }
12016
12017         if ((aip->nearest_locked_object != -1) && (Objects[aip->nearest_locked_object].type == OBJ_WEAPON)) {
12018                 object  *weapon_objp;
12019
12020                 weapon_objp = &Objects[aip->nearest_locked_object];
12021
12022                 if ((dist = vm_vec_dist_quick(&objp->pos, &weapon_objp->pos)) < weapon_objp->phys_info.speed*2.0f) {
12023         
12024                         aip->nearest_locked_distance = dist;
12025                         //      Verify that this object is really homing on us.
12026                         object  *weapon_objp;
12027
12028                         weapon_objp = &Objects[aip->nearest_locked_object];
12029
12030                         float   fire_chance;
12031
12032                         //      For ships on player's team, have constant, average chance to fire.
12033                         //      For enemies, increasing chance with higher skill level.
12034                         if (shipp->team == Player_ship->team)
12035                                 fire_chance = Cmeasure_fire_chance[NUM_SKILL_LEVELS/2];
12036                         else
12037                                 fire_chance = Cmeasure_fire_chance[Game_skill_level];
12038
12039                         //      Decrease chance to fire at lower ai class.
12040                         fire_chance *= (float) aip->ai_class/Num_ai_classes;
12041
12042                         float r = frand();
12043                         if (fire_chance < r) {
12044                                 //nprintf(("AI", "Not firing countermeasure due to skill level: %7.3f < %7.3f\n", fire_chance, r));
12045                                 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.
12046                                 return;
12047                         }
12048
12049                         if (weapon_objp->type == OBJ_WEAPON) {
12050                                 if (weapon_objp->instance >= 0) {
12051                                         //nprintf(("AI", "Firing countermeasure at time t=%7.3f\n", f2fl(Missiontime)));
12052                                         ship_launch_countermeasure(objp);
12053                                         shipp->cmeasure_fire_stamp = timestamp(2*CMEASURE_WAIT);
12054                                         return;
12055                                 }
12056                         }
12057         
12058                 }
12059         }
12060
12061         return;
12062 }
12063
12064 //      --------------------------------------------------------------------------
12065 void ai_preprocess_ignore_objnum(object *objp, ai_info *aip)
12066 {
12067 //      if (aip->ignore_objnum == UNUSED_OBJNUM)
12068 //              return;
12069
12070         if (aip->ai_flags & AIF_TEMPORARY_IGNORE) {
12071                 if (timestamp_elapsed(aip->ignore_expire_timestamp)) {
12072                         aip->ignore_objnum = UNUSED_OBJNUM;
12073                 }
12074         }
12075
12076         if (is_ignore_object(aip, aip->goal_objnum)) {
12077                 aip->goal_objnum = -1;
12078                 // AL 12-11-97: If in STRAFE mode, we need to ensure that target_objnum is also
12079                 //              set to -1
12080                 if ( aip->mode == AIM_STRAFE ) {
12081                         aip->target_objnum = -1;
12082                 }
12083         }
12084
12085         if (is_ignore_object(aip, aip->target_objnum))
12086                 aip->target_objnum = -1;
12087 }
12088
12089 /*
12090 void ai_safety_circle_spot()
12091 {
12092         vector  goal_point;
12093         ship_info       *sip;
12094
12095         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
12096
12097         goal_point = Ai_info[Ships[Pl_objp->instance].ai_index].goal_point;
12098         turn_towards_tangent(Pl_objp, &goal_point, 50.0f);
12099
12100         set_accel_for_target_speed(Pl_objp, sip->max_speed/4.0f);
12101
12102 //      float dist = vm_vec_dist_quick(&goal_point, &Pl_objp->pos);
12103 //      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));
12104
12105 }
12106 */
12107
12108 #define CHASE_CIRCLE_DIST               100.0f
12109
12110 void ai_chase_circle(object *objp)
12111 {
12112         float           dist_to_goal;
12113         float           target_speed;
12114         vector  goal_point;
12115         ship_info       *sip;
12116         ai_info         *aip;
12117
12118         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
12119
12120         target_speed = sip->max_speed/4.0f;
12121         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
12122
12123         SDL_assert(vm_vec_mag(&aip->goal_point) >= 0.0f);               //      Supposedly detects bogus vector
12124
12125         goal_point = aip->goal_point;
12126
12127         if (aip->ignore_objnum == UNUSED_OBJNUM) {
12128                 dist_to_goal = vm_vec_dist_quick(&aip->goal_point, &objp->pos);
12129
12130                 if (dist_to_goal > 2*CHASE_CIRCLE_DIST) {
12131                         vector  vec_to_goal;
12132                         //      Too far from circle goal, create a new goal point.
12133                         vm_vec_normalized_dir(&vec_to_goal, &aip->goal_point, &objp->pos);
12134                         vm_vec_scale_add(&aip->goal_point, &objp->pos, &vec_to_goal, CHASE_CIRCLE_DIST);
12135                 }
12136
12137                 goal_point = aip->goal_point;
12138         } else if (is_ignore_object(aip, aip->ignore_objnum)) {
12139                 object  *ignore_objp = &Objects[aip->ignore_objnum];
12140
12141                 vector  tvec1;
12142                 float           dist;
12143
12144                 dist = vm_vec_normalized_dir(&tvec1, &Pl_objp->pos, &ignore_objp->pos);
12145
12146                 if (dist < ignore_objp->radius*2 + 1500.0f) {
12147                         vm_vec_scale_add(&goal_point, &Pl_objp->pos, &tvec1, ignore_objp->radius*2 + 1400.0f);
12148                         if (dist < ignore_objp->radius*2 + 1300.0f)
12149                                 target_speed = sip->max_speed * (1.25f - dist/(ignore_objp->radius*2 + 1500.0f));
12150                 }
12151         }
12152
12153         SDL_assert(vm_vec_mag(&aip->goal_point) >= 0.0f);               //      Supposedly detects bogus vector
12154
12155         turn_towards_tangent(Pl_objp, &goal_point, 10*objp->radius + 200.0f);
12156
12157         set_accel_for_target_speed(Pl_objp, target_speed);
12158
12159 }
12160
12161 #define SHIELD_BALANCE_RATE     0.2f            //      0.1f -> takes 10 seconds to equalize shield.
12162
12163 //      Transfer shield energy to most recently hit section from others.
12164 void ai_transfer_shield(object *objp, int quadrant_num)
12165 {
12166         int     i;
12167         float   transfer_amount;
12168         float   transfer_delta;
12169         ship_info       *sip;
12170         float   max_quadrant_strength;
12171
12172         sip = &Ship_info[Ships[objp->instance].ship_info_index];
12173         max_quadrant_strength = sip->shields/MAX_SHIELD_SECTIONS;
12174
12175         transfer_amount = 0.0f;
12176         transfer_delta = (SHIELD_BALANCE_RATE/2) * max_quadrant_strength;
12177
12178         if (objp->shields[quadrant_num] + (MAX_SHIELD_SECTIONS-1)*transfer_delta > max_quadrant_strength)
12179                 transfer_delta = (max_quadrant_strength - objp->shields[quadrant_num])/(MAX_SHIELD_SECTIONS-1);
12180
12181         for (i=0; i<MAX_SHIELD_SECTIONS; i++)
12182                 if (i != quadrant_num) {
12183                         if (objp->shields[i] >= transfer_delta) {
12184                                 objp->shields[i] -= transfer_delta;
12185                                 transfer_amount += transfer_delta;
12186                         } else {
12187                                 transfer_amount += objp->shields[i];
12188                                 objp->shields[i] = 0.0f;
12189                         }
12190                 }
12191
12192         objp->shields[quadrant_num] += transfer_amount;
12193 }
12194
12195 void ai_balance_shield(object *objp)
12196 {
12197         int     i;
12198         float   shield_strength_avg;
12199         float   delta;
12200
12201
12202         shield_strength_avg = get_shield_strength(objp)/MAX_SHIELD_SECTIONS;
12203
12204         delta = SHIELD_BALANCE_RATE * shield_strength_avg;
12205
12206         for (i=0; i<MAX_SHIELD_SECTIONS; i++)
12207                 if (objp->shields[i] < shield_strength_avg) {
12208                         add_shield_strength(objp, delta);
12209                         if (objp->shields[i] > shield_strength_avg)
12210                                 objp->shields[i] = shield_strength_avg;
12211                 } else {
12212                         add_shield_strength(objp, -delta);
12213                         if (objp->shields[i] < shield_strength_avg)
12214                                 objp->shields[i] = shield_strength_avg;
12215                 }
12216 }
12217
12218 //      Manage the shield for this ship.
12219 //      Try to max out the side that was most recently hit.
12220 void ai_manage_shield(object *objp, ai_info *aip)
12221 {
12222         ship_info *sip;
12223
12224         sip = &Ship_info[Ships[objp->instance].ship_info_index];
12225
12226         if (timestamp_elapsed(aip->shield_manage_timestamp)) {
12227                 float           delay;
12228
12229                 //      Scale time until next manage shield based on Skill_level.
12230                 //      Ships on player's team are treated as if Skill_level is average.
12231                 if (Ships[objp->instance].team != Player_ship->team){
12232                         delay = Shield_manage_delays[Game_skill_level];
12233                 } else {
12234                         delay = Shield_manage_delays[NUM_SKILL_LEVELS/2];
12235                 }
12236
12237                 //      Scale between 1x and 3x based on ai_class
12238                 delay = delay + delay * (float) (3*(Num_ai_classes - aip->ai_class - 1) / (Num_ai_classes - 1));
12239                 aip->shield_manage_timestamp = timestamp((int) (delay * 1000.0f));
12240
12241                 if (sip->flags & SIF_SMALL_SHIP) {
12242                         if (Missiontime - aip->last_hit_time < F1_0*10)
12243                                 ai_transfer_shield(objp, aip->last_hit_quadrant);
12244                         else
12245                                 ai_balance_shield(objp);
12246                 }
12247
12248                 // 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]));
12249         }
12250 }
12251
12252 //      See if object *objp should evade an incoming missile.
12253 //      *aip is the ai_info pointer within *objp.
12254 void ai_maybe_evade_locked_missile(object *objp, ai_info *aip)
12255 {
12256         ship                    *shipp;
12257
12258         shipp = &Ships[objp->instance];
12259
12260         //      Only small ships evade an incoming missile.  Why would a capital ship try to swerve?
12261         if (!(Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
12262                 return;
12263         }
12264
12265         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
12266                 return;
12267         }
12268
12269         if (aip->nearest_locked_object != -1) {
12270                 object  *missile_objp;
12271
12272                 missile_objp = &Objects[aip->nearest_locked_object];
12273
12274                 if (Weapons[missile_objp->instance].homing_object != objp) {
12275                         //nprintf(("AI", "\nMissile lost home!"));
12276                         aip->nearest_locked_object = -1;
12277                         return;
12278                 }
12279
12280                 if ((missile_objp->type == OBJ_WEAPON) && (Weapon_info[Weapons[missile_objp->instance].weapon_info_index].wi_flags & WIF_HOMING)) {
12281                         float dist = vm_vec_dist_quick(&missile_objp->pos, &objp->pos);
12282                         float dist2 = 4.0f  * vm_vec_mag_quick(&missile_objp->phys_info.vel);                   
12283                         if (dist < dist2) {
12284                                 switch (aip->mode) {
12285                                 //      If in AIM_STRAFE mode, don't evade if parent of weapon is targeted ship.
12286                                 case AIM_STRAFE:
12287                                         if ((missile_objp->parent != -1) && (missile_objp->parent == aip->target_objnum)) {
12288                                                 ;
12289                                         } else {
12290                                                 ;               //      Alan -- If you want to handle incoming weapons from someone other than the ship
12291                                                                 //      the strafing ship is attacking, do it here.
12292                                         }
12293                                         break;
12294                                 case AIM_CHASE:
12295                                         //      Don't always go into evade weapon mode.  Usually, a countermeasure gets launched.
12296                                         // If low on countermeasures, more likely to try to evade.  If 8+, never evade due to low cmeasures.
12297                                         if (((((Missiontime >> 18) ^ OBJ_INDEX(objp)) & 3) == 0) || 
12298                                                 (objp->phys_info.speed < 40.0f) ||
12299                                                 (frand() < 1.0f - (float) shipp->cmeasure_count/8.0f)) {
12300                                                 if (aip->submode != SM_ATTACK_FOREVER) {        //      SM_ATTACK_FOREVER means engines blown.
12301                                                         aip->submode = SM_EVADE_WEAPON;
12302                                                         aip->submode_start_time = Missiontime;
12303                                                 }
12304                                         }
12305                                         break;
12306                                 case AIM_DOCK:  //      Ships in dock mode can evade iif they are not currently repairing or docked.
12307                                         if (aip->ai_flags & (AIF_REPAIRING | AIF_DOCKED))
12308                                                 break;
12309                                 case AIM_GUARD:
12310                                         //      If in guard mode and far away from guard object, don't pursue guy that hit me.
12311                                         if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
12312                                                 if (vm_vec_dist_quick(&objp->pos, &Objects[aip->guard_objnum].pos) > 500.0f) {
12313                                                         return;
12314                                                 }
12315                                         }
12316                                 case AIM_EVADE:
12317                                 case AIM_GET_BEHIND:
12318                                 case AIM_STAY_NEAR:
12319                                 case AIM_STILL:
12320                                 case AIM_AVOID:
12321                                 case AIM_WAYPOINTS:
12322                                 case AIM_NONE:
12323                                 case AIM_BIGSHIP:
12324                                 case AIM_PATH:
12325                                 case AIM_BE_REARMED:
12326                                 case AIM_SAFETY:
12327                                 case AIM_BAY_EMERGE:
12328                                         aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
12329                                         aip->previous_mode = aip->mode;
12330                                         aip->previous_submode = aip->submode;
12331                                         aip->mode = AIM_EVADE_WEAPON;
12332                                         aip->submode = -1;
12333                                         aip->submode_start_time = Missiontime;
12334                                         aip->mode_time = timestamp(MAX_EVADE_TIME);     //      Max time to evade.
12335                                         //nprintf(("AI", "%s Evade weapon in frame #%i\n", Ships[objp->instance].ship_name, AI_FrameCount));
12336                                         break;
12337                                 case AIM_EVADE_WEAPON:          //      Note: We don't want to change mode on another evasion, or previous_mode will get bashed.
12338                                 case AIM_PLAY_DEAD:
12339                                 case AIM_BAY_DEPART:
12340                                 case AIM_SENTRYGUN:
12341                                         break;
12342                                 case AIM_WARP_OUT:
12343                                         break;
12344                                 default:
12345                                         Int3();                 //      Hey, what mode is it?
12346                                         break;
12347                                 }
12348                         }
12349                 } else {
12350                         aip->nearest_locked_object = -1;
12351                 }
12352         }
12353 }
12354
12355 //      Maybe evade a dumbfire weapon that was fired when Pl_objp was targeted.
12356 //      Have an 80% chance of evading in a second
12357 void maybe_evade_dumbfire_weapon(ai_info *aip)
12358 {
12359         //      Only small ships evade an incoming missile.  Why would a capital ship try to swerve?
12360         if (!(Ship_info[Ships[Pl_objp->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
12361                 return;
12362         }
12363
12364         //      Make sure in a mode in which we evade dumbfire weapons.
12365         switch (aip->mode) {
12366         case AIM_CHASE:
12367                 if (aip->submode == SM_ATTACK_FOREVER) {
12368                         return;
12369                 }
12370         case AIM_GUARD:
12371                 //      If in guard mode and far away from guard object, don't pursue guy that hit me.
12372                 if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
12373                         if (vm_vec_dist_quick(&Objects[Ships[aip->shipnum].objnum].pos, &Objects[aip->guard_objnum].pos) > 500.0f) {
12374                                 return;
12375                         }
12376                 }
12377         case AIM_STILL:
12378         case AIM_STAY_NEAR:
12379         case AIM_EVADE:
12380         case AIM_GET_BEHIND:
12381         case AIM_AVOID:
12382         case AIM_PATH:
12383         case AIM_NONE:
12384         case AIM_WAYPOINTS:
12385         case AIM_SAFETY:
12386                 break;
12387         case AIM_STRAFE:
12388         case AIM_BIGSHIP:
12389         case AIM_DOCK:
12390         case AIM_PLAY_DEAD:
12391         case AIM_EVADE_WEAPON:
12392         case AIM_BAY_EMERGE:
12393         case AIM_BAY_DEPART:
12394         case AIM_SENTRYGUN:
12395         case AIM_WARP_OUT:
12396                 return;
12397         default:
12398                 Int3(); //      Bogus mode!
12399                 return;
12400         }
12401
12402         if (is_instructor(&Objects[Ships[aip->shipnum].objnum]))
12403                 return; //      Instructor doesn't evade.
12404
12405         float t = ai_endangered_by_weapon(aip);
12406         if ((t > 0.0f) && (t < 1.0f)) {
12407         // Check if this weapon is from a large ship Pl_objp is attacking... if so, enter strafe mode
12408                 if ( ai_big_maybe_enter_strafe_mode(Pl_objp, aip->danger_weapon_objnum) ) {
12409                         return;
12410                 }
12411
12412                 switch (aip->mode) {
12413                 case AIM_CHASE:
12414                         switch (aip->submode) {
12415                         case SM_EVADE:
12416                         case SM_ATTACK_FOREVER:
12417                         case SM_AVOID:
12418                         case SM_GET_AWAY:
12419                         case SM_EVADE_WEAPON:
12420                                 break;
12421                         default:
12422                                 if (ai_near_full_strength(Pl_objp, &Ship_info[Ships[Pl_objp->instance].ship_info_index])) {
12423                                         //mprintf(("Ship %s entered super mode at %7.3f\n", Ships[Pl_objp->instance].ship_name, 1.0f * Missiontime / (1<<16)));
12424                                         aip->submode = SM_SUPER_ATTACK;
12425                                         aip->submode_start_time = Missiontime;
12426                                         aip->last_attack_time = Missiontime;
12427                                 } else {
12428                                         //mprintf(("Ship %s entered dumbfire evade mode at %7.3f\n", Ships[Pl_objp->instance].ship_name, 1.0f * Missiontime / (1<<16)));
12429                                         aip->submode = SM_EVADE_WEAPON;
12430                                         aip->submode_start_time = Missiontime;
12431                                 }
12432                                 break;
12433                         }
12434                         break;
12435                 case AIM_GUARD:
12436                 case AIM_STILL:
12437                 case AIM_STAY_NEAR:
12438                 case AIM_EVADE:
12439                 case AIM_GET_BEHIND:
12440                 case AIM_AVOID:
12441                 case AIM_PATH:
12442                 case AIM_NONE:
12443                 case AIM_WAYPOINTS:
12444                 case AIM_SAFETY:
12445                         if (!(aip->ai_flags & (AIF_NO_DYNAMIC | AIF_KAMIKAZE)) && (Ship_info[Ships[aip->shipnum].ship_info_index].flags & SIF_SMALL_SHIP)) {
12446                                 aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
12447                                 aip->previous_mode = aip->mode;
12448                                 aip->previous_submode = aip->submode;
12449                                 aip->mode = AIM_EVADE_WEAPON;
12450                                 aip->submode = -1;
12451                                 aip->submode_start_time = Missiontime;
12452                                 aip->mode_time = timestamp(MAX_EVADE_TIME);     //      Evade for up to five seconds.
12453                         }
12454                         break;
12455                 case AIM_STRAFE:
12456                 case AIM_BIGSHIP:
12457                 case AIM_DOCK:
12458                 case AIM_PLAY_DEAD:
12459                 case AIM_EVADE_WEAPON:
12460                 case AIM_BAY_EMERGE:
12461                 case AIM_BAY_DEPART:
12462                 case AIM_SENTRYGUN:
12463                         break;
12464                 default:
12465                         Int3(); //      Bogus mode!
12466                 }
12467         }
12468 }
12469
12470 // determine what path to use when emerging from a fighter bay
12471 // input:       pl_objp =>      pointer to object for ship that is arriving
12472 //                              pos             =>      output parameter, it is the starting world pos for path choosen
12473 //                              v.fvec          =>      output parameter, this is the forward vector that ship has when arriving
12474 //
12475 // exit:                -1              =>      path could not be located
12476 //                               0              => success
12477 int ai_acquire_emerge_path(object *pl_objp, int parent_objnum, vector *pos, vector *fvec)
12478 {
12479         int                     path_index, sb_path_index;
12480         ship                    *parent_sp = NULL;
12481         polymodel       *pm;
12482         ai_info         *aip;
12483         ship_bay                *sb;
12484         pnode                   *pnp;
12485         vector          *next_point;
12486
12487         aip = &Ai_info[Ships[pl_objp->instance].ai_index];
12488
12489         if ( parent_objnum == -1 ) {
12490                 Int3();
12491                 return -1;
12492         }
12493
12494         parent_sp = &Ships[Objects[parent_objnum].instance];
12495
12496         SDL_assert(parent_sp != NULL);
12497         pm = model_get( parent_sp->modelnum );
12498         sb = pm->ship_bay;
12499
12500         if ( sb == NULL ) 
12501                 return -1;
12502
12503         if ( sb->num_paths <= 0 ) 
12504                 return -1;
12505
12506         // try to find a bay path that is not taken
12507         path_index = -1;
12508         sb_path_index = Ai_last_arrive_path++;
12509
12510         if ( sb_path_index >= sb->num_paths ) {
12511                 sb_path_index=0;
12512                 Ai_last_arrive_path=0;
12513         }
12514
12515         path_index = sb->paths[sb_path_index];
12516         if ( path_index == -1 ) 
12517                 return -1;
12518
12519         // create the path for pl_objp to follow
12520         create_model_exit_path(pl_objp, &Objects[parent_objnum], path_index, pm->paths[path_index].nverts);
12521         
12522         // Set this flag, so we don't bother recreating the path... we won't need to update the path
12523         // that has just been created.
12524 //      aip->ai_flags |= AIF_USE_STATIC_PATH;
12525
12526         // now return to the caller what the starting world pos and starting fvec for the ship will be
12527         SDL_assert((aip->path_start >= 0) && (aip->path_start < MAX_PATH_POINTS));
12528         pnp = &Path_points[aip->path_start];
12529         *pos = pnp->pos;
12530
12531         // calc the forward vector using the starting two points of the path
12532         pnp = &Path_points[aip->path_start+1];
12533         next_point = &pnp->pos;
12534         vm_vec_normalized_dir(fvec, next_point, pos);
12535
12536         // record the parent objnum, since we'll need it once we're done with following the path
12537         aip->goal_objnum = parent_objnum;
12538         aip->goal_signature = Objects[parent_objnum].signature;
12539         aip->mode = AIM_BAY_EMERGE;
12540         aip->submode_start_time = Missiontime;
12541
12542         // set up starting vel
12543         vector vel;
12544         float speed;
12545         speed = Ship_info[Ships[pl_objp->instance].ship_info_index].max_speed;
12546         vel = *fvec;
12547         vm_vec_scale( &vel, speed );
12548         pl_objp->phys_info.vel = vel;
12549         pl_objp->phys_info.desired_vel = vel;
12550         pl_objp->phys_info.prev_ramp_vel.xyz.x = 0.0f;
12551         pl_objp->phys_info.prev_ramp_vel.xyz.y = 0.0f;
12552         pl_objp->phys_info.prev_ramp_vel.xyz.z = speed;
12553         pl_objp->phys_info.forward_thrust = 0.0f;               // How much the forward thruster is applied.  0-1.
12554
12555         return 0;       
12556 }
12557
12558 // clean up path data used for emerging from a fighter bay
12559 void ai_emerge_bay_path_cleanup(ai_info *aip)
12560 {
12561         aip->path_start = -1;
12562         aip->path_cur = -1;
12563         aip->path_length = 0;
12564         aip->mode = AIM_NONE;
12565 }
12566
12567 // handler for AIM_BAY_EMERGE
12568 void ai_bay_emerge()
12569 {
12570         ai_info *aip;
12571         int             parent_died=0;
12572
12573         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
12574
12575         // if no path to follow, leave this mode
12576         if ( aip->path_start < 0 ) {
12577                 aip->mode = AIM_NONE;
12578                 return;
12579         }
12580
12581         // ensure parent ship is still alive
12582         if ( aip->goal_objnum < 0 ) {
12583                 parent_died=1;
12584         } 
12585         if ( !parent_died ) {
12586                 if ( Objects[aip->goal_objnum].signature != aip->goal_signature ) {
12587                         parent_died=1;
12588                 }
12589         }
12590
12591         if ( !parent_died ) {
12592                 SDL_assert(Objects[aip->goal_objnum].type == OBJ_SHIP);
12593                 if ( Ships[Objects[aip->goal_objnum].instance].flags & SF_DYING ) {
12594                         parent_died = 1;
12595                 }
12596         }
12597
12598         if ( parent_died ) {
12599                 ai_emerge_bay_path_cleanup(aip);
12600                 return;
12601         }
12602
12603         // follow the path to the final point
12604         ai_path();
12605
12606         // New test: must have been in AI_EMERGE mode for at least 10 seconds, and be a minimum distance from the start point
12607         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)) {
12608                 // erase path
12609                 ai_emerge_bay_path_cleanup(aip);
12610         }
12611
12612         // 2-25-99: Need this check to fix an assert for supercap ships... maybe we'll only do this check for supercaps 
12613         if (aip->path_cur > (aip->path_start+aip->path_length-1)) {
12614                 ai_emerge_bay_path_cleanup(aip);
12615         }       
12616 }
12617
12618 // Select the closest depart path
12619 //
12620 //      input:  aip     =>              ai info pointer to ship seeking to depart
12621 //                              pm              =>              pointer to polymodel for the ship contining the ship bay/depart paths
12622 //
12623 // exit:                >=0     =>              ship bay path index for depart path (ie index into sb->paths[])
12624 //                              -1              =>              no path could be found
12625 //
12626 // NOTE: this function should only be used for calculating closest depart paths for ai mode
12627 //                      AI_BAY_DEPART.  It tries to find the closest path that isn't already in use
12628 int ai_find_closest_depart_path(ai_info *aip, polymodel *pm)
12629 {
12630         int                     i, j, best_path, best_free_path;
12631         float                   dist, min_dist, min_free_dist;
12632         vector          *source;
12633         model_path      *mp;
12634         ship_bay                *sb;
12635
12636         sb = pm->ship_bay;
12637
12638         best_free_path = best_path = -1;
12639         min_free_dist = min_dist = 1e20f;
12640         SDL_assert(aip->shipnum >= 0);
12641         source = &Objects[Ships[aip->shipnum].objnum].pos;
12642
12643         for ( i = 0; i < sb->num_paths; i++ ) {
12644
12645
12646                 mp = &pm->paths[sb->paths[i]];
12647                 for ( j = 0; j < mp->nverts; j++ ) {
12648                         dist = vm_vec_dist_squared(source, &mp->verts[j].pos);
12649
12650                         if ( dist < min_dist ) {
12651                                 min_dist = dist;
12652                                 best_path = i;
12653                         }
12654
12655                         // If this is a free path
12656                         if ( !(sb->depart_flags & (1<<i)) ) {
12657                                 if ( dist < min_free_dist ) {
12658                                         min_free_dist = dist;
12659                                         best_free_path = i;
12660                                 }
12661                         }
12662                 }
12663         }
12664
12665         if ( best_free_path >= 0 ) {
12666                 return best_free_path;          
12667         }
12668
12669         return best_path;
12670 }
12671
12672 // determine what path to use when trying to depart to a fighter bay
12673 // NOTE: this should be called when AIM_BAY_DEPART mode is set
12674 //
12675 // input:       pl_objp =>      pointer to object for ship that is departing
12676 //
12677 // exit:                -1      =>      could not find depart path
12678 //                              0       => found depart path
12679 int ai_acquire_depart_path(object *pl_objp, int parent_objnum)
12680 {
12681         int                     objnum, path_index;
12682         polymodel       *pm;
12683         ai_info         *aip;
12684         ship                    *sp;
12685         ship_bay                *sb;
12686
12687         aip = &Ai_info[Ships[pl_objp->instance].ai_index];
12688
12689         if ( parent_objnum == -1 ) {
12690                 ship_obj        *so;
12691
12692                 // for now just locate a captial ship on the same team:
12693                 so = GET_FIRST(&Ship_obj_list);
12694                 objnum = -1;
12695                 while(so != END_OF_LIST(&Ship_obj_list)){
12696                         sp = &Ships[Objects[so->objnum].instance];
12697                         if ( (Ship_info[sp->ship_info_index].flags & (SIF_HUGE_SHIP)) && (sp->team == Ships[pl_objp->instance].team) ) {
12698                                 objnum = so->objnum;
12699                                 break;
12700                         }
12701                         so = GET_NEXT(so);
12702                 } 
12703         } else {
12704                 objnum = parent_objnum;
12705         }
12706
12707         aip->path_start = -1;
12708
12709         if ( objnum == -1 )
12710                 return -1;
12711
12712         pm = model_get( Ships[Objects[objnum].instance].modelnum );
12713         sb = pm->ship_bay;
12714
12715         if ( sb == NULL ) 
12716                 return -1;
12717         if ( sb->num_paths <= 0 ) 
12718                 return -1;
12719
12720 /*
12721         
12722         path_index = -1;
12723         for ( i = 0; i < sb->num_paths; i++ ) {
12724                 if ( !(sb->depart_flags & (1<<i)) ) {
12725                         sb->depart_flags |= (1<<i);
12726                         path_index = sb->paths[i];
12727                         aip->submode_parm0 = i;                 // use mode-specific parameter to record ship bay path index
12728                         break;
12729                 }
12730         }
12731 */
12732         
12733         // take the closest path we can find
12734         int ship_bay_path;
12735         ship_bay_path = ai_find_closest_depart_path(aip, pm);
12736
12737         if (ship_bay_path == -1) {
12738                 return -1;
12739         }
12740
12741         path_index = sb->paths[ship_bay_path];
12742         aip->submode_parm0 = ship_bay_path;
12743         sb->depart_flags |= (1<<ship_bay_path);
12744
12745         if ( path_index == -1 ) {
12746                 return -1;
12747         }
12748
12749         SDL_assert(pm->n_paths > path_index);
12750         ai_find_path(pl_objp, objnum, path_index, 0);
12751
12752         // Set this flag, so we don't bother recreating the path... we won't need to update the path
12753         // that has just been created.
12754         aip->ai_flags &= ~AIF_USE_STATIC_PATH;
12755
12756         aip->goal_objnum = objnum;
12757         aip->goal_signature = Objects[objnum].signature;
12758         aip->mode = AIM_BAY_DEPART;
12759
12760         Ships[pl_objp->instance].flags |= SF_DEPART_DOCKBAY;
12761         return 0;
12762 }
12763
12764 // handler for AIM_BAY_DEPART
12765 void ai_bay_depart()
12766 {
12767         ai_info *aip;
12768
12769         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
12770
12771         // if no path to follow, leave this mode
12772         if ( aip->path_start < 0 ) {
12773                 aip->mode = AIM_NONE;
12774                 return;
12775         }
12776
12777         // check if parent ship still exists, if not abort depart 
12778         if ( aip->goal_signature != Objects[aip->goal_objnum].signature ) {
12779                 aip->mode = AIM_NONE;
12780                 return;
12781         }
12782
12783         // follow the path to the final point
12784         ai_path();
12785
12786         // if the final point is reached, let default AI take over
12787         if ( aip->path_cur >= (aip->path_start+aip->path_length) ) {
12788                 polymodel       *pm;
12789                 ship_bay                *sb;
12790
12791                 pm = model_get( Ships[Objects[aip->goal_objnum].instance].modelnum );
12792                 sb = pm->ship_bay;
12793                 if ( sb != NULL ) {
12794                         sb->depart_flags &= ~(1<<aip->submode_parm0);
12795                 }
12796
12797                 // make ship disappear
12798                 Pl_objp->flags |= OF_SHOULD_BE_DEAD;
12799                 ship_departed( Pl_objp->instance );
12800
12801                 // clean up path stuff
12802                 aip->path_start = -1;
12803                 aip->path_cur = -1;
12804                 aip->path_length = 0;
12805                 aip->mode = AIM_NONE;
12806         }
12807 }
12808
12809 // Handler for AIM_SENTRYGUN.  This AI mode is for sentry guns only (ie floating turrets).
12810 void ai_sentrygun()
12811 {
12812         // Nothing to do here.  Turret firing is handled via process_subobjects().
12813         // If you want the sentry guns to do anything beyond firing their turrets at enemies, add it here!
12814 }
12815
12816 //      --------------------------------------------------------------------------
12817 //      Execute behavior given by aip->mode.
12818 void ai_execute_behavior(ai_info *aip)
12819 {
12820         switch (aip->mode) {
12821         case AIM_CHASE:
12822                 if (En_objp) {
12823                         ai_chase();
12824                 } else if (aip->submode == SM_EVADE_WEAPON) {
12825                         evade_weapon();
12826                         // maybe reset submode
12827                         if (aip->danger_weapon_objnum == -1) {
12828                                 aip->submode = SM_ATTACK;
12829                                 aip->submode_start_time = Missiontime;
12830                                 aip->last_attack_time = Missiontime;
12831                         }
12832                 } else {
12833                         //      Don't circle if this is the instructor.
12834                         ship    *shipp = &Ships[aip->shipnum];
12835                         ship_info       *sip = &Ship_info[shipp->ship_info_index];
12836
12837                         if (SDL_strncasecmp(shipp->ship_name, INSTRUCTOR_SHIP_NAME, strlen(INSTRUCTOR_SHIP_NAME))) {
12838                                 if (sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
12839                                         aip->mode = AIM_NONE;
12840                                 } else {
12841                                         ai_chase_circle(Pl_objp);
12842                                 }
12843                         }
12844                 }
12845                 break;
12846         case AIM_EVADE:
12847                 if (En_objp) {
12848                         ai_evade();
12849                 } else {
12850                         vector  tvec;
12851                         vm_vec_scale_add(&tvec, &Pl_objp->pos, &Pl_objp->orient.v.rvec, 100.0f);
12852                         turn_towards_point(Pl_objp, &tvec, NULL, 0.0f);
12853                         accelerate_ship(aip, 0.5f);
12854                 }
12855                 break;
12856         case AIM_STILL:
12857                 ai_still();
12858                 break;
12859         case AIM_STAY_NEAR:
12860                 ai_stay_near();
12861                 break;
12862         case AIM_GUARD:
12863                 ai_guard();
12864                 break;
12865         case AIM_WAYPOINTS:
12866                 ai_waypoints();
12867                 break;
12868         case AIM_DOCK:
12869                 ai_dock();
12870                 break;
12871         case AIM_NONE:
12872                 // ai_formation();
12873                 break;
12874         case AIM_BIGSHIP:
12875                 ai_big_ship(Pl_objp);
12876                 break;
12877         case AIM_PATH: {
12878                 int path_num;
12879                 path_num = ai_return_path_num_from_dockbay(&Objects[aip->goal_objnum], 0);
12880                 ai_find_path(Pl_objp, aip->goal_objnum, path_num, 0);
12881                 ai_path();
12882                 break;
12883         }
12884         case AIM_SAFETY:
12885                 ai_safety();
12886                 break;
12887         case AIM_EVADE_WEAPON:
12888                 evade_weapon();
12889                 break;
12890         case AIM_STRAFE:
12891                 if (En_objp) {
12892                         SDL_assert(En_objp->type == OBJ_SHIP);
12893                         ai_big_strafe();        // strafe a big ship
12894                 } else {
12895                         aip->mode = AIM_NONE;
12896                 }
12897                 break;
12898         case AIM_BAY_EMERGE:
12899                 ai_bay_emerge();
12900                 break;
12901         case AIM_BAY_DEPART:
12902                 ai_bay_depart();
12903                 break;
12904         case AIM_SENTRYGUN:
12905                 ai_sentrygun();
12906                 break;
12907         case AIM_WARP_OUT:
12908                 break;          //      Note, handled directly from ai_frame().
12909         default:
12910                 Int3();         //      This should never happen -- MK, 5/12/97 
12911                 break;
12912         }
12913
12914         if ( !(ship_get_SIF(aip->shipnum) & SIF_NOT_FLYABLE) ) {
12915                 maybe_evade_dumbfire_weapon(aip);
12916         }
12917 }
12918
12919 //      Auxiliary function for maybe_request_support.
12920 //      Return 1 if subsystem "type" is worthy of repair, else return 0.
12921 //      Since subsystems cannot be repaired if they are at 0 strength, don't return 1 if subsystem is dead.
12922 int mrs_subsystem(ship *shipp, int type)
12923 {
12924         float   t;
12925
12926         t = ship_get_subsystem_strength(shipp, type);
12927
12928         if (t > 0.0f) {
12929                 return (int) ((1.0f - t) * 3);
12930         } else {
12931                 return 3;
12932         }
12933 }
12934
12935 //      Return number of ships on *objp's team that are currently rearming.
12936 int num_allies_rearming(object *objp)
12937 {
12938         ship_obj        *so;
12939         int             team;
12940         int             count = 0;
12941
12942         team = Ships[objp->instance].team;
12943
12944         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
12945                 object  *A;
12946                 
12947                 SDL_assert (so->objnum != -1);
12948                 A = &Objects[so->objnum];
12949
12950                 if (Ships[A->instance].team == team) {
12951                         if (Ai_info[Ships[A->instance].ai_index].ai_flags & (AIF_REPAIRING | AIF_AWAITING_REPAIR)) {
12952                                 count++;
12953                         }
12954                 }
12955         }
12956
12957         return count;
12958 }
12959
12960
12961 //      Maybe ship *objp should request support (rearm/repair).
12962 //      If it does, return TRUE, else return FALSE.
12963 int maybe_request_support(object *objp)
12964 {
12965         ship_info       *sip;
12966         ship                    *shipp;
12967         ai_info         *aip;
12968         int                     desire;
12969
12970         SDL_assert(objp->type == OBJ_SHIP);
12971         shipp = &Ships[objp->instance];
12972         aip = &Ai_info[shipp->ai_index];
12973         sip = &Ship_info[shipp->ship_info_index];
12974
12975         if (!timestamp_elapsed(aip->next_rearm_request_timestamp))
12976                 return 0;
12977
12978         //      Only fighters and bombers request support.
12979         if (!(sip->flags & (SIF_FIGHTER | SIF_BOMBER)))
12980                 return 0;
12981
12982         //      A ship that is currently awaiting does not need support!
12983         if (aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED))
12984                 return 0;
12985
12986         if (!is_support_allowed(objp))
12987                 return 0;
12988
12989         //if (shipp->team != TEAM_FRIENDLY)
12990         //      return 0;
12991
12992         //      Compute a desire value.
12993         //      Desire of 0 means no reason to request support.
12994         //      1 is slight, 2 more, etc.  Maximum is around 20.  Anything larger than 3 is pretty strong.
12995         desire = 0;
12996
12997         //      Set desire based on hull strength.
12998         //      No: We no longer repair hull, so this would cause repeated repair requests.
12999         //desire += 6 - (int) ((objp->hull_strength/sip->initial_hull_strength) * 6.0f);
13000
13001         //      Set desire based on key subsystems.
13002         desire += 2*mrs_subsystem(shipp, SUBSYSTEM_ENGINE);     //      Note, disabled engine forces repair request, regardless of nearby enemies.
13003         desire += mrs_subsystem(shipp, SUBSYSTEM_COMMUNICATION);
13004         desire += mrs_subsystem(shipp, SUBSYSTEM_WEAPONS);
13005         desire += mrs_subsystem(shipp, SUBSYSTEM_SENSORS);
13006
13007         //      Set desire based on percentage of secondary weapons.
13008         ship_weapon *swp = &shipp->weapons;
13009
13010         for ( int i = 0; i < swp->num_secondary_banks; i++ ) {
13011                 if (swp->secondary_bank_start_ammo[i] > 0) {
13012 //                      float r = (float) swp->secondary_bank_ammo[i]*Weapon_info[swp->secondary_bank_weapons[i]].cargo_size/swp->secondary_bank_capacity[i];
13013                         float r = (float) swp->secondary_bank_ammo[i]/swp->secondary_bank_start_ammo[i];
13014                         desire += (int) ((1.0f - r) * 3.0f);
13015                 }
13016         }
13017
13018         //      If no reason to repair, don't bother to see if it's safe to repair.
13019         if (desire == 0){
13020                 return 0;
13021         }
13022
13023         //      Compute danger threshold.
13024         //      Balance this with desire and maybe request support.
13025         if (ai_good_time_to_rearm( objp )) {
13026                 ai_issue_rearm_request(objp);
13027                 return 1;
13028         } else if (num_allies_rearming(objp) < 2) {
13029                 if (desire >= 8) {      //      guarantees disabled will cause repair request
13030                         ai_issue_rearm_request(objp);
13031                 } else if (desire >= 3) {               //      >= 3 means having a single subsystem fully blown will cause repair.
13032                         int     count;
13033                         int objnum = find_nearby_hostile(OBJ_INDEX(objp), get_enemy_team_mask(OBJ_INDEX(objp)), 2000.0f, &count);
13034
13035                         if ((objnum == -1) || (count < 2) || (vm_vec_dist_quick(&objp->pos, &Objects[objnum].pos) > 3000.0f*count/desire)) {
13036                                 ai_issue_rearm_request(objp);
13037                                 return 1;
13038                         } else {
13039                                 //nprintf(("AI", "Would like to rearm, but enemy only %7.3f units away.\n", vm_vec_dist_quick(&objp->pos, &Objects[objnum].pos)));
13040                         }
13041                 }
13042         }
13043
13044         return 0;
13045
13046 }
13047
13048 void ai_set_mode_warp_out(object *objp, ai_info *aip)
13049 {
13050         ai_abort_rearm_request(objp);
13051         if (aip->mode != AIM_WARP_OUT) {
13052                 aip->mode = AIM_WARP_OUT;
13053                 aip->submode = AIS_WARP_1;
13054         }
13055 }
13056
13057 //      Maybe warp ship out.
13058 //      Shivan and HoL fighter/bomber warp out if their weapons subsystems have been destroyed.
13059 void ai_maybe_warp_out(object *objp)
13060 {
13061         ship    *shipp;
13062
13063         // don't do anything if in a training mission.
13064         if ( The_mission.game_type & MISSION_TYPE_TRAINING )
13065                 return;
13066
13067         SDL_assert(objp->type == OBJ_SHIP);
13068
13069         shipp = &Ships[objp->instance];
13070         ai_info *aip = &Ai_info[shipp->ai_index];
13071
13072         if (aip->mode == AIM_WARP_OUT)
13073                 return;
13074
13075         //      If a support ship with no goals and low hull, warp out.  Be sure that there are no pending goals
13076         // in the support ships ai_goal array.  Just process this ships goals.
13077         ship_info       *sip = &Ship_info[shipp->ship_info_index];
13078         if (sip->flags & SIF_SUPPORT) {
13079                 if ( timestamp_elapsed(aip->warp_out_timestamp) ) {
13080                         ai_process_mission_orders( OBJ_INDEX(objp), aip );
13081                         if ( (aip->dock_objnum == -1) && (objp->hull_strength/sip->initial_hull_strength < 0.25f) ) {
13082                                 ai_set_mode_warp_out(objp, aip);
13083                         }
13084                 }
13085         }
13086
13087         //      Friendly don't warp out, they'll eventually request support.
13088         if (shipp->team == TEAM_FRIENDLY)
13089                 return;
13090
13091         if (!(shipp->flags & SF_DEPARTING)) {
13092                 ship_info       *sip;
13093
13094                 sip = &Ship_info[shipp->ship_info_index];
13095                 if (sip->flags & (SIF_FIGHTER | SIF_BOMBER)) {
13096                         if (aip->warp_out_timestamp == 0) {
13097                                 //if (ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS) == 0.0f) {
13098                                 //      aip->warp_out_timestamp = timestamp(((myrand() % 10) + 10) * 1000);
13099                                 //}
13100                         } else if (timestamp_elapsed(aip->warp_out_timestamp)) {
13101                                 ai_set_mode_warp_out(objp, aip);
13102                         }
13103                 }
13104         }
13105 }
13106
13107 //      Warp this ship out.
13108 void ai_warp_out(object *objp)
13109 {
13110         // if dying, don't warp out.
13111         if (Ships[objp->instance].flags & SF_DYING) {
13112                 return;
13113         }
13114
13115         ai_info *aip;
13116
13117         aip = &Ai_info[Ships[objp->instance].ai_index];
13118
13119         switch (aip->submode) {
13120         case AIS_WARP_1:
13121                 aip->force_warp_time = timestamp(10*1000);      //      Try to avoid a collision for up to ten seconds.
13122                 aip->submode = AIS_WARP_2;
13123                 break;
13124         case AIS_WARP_2:                        //      Make sure won't collide with any object.
13125                 if (timestamp_elapsed(aip->force_warp_time) || !collide_predict_large_ship(objp, objp->radius*2.0f + 100.0f)) {
13126                         aip->submode = AIS_WARP_3;
13127
13128                         // maybe recalculate collision pairs.
13129                         if (ship_get_warp_speed(objp) > ship_get_max_speed(&Ships[objp->instance])) {
13130                                 // recalculate collision pairs
13131                                 OBJ_RECALC_PAIRS(objp); 
13132                         }
13133
13134                         aip->force_warp_time = timestamp(4*1000);               //      Try to attain target speed for up to 4 seconds.
13135                 } else {
13136                         vector  goal_point;
13137                         vm_vec_scale_add(&goal_point, &objp->pos, &objp->orient.v.uvec, 100.0f);
13138                         turn_towards_point(objp, &goal_point, NULL, 0.0f);
13139                         accelerate_ship(aip, 0.0f);
13140                 }
13141                 break;
13142         case AIS_WARP_3:
13143                 //      Rampup desired_vel in here from current to desired velocity and set PF_USE_VEL. (not sure this is the right flag)
13144                 //      desired velocity is computed in shipfx_calculate_warp_time().  See shipfx#572 for sample code.
13145                 float   speed, goal_speed;
13146                 float shipfx_calculate_warp_speed(object*);
13147                 goal_speed = shipfx_calculate_warp_speed(objp);
13148
13149                 // HUGE ships go immediately to AIS_WARP_4
13150                 if (Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_HUGE_SHIP) {
13151                         aip->submode = AIS_WARP_4;
13152                         break;
13153                 }
13154                 //compute_warpout_stuff(objp, &goal_speed, &warp_time, &warp_pos);
13155                 //goal_speed = 80.0f;
13156                 //set_accel_for_target_speed(objp, 40.0f);
13157                 // 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
13158                 speed = goal_speed * flFrametime + objp->phys_info.speed * (1.0f - flFrametime);
13159                 vm_vec_copy_scale(&objp->phys_info.vel, &objp->orient.v.fvec, speed);
13160                 objp->phys_info.desired_vel = objp->phys_info.vel;
13161                 // nprintf(("AI", "Frame %i, speed = %7.3f, goal = %7.3f\n", Framecount, vm_vec_mag_quick(&objp->phys_info.vel), goal_speed));
13162                 if (timestamp_elapsed(aip->force_warp_time) || (fl_abs(objp->phys_info.speed - goal_speed) < 2.0f))
13163                         aip->submode = AIS_WARP_4;
13164                 break;
13165         case AIS_WARP_4: {
13166                 shipfx_warpout_start(objp);
13167                 aip->submode = AIS_WARP_5;
13168                 break;
13169         }
13170         case AIS_WARP_5:
13171                 break;
13172         default:
13173                 Int3();         //      Illegal submode for warping out.
13174         }
13175 }
13176
13177 //      Return object index of weapon that could produce a shockwave that should be known about to *objp.
13178 //      Return nearest one.
13179 int ai_find_shockwave_weapon(object *objp, ai_info *aip)
13180 {
13181         missile_obj     *mo;
13182         float   nearest_dist = 999999.9f;
13183         int     nearest_index = -1;
13184
13185         for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
13186                 object          *A;
13187                 weapon          *wp;
13188                 weapon_info     *wip;
13189         
13190                 SDL_assert(mo->objnum >= 0 && mo->objnum < MAX_OBJECTS);
13191                 A = &Objects[mo->objnum];
13192
13193                 SDL_assert(A->type == OBJ_WEAPON);
13194                 SDL_assert((A->instance >= 0) && (A->instance < MAX_WEAPONS));
13195                 wp = &Weapons[A->instance];
13196                 wip = &Weapon_info[wp->weapon_info_index];
13197                 SDL_assert( wip->subtype == WP_MISSILE );
13198
13199                 if (wip->shockwave_speed > 0.0f) {
13200                         float   dist;
13201
13202                         dist = vm_vec_dist_quick(&objp->pos, &A->pos);
13203                         if (dist < nearest_dist) {
13204                                 nearest_dist = dist;
13205                                 nearest_index = mo->objnum;
13206                         }
13207                 }
13208         }
13209
13210         return nearest_index;
13211
13212 }
13213
13214 #define EVADE_SHOCKWAVE_DAMAGE_THRESHOLD                100.0f
13215
13216 //      Tell all ships to avoid a big ship that is blowing up.
13217 //      Only avoid if shockwave is fairly large.
13218 //      OK to tell everyone to avoid.  If they're too far away, that gets cleaned up in the frame interval.
13219 void ai_announce_ship_dying(object *dying_objp)
13220 {
13221         float damage = ship_get_exp_damage(dying_objp);
13222         if (damage >= EVADE_SHOCKWAVE_DAMAGE_THRESHOLD) {
13223                 ship_obj        *so;
13224
13225                 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
13226                         if (Ship_info[Ships[Objects[so->objnum].instance].ship_info_index].flags & (SIF_SMALL_SHIP | SIF_FREIGHTER)) {
13227                                 ai_info *aip;
13228
13229                                 aip = &Ai_info[Ships[Objects[so->objnum].instance].ai_index];
13230
13231                                 if ( !(aip->ai_flags & (AIF_DOCKED|AIF_BEING_REPAIRED)) ) {
13232                                         aip->ai_flags |= AIF_AVOID_SHOCKWAVE_SHIP;
13233                                 }
13234                         }
13235                 }
13236         }
13237 }
13238
13239
13240 //      Return object index of weapon that could produce a shockwave that should be known about to *objp.
13241 //      Return nearest one.
13242 int ai_find_shockwave_ship(object *objp, ai_info *aip)
13243 {
13244         ship_obj        *so;
13245         float   nearest_dist = 999999.9f;
13246         int     nearest_index = -1;
13247
13248         for ( so = GET_NEXT(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
13249                 object          *A;
13250                 ship                    *shipp;
13251         
13252                 SDL_assert(so->objnum >= 0 && so->objnum < MAX_OBJECTS);
13253                 A = &Objects[so->objnum];
13254
13255                 SDL_assert(A->type == OBJ_SHIP);
13256                 SDL_assert((A->instance >= 0) && (A->instance < MAX_SHIPS));
13257                 shipp = &Ships[A->instance];
13258                 //      Only look at objects in the process of dying.
13259                 if (shipp->flags & SF_DYING) {
13260                         float damage = ship_get_exp_damage(objp);
13261
13262                         if (damage >= EVADE_SHOCKWAVE_DAMAGE_THRESHOLD) {               //      Only evade quite large blasts
13263                                 float   dist;
13264
13265                                 dist = vm_vec_dist_quick(&objp->pos, &A->pos);
13266                                 if (dist < nearest_dist) {
13267                                         nearest_dist = dist;
13268                                         nearest_index = so->objnum;
13269                                 }
13270                         }
13271                 }
13272         }
13273
13274         return nearest_index;
13275
13276 }
13277
13278 int aas_1(object *objp, ai_info *aip, vector *safe_pos)
13279 {
13280         // MAKE SURE safe_pos DOES NOT TAKE US TOWARD THE A SHIP WE'RE ATTACKING.
13281         if (aip->ai_flags & AIF_AVOID_SHOCKWAVE_WEAPON) {
13282                 //      If we don't currently know of a weapon to avoid, try to find one.
13283                 //      If we can't find one, then clear the bit so we don't keep coming here.
13284                 if (aip->shockwave_object == -1) {
13285                         int shockwave_weapon = ai_find_shockwave_weapon(objp, aip);
13286                         if (shockwave_weapon == -1) {
13287                                 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13288                                 return 0;
13289                         } else {
13290                                 aip->shockwave_object = shockwave_weapon;
13291                         }
13292                 }
13293
13294                 //      OK, we have reason to believe we should avoid aip->shockwave_object.
13295                 SDL_assert(aip->shockwave_object > -1);
13296                 object  *weapon_objp = &Objects[aip->shockwave_object];
13297                 if (weapon_objp->type != OBJ_WEAPON) {
13298                         aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13299                         aip->shockwave_object = -1;
13300                         return 0;
13301                 }
13302
13303                 weapon  *weaponp = &Weapons[weapon_objp->instance];
13304                 weapon_info     *wip = &Weapon_info[weaponp->weapon_info_index];
13305                 object *target_ship_obj = NULL;
13306
13307                 if (wip->shockwave_speed == 0.0f) {
13308                         aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13309                         aip->shockwave_object = -1;
13310                         return 0;
13311                 }
13312
13313                 float   danger_dist;
13314                 vector  expected_pos;           //      Position at which we expect the weapon to detonate.
13315                 int             pos_set = 0;
13316
13317                 danger_dist = wip->outer_radius;
13318                 //      Set predicted position of detonation.
13319                 //      If an aspect locked missile, assume it will detonate at the homing position.
13320                 //      If not, which is not possible in a default FreeSpace weapon, then predict it will detonate at some
13321                 //      time in the future, this time based on max lifetime and life left.
13322                 if (wip->wi_flags & WIF_HOMING_ASPECT) {
13323                         expected_pos = weaponp->homing_pos;
13324                         if (weaponp->homing_object && weaponp->homing_object->type == OBJ_SHIP) {
13325                                 target_ship_obj = weaponp->homing_object;
13326                         }
13327                         pos_set = 1;
13328                         if (IS_VEC_NULL(&weaponp->homing_pos)) {
13329                                 pos_set = 0;
13330                                 if (weaponp->target_num != -1) {
13331                                         if (Objects[weaponp->target_num].type == OBJ_SHIP) {
13332                                                 target_ship_obj = &Objects[weaponp->target_num];
13333                                                 expected_pos = target_ship_obj->pos;
13334                                                 pos_set = 1;
13335                                         }
13336                                 }
13337                         }
13338                 }
13339
13340                 if (!pos_set) {
13341                         float   time_scale;
13342
13343                         if (wip->lifetime - weaponp->lifeleft > 5.0f) {
13344                                 time_scale = 1.0f;
13345                         } else {
13346                                 time_scale = weaponp->lifeleft/2.0f;
13347                         }
13348
13349                         vm_vec_scale_add(&expected_pos, &weapon_objp->pos, &weapon_objp->orient.v.fvec, time_scale);
13350                 }
13351
13352                 //      See if too far away to care about shockwave.
13353                 if (vm_vec_dist_quick(&objp->pos, &expected_pos) > danger_dist*2.0f) {
13354                         //aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13355                         return 0;
13356                 } else {
13357                         // try to find a safe position
13358                         vector vec_from_exp;
13359                         float dir = 1.0f;
13360                         vm_vec_sub(&vec_from_exp, &objp->pos, &expected_pos);
13361                         float dot = vm_vec_dotprod(&vec_from_exp, &weapon_objp->orient.v.fvec);
13362                         if (dot > -30) {
13363                                 // if we're already on the other side of the explosion, don't try to fly behind it
13364                                 dir = -1.0f;
13365                         }
13366
13367                         //      Fly towards a point behind the weapon.
13368                         vm_vec_scale_add(safe_pos, &weapon_objp->pos, &weapon_objp->orient.v.fvec, -50000.0f*dir);
13369
13370                         // verify safe_pos will not make us collide with our target objnum, else try 2 other vecs
13371                         // don't bang your head, else go
13372 //                      int go_safe = FALSE;
13373                         int go_safe = TRUE;
13374 /*                      if (target_ship_obj) {
13375                                 if (pp_collide(&objp->pos, safe_pos, target_ship_obj, objp->radius)) {
13376                                         // try up to 2 other random directions
13377                                         vector dir_vec, rand_vec;
13378                                         int idx;
13379                                         for (idx=0; idx<2; idx++) {
13380                                                 vm_vec_rand_vec_quick(&rand_vec);
13381                                                 vm_vec_scale_add(&dir_vec, &weapon_objp->orient.v.fvec, &rand_vec, 0.5f);
13382                                                 vm_vec_scale_add(safe_pos, &weapon_objp->pos, &dir_vec, -50000.0f*dir);
13383                                                 if ( !pp_collide(&objp->pos, safe_pos, target_ship_obj, objp->radius) ) {
13384                                                         go_safe = TRUE;
13385                                                         break;
13386                                                 }
13387                                         }
13388                                 } else { // direct path is safe
13389                                         go_safe = TRUE;
13390                                 }
13391                         } else { // no target_obj_ship
13392                                 go_safe = TRUE;
13393                         } */
13394
13395                         if (go_safe) {
13396                                 return 1;
13397                         } else {
13398                                 // can't figure out a good way to go
13399                                 return 0;
13400                         }
13401                 }
13402         } else if (aip->ai_flags & AIF_AVOID_SHOCKWAVE_SHIP) {
13403                 if (aip->shockwave_object == -1) {
13404                         int shockwave_ship = ai_find_shockwave_ship(objp, aip);
13405                         if (shockwave_ship == -1) {
13406                                 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_SHIP;
13407                                 return 0;
13408                         } else {
13409                                 aip->shockwave_object = shockwave_ship;
13410                         }
13411                 }
13412
13413                 SDL_assert(aip->shockwave_object > -1);
13414                 object  *ship_objp = &Objects[aip->shockwave_object];
13415                 if (ship_objp == objp) {
13416                         aip->shockwave_object = -1;
13417                         return 0;
13418                 }
13419
13420                 if (ship_objp->type != OBJ_SHIP) {
13421                         aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_SHIP;
13422                         return 0;
13423                 }
13424
13425                 //      Optimize note! Don't really have to normalize.  We only need a point away from the blowing-up ship.
13426                 vector safe_vec;
13427
13428                 vm_vec_normalized_dir(&safe_vec, &objp->pos, &ship_objp->pos);
13429                 vm_vec_scale_add(safe_pos, &ship_objp->pos, &safe_vec, 50000.0f);       //      Fly away from the ship.
13430
13431                 float outer_rad = ship_get_exp_outer_rad(ship_objp);
13432
13433                 if (vm_vec_dist_quick(&objp->pos, &ship_objp->pos) > outer_rad*1.5f) {
13434                         aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13435                         return 0;
13436                 }
13437
13438                 return 1;
13439
13440         } else {
13441                 Int3(); //      Illegal -- supposedly avoiding a shockwave, but neither ship nor weapon.  What is it!?
13442         }
13443
13444         return 0;
13445 }
13446
13447 /*
13448 int rct_done = 0;
13449
13450 void rand_chance_test()
13451 {
13452         int     i;
13453         float   frametime;
13454
13455         if (rct_done)
13456                 return;
13457
13458         rct_done = 1;
13459
13460         for (frametime=0.02f; frametime<0.25f; frametime *= 1.25f) {
13461                 float   chance;
13462
13463                 nprintf(("AI", "%6.4f: ", frametime));
13464                 for (chance=0.25f; chance<2.5f; chance += 0.25f) {
13465                         int count = 0;
13466
13467                         for (i=0; i<100.0f/frametime; i++) {
13468                                 if (rand_chance(frametime, chance))
13469                                         count++;
13470                         }
13471                         nprintf(("AI", "%3i ", count));
13472                 }
13473                 nprintf(("AI", "\n"));
13474         }
13475 }
13476 */
13477
13478 //      --------------------------------------------------------------------------
13479 //      Make object *objp avoid the nearest dangerous shockwave-producing weapon.
13480 //      If it looks like there is no valid shockwave-producing weapon then clear the AIF_AVOID_SHOCKWAVE_WEAPON bit in ai_flags and return.
13481 //      Return 1 if avoiding a shockwave, else return 0.
13482 int ai_avoid_shockwave(object *objp, ai_info *aip)
13483 {
13484         vector  safe_pos;
13485
13486         //rand_chance_test();
13487         // BIG|HUGE do not respond to shockwaves
13488         if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) {
13489                 // don't come here again
13490                 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE;
13491                 return 0;
13492         }
13493
13494         //      Don't all react right away.
13495         if (!(aip->ai_flags & AIF_AVOID_SHOCKWAVE_STARTED))
13496                 if (!rand_chance(flFrametime, (float) aip->ai_class/4.0f + 0.25f))      //      Chance to avoid in 1 second is 0.25 + ai_class/4
13497                         return 0;
13498
13499         if (!aas_1(objp, aip, &safe_pos)) {
13500                 aip->ai_flags |= AIF_AVOID_SHOCKWAVE_STARTED;
13501                 return 0;
13502         }
13503
13504         aip->ai_flags |= AIF_AVOID_SHOCKWAVE_STARTED;
13505
13506         //      OK, evade the shockwave!
13507         turn_towards_point(objp, &safe_pos, NULL, 0.0f);
13508         vector  vec_to_safe_pos;
13509         float           dot_to_goal;
13510
13511         vm_vec_normalized_dir(&vec_to_safe_pos, &safe_pos, &objp->pos);
13512
13513         dot_to_goal = vm_vec_dot(&objp->orient.v.fvec, &vec_to_safe_pos);
13514         if (dot_to_goal < -0.5f)
13515                 accelerate_ship(aip, 0.3f);
13516         else {
13517                 accelerate_ship(aip, 1.0f + dot_to_goal);
13518                 if (dot_to_goal > 0.2f) {
13519                         if (!(objp->phys_info.flags & PF_AFTERBURNER_ON )) {
13520                                 afterburners_start(objp);
13521                                 aip->afterburner_stop_time = Missiontime + 2*F1_0;
13522                         }
13523                 }
13524         }
13525
13526         return 1;
13527 }
13528
13529 //      Awaiting repair.  Be useful.
13530 //      Probably fly towards incoming repair ship.
13531 //      Return true if this ship is close to being repaired, else return false.
13532 int ai_await_repair_frame(object *objp, ai_info *aip)
13533 {
13534         if (!(aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED)))
13535                 return 0;
13536
13537         if (aip->dock_objnum == -1)
13538                 return 0;
13539
13540         ship    *shipp;
13541         ship_info       *sip;
13542
13543         shipp = &Ships[Objects[aip->dock_objnum].instance];
13544         sip = &Ship_info[shipp->ship_info_index];
13545
13546         aip->ai_flags &= ~AIF_FORMATION_OBJECT; //      Prevents endless rotation.
13547
13548         if (!(sip->flags & SIF_SUPPORT))
13549                 return 0;
13550
13551         vector  goal_point;
13552         object  *repair_objp;
13553
13554         repair_objp = &Objects[aip->dock_objnum];
13555
13556         if (Ships[repair_objp->instance].team == TEAM_TRAITOR) {
13557                 ai_abort_rearm_request(repair_objp);
13558                 return 0;
13559         }
13560
13561         vm_vec_scale_add(&goal_point, &repair_objp->pos, &repair_objp->orient.v.uvec, -50.0f);  //      Fly towards point below repair ship.
13562
13563         vector  vtr;
13564         float dist = vm_vec_normalized_dir(&vtr, &goal_point, &objp->pos);
13565         float dot = vm_vec_dot(&vtr, &objp->orient.v.fvec);
13566
13567         if (dist > 200.0f) {
13568                 //nprintf(("AI", "%s flying towards %s for repair, dist = %7.3f\n", Ships[objp->instance].ship_name, &Ships[repair_objp->instance].ship_name, dist));
13569                 accelerate_ship(aip, (0.9f + dot) * dist/1500.0f);
13570                 turn_towards_point(objp, &goal_point, NULL, 0.0f);
13571         } else {
13572                 accelerate_ship(aip, 0.0f);
13573                 //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));
13574         }
13575
13576         return 1;
13577 }
13578
13579 //      Maybe cause this ship to self-destruct.
13580 //      Currently, any small ship (SIF_SMALL_SHIP) that has been disabled will self-destruct after awhile.
13581 //      Maybe should only do this if they are preventing their wing from re-entering.
13582 void ai_maybe_self_destruct(object *objp, ai_info *aip)
13583 {
13584         //      Friendly ships can be repaired, so no self-destruct.
13585         //      In multiplayer, just don't self-destruct.  I figured there would be a problem. -- MK, 3/19/98.
13586         if ((Ships[objp->instance].team == TEAM_FRIENDLY) || (Game_mode & GM_MULTIPLAYER))
13587                 return;
13588
13589         //      Small ships in a wing blow themselves up after awhile if engine or weapons system has been destroyed.
13590         //      Reason: Don't want them to prevent a re-emergence of the wing.
13591         //      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
13592         //      mission would be broken.
13593         if ((Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_SMALL_SHIP) && (Ships[objp->instance].wingnum != -1)) {
13594                 if ((ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) ||
13595                         (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_WEAPONS) <= 0.0f)) {
13596                         if (aip->self_destruct_timestamp < 0)
13597                                 aip->self_destruct_timestamp = timestamp(90 * 1000);    //      seconds until self-destruct
13598                 } else {
13599                         aip->self_destruct_timestamp = -1;
13600                 }
13601
13602                 if (aip->self_destruct_timestamp < 0) {
13603                         return;
13604                 }
13605
13606                 if (timestamp_elapsed(aip->self_destruct_timestamp)) {
13607                         ship_apply_local_damage( objp, objp, &objp->pos, objp->hull_strength*flFrametime + 1.0f, MISS_SHIELDS);
13608                 }
13609         }
13610 }
13611
13612 // Determine if pl_objp needs a new target, called from ai_frame()
13613 int ai_need_new_target(object *pl_objp, int target_objnum)
13614 {
13615         object *objp;
13616
13617         if ( target_objnum < 0 ) {
13618                 return 1;
13619         }
13620
13621         objp = &Objects[target_objnum];
13622
13623         if ( (objp->type != OBJ_SHIP) && (objp->type != OBJ_ASTEROID) && (objp->type != OBJ_WEAPON) ) {
13624                 return 1;
13625         }
13626
13627         if ( objp->type == OBJ_SHIP ) {
13628                 if ( Ships[objp->instance].flags & SF_DYING ) {
13629                         return 1;
13630                 } else if (Ships[objp->instance].team == Ships[pl_objp->instance].team)
13631                         return 1;
13632         }
13633
13634         return 0;
13635 }
13636
13637 //      If *objp is recovering from a collision with a big ship, handle it.
13638 //      Return true if recovering.
13639 int maybe_big_ship_collide_recover_frame(object *objp, ai_info *aip)
13640 {
13641         float   dot, dist;
13642         vector  v2g;
13643         
13644         if (aip->ai_flags & AIF_BIG_SHIP_COLLIDE_RECOVER_1) {
13645                 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);
13646                 dist = vm_vec_normalized_dir(&v2g, &aip->big_recover_pos_1, &objp->pos);
13647                 dot = vm_vec_dot(&objp->orient.v.fvec, &v2g);
13648                 accelerate_ship(aip, dot);
13649
13650                 //      If close to desired point, or 15+ seconds since entered this mode, continue to next mode.
13651                 if ((timestamp_until(aip->big_recover_timestamp) < -15*1000) || (dist < (0.5f + flFrametime) * objp->phys_info.speed)) {
13652                         aip->ai_flags &= ~AIF_BIG_SHIP_COLLIDE_RECOVER_1;
13653                         aip->ai_flags |= AIF_BIG_SHIP_COLLIDE_RECOVER_2;
13654                 }
13655
13656                 return 1;
13657
13658         } else if (aip->ai_flags & AIF_BIG_SHIP_COLLIDE_RECOVER_2) {
13659                 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);
13660                 dist = vm_vec_normalized_dir(&v2g, &aip->big_recover_pos_2, &objp->pos);
13661                 dot = vm_vec_dot(&objp->orient.v.fvec, &v2g);
13662                 accelerate_ship(aip, dot);
13663
13664                 //      If close to desired point, or 30+ seconds since started avoiding collision, done avoiding.
13665                 if ((timestamp_until(aip->big_recover_timestamp) < -30*1000) || (dist < (0.5f + flFrametime) * objp->phys_info.speed)) {
13666                         aip->ai_flags &= ~AIF_BIG_SHIP_COLLIDE_RECOVER_2;
13667                         aip->ai_flags &= ~AIF_TARGET_COLLISION;
13668                 }
13669
13670                 return 1;
13671         }
13672
13673         if (aip->ai_flags & AIF_TARGET_COLLISION) {
13674                 aip->ai_flags &= ~AIF_TARGET_COLLISION;
13675         }
13676         return 0;
13677 }
13678
13679 void validate_mode_submode(ai_info *aip)
13680 {
13681         switch (aip->mode) {
13682         case AIM_CHASE:
13683                 // check valid submode
13684                 switch (aip->submode) {
13685                 case SM_CONTINUOUS_TURN:
13686                 case SM_ATTACK:
13687                 case SM_EVADE_SQUIGGLE:
13688                 case SM_EVADE_BRAKE:    
13689                 case SM_EVADE:          
13690                 case SM_SUPER_ATTACK:
13691                 case SM_AVOID:  
13692                 case SM_GET_BEHIND:
13693                 case SM_GET_AWAY:               
13694                 case SM_EVADE_WEAPON:
13695                 case SM_FLY_AWAY:       
13696                 case SM_ATTACK_FOREVER:
13697                         break;
13698                 default:
13699                         Int3();
13700                 }
13701                 break;
13702
13703         case AIM_STRAFE:
13704                 // check valid submode
13705                 switch(aip->submode) {
13706                 case AIS_STRAFE_ATTACK:
13707                 case AIS_STRAFE_AVOID:
13708                 case AIS_STRAFE_RETREAT1:
13709                 case AIS_STRAFE_RETREAT2:
13710                 case AIS_STRAFE_POSITION:
13711                         break;
13712                 default:
13713                         Int3();
13714                 }
13715                 break;
13716         }
13717 }
13718
13719 //      --------------------------------------------------------------------------
13720 // Process AI object "objnum".
13721 void ai_frame(int objnum)
13722 {
13723         ship            *shipp = &Ships[Objects[objnum].instance];
13724         ai_info *aip = &Ai_info[shipp->ai_index];
13725         int             target_objnum;
13726
13727 //      validate_mode_submode(aip);
13728
13729         SDL_assert((aip->mode != AIM_WAYPOINTS) || (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC));
13730
13731         // Set globals defining the current object and its enemy object.
13732         Pl_objp = &Objects[objnum];
13733
13734         if (aip->mode == AIM_WARP_OUT) {
13735                 ai_warp_out(Pl_objp);
13736                 return;
13737         }
13738
13739 /*      //      HACK! TEST! REMOVE ME!
13740         if (Ship_info[shipp->ship_info_index].flags & SIF_BIG_SHIP)
13741                 if (shipp->team == Player_ship->team)
13742                         aip->mode = AIM_CHASE;
13743 */
13744
13745 //      if (!SDL_strncasecmp(Ships[Pl_objp->instance].ship_name, "cancer", 6))
13746 //              nprintf(("AI", "Ship %s: mode = %s, submode = %i\n", Ships[Pl_objp->instance].ship_name, Mode_text[aip->mode], aip->submode));
13747
13748         ai_maybe_self_destruct(Pl_objp, aip);
13749
13750 //      if ( timestamp_elapsed(aip->goal_check_time) ) {
13751                 ai_process_mission_orders( objnum, aip );
13752 //              aip->goal_check_time = timestamp_rand(1000,2000);
13753 //      }
13754
13755         //      Avoid a shockwave, if necessary.  If a shockwave and rearming, stop rearming.
13756         if (aip->ai_flags & AIF_AVOID_SHOCKWAVE) {
13757                 if (ai_avoid_shockwave(Pl_objp, aip)) {
13758                         aip->ai_flags &= ~(AIF_BIG_SHIP_COLLIDE_RECOVER_1 | AIF_BIG_SHIP_COLLIDE_RECOVER_2);
13759                         if (aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED))
13760                                 ai_abort_rearm_request(Pl_objp);
13761                         return;
13762                 }
13763         } else {
13764                 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_STARTED;
13765         }
13766
13767         // moved call to ai_do_repair frame here from below because of the subsequent if statment returning
13768         // if the ship is getting repaired
13769         //      If waiting to be repaired, just stop and sit.
13770         ai_do_repair_frame(Pl_objp, aip, flFrametime);
13771         if ((aip->ai_flags & AIF_AWAITING_REPAIR) || (aip->ai_flags & AIF_BEING_REPAIRED)) {
13772                 if (ai_await_repair_frame(Pl_objp, aip))
13773                         return;
13774         }
13775
13776         if (aip->mode == AIM_PLAY_DEAD)
13777                 return;
13778
13779         //      If recovering from a collision with a big ship, don't continue.
13780         if (maybe_big_ship_collide_recover_frame(Pl_objp, aip))
13781                 return;
13782
13783         ai_preprocess_ignore_objnum(Pl_objp, aip);
13784         target_objnum = set_target_objnum(aip, aip->target_objnum);
13785
13786         // 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));
13787
13788         SDL_assert(objnum != target_objnum);
13789
13790         ai_manage_shield(Pl_objp, aip);
13791         
13792         if ( maybe_request_support(Pl_objp) ) {
13793                 if ( Ships[Pl_objp->instance].flags & SF_FROM_PLAYER_WING ) {
13794                         ship_maybe_tell_about_rearm(shipp);
13795                 }
13796         }
13797
13798         ai_maybe_warp_out(Pl_objp);
13799
13800 /*
13801         //      If this ship is attacking an object's subsystems and someone else destroyed
13802         //      the subsystem, it could continue attacking the ship.  Need to invalidate the objnum.
13803         if (target_objnum >= 0)
13804                 if (Objects[target_objnum].flags & OF_PROTECTED) {
13805                         // if (aip->targeted_subsys != NULL)
13806                         //      ; //nprintf(("AI", "subsys hits = %7.3f\n", aip->targeted_subsys->current_hits));
13807
13808                         if ((aip->targeted_subsys == NULL) || (aip->targeted_subsys->current_hits <= 0.0f)) {
13809                                 target_objnum = -1;
13810                                 aip->target_objnum = -1;
13811                         }
13812                 }
13813 */
13814
13815
13816         //      Find an enemy if don't already have one.
13817         En_objp = NULL;
13818         if ( ai_need_new_target(Pl_objp, target_objnum) ) {
13819                 if ((aip->mode != AIM_EVADE_WEAPON) && (aip->active_goal == AI_ACTIVE_GOAL_DYNAMIC)) {
13820                         aip->resume_goal_time = -1;
13821                         aip->active_goal = AI_GOAL_NONE;
13822                 } else if (aip->resume_goal_time == -1) {
13823                         // AL 12-9-97: Don't allow cargo and navbuoys to set their aip->target_objnum
13824                         if ( !(Ship_info[shipp->ship_info_index].flags & SIF_HARMLESS) ) {
13825                                 target_objnum = find_enemy(objnum, MAX_ENEMY_DISTANCE, Skill_level_max_attackers[Game_skill_level]);            //      Attack up to 25K units away.
13826                                 if (target_objnum != -1) {
13827                                         if (aip->target_objnum != target_objnum)
13828                                                 aip->aspect_locked_time = 0.0f;
13829                                         set_target_objnum(aip, target_objnum);
13830                                         En_objp = &Objects[target_objnum];
13831                                 }
13832                         }
13833                 }
13834         } else if (target_objnum >= 0) {
13835                 En_objp = &Objects[target_objnum];
13836         }
13837
13838         // set base stealth info each frame
13839         aip->ai_flags &= ~AIF_STEALTH_PURSIUT;
13840         if (En_objp && En_objp->type == OBJ_SHIP) {
13841                 if (Ship_info[Ships[En_objp->instance].ship_info_index].flags & SIF_STEALTH) {
13842                         int stealth_state = ai_is_stealth_visible(Pl_objp, En_objp);
13843                         float dist = vm_vec_dist_quick(&En_objp->pos, &Pl_objp->pos);
13844
13845                         if (stealth_state != STEALTH_FULLY_TARGETABLE) {
13846                                 aip->ai_flags |= AIF_STEALTH_PURSIUT;
13847                         }
13848
13849                         if ( (stealth_state == STEALTH_FULLY_TARGETABLE) || (stealth_state == STEALTH_VISIBLE) ) {
13850                                 aip->stealth_last_visible_stamp = timestamp();
13851                                 aip->stealth_last_cheat_visible_stamp = aip->stealth_last_visible_stamp;
13852                                 aip->stealth_last_pos = En_objp->pos;
13853                                 aip->stealth_velocity = En_objp->phys_info.vel;
13854                         } else if (dist < 100) {
13855                                 // get cheat timestamp
13856                                 aip->stealth_last_cheat_visible_stamp = timestamp();
13857
13858                                 // set approximate pos and vel, with increasing error as time from last_visible_stamp increases
13859                                 update_ai_stealth_info_with_error(aip/*, 0*/);
13860                         }
13861                 }
13862         }
13863
13864         /*      if ((Pl_objp != NULL) && (En_objp != NULL)) {
13865                 slide_face_ship();
13866                 return;
13867         }
13868 */
13869         // AL 12-10-97: ensure that cargo and navbuoys aip->target_objnum is always -1.
13870         if ( Ship_info[shipp->ship_info_index].flags & SIF_HARMLESS ) {
13871                 aip->target_objnum = -1;
13872         }
13873
13874         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)) {
13875                 mprintf(("Warning: Object and its enemy have same position.  Object #%i\n", Pl_objp-Objects));
13876                 En_objp = NULL;
13877         }
13878
13879         if (aip->mode == AIM_CHASE) {
13880                 if (En_objp == NULL) {
13881                         aip->active_goal = -1;
13882                 }
13883         }
13884
13885         //      If there is a goal to resume and enough time has elapsed, resume the goal.
13886         if ((aip->resume_goal_time > 0) && (aip->resume_goal_time < Missiontime)) {
13887                 aip->active_goal = AI_GOAL_NONE;
13888                 aip->resume_goal_time = -1;
13889                 target_objnum = find_enemy(objnum, 2000.0f, Skill_level_max_attackers[Game_skill_level]);
13890                 if (target_objnum != -1) {
13891                         if (aip->target_objnum != target_objnum) {
13892                                 aip->aspect_locked_time = 0.0f;
13893                         }
13894                         set_target_objnum(aip, target_objnum);
13895                 }
13896         }
13897
13898         // check if targeted subsystem has been destroyed, if so, move onto another subsystem
13899         // if trying to disable or disarm the target
13900         if ((En_objp != NULL) && ( aip->targeted_subsys != NULL )) {
13901                 SDL_assert(En_objp->type == OBJ_SHIP);
13902                 if ( aip->targeted_subsys->current_hits <= 0.0f ) {
13903                         int subsys_type;
13904
13905                         if ( aip->goals[0].ai_mode == AI_GOAL_DISABLE_SHIP ) {
13906                                 subsys_type = SUBSYSTEM_ENGINE;
13907                         } else if ( aip->goals[0].ai_mode == AI_GOAL_DISARM_SHIP ) {
13908                                 subsys_type = SUBSYSTEM_TURRET;
13909                         } else {
13910                                 subsys_type = -1;
13911                         }
13912
13913                         if ( subsys_type != -1 ) {
13914                                 ship_subsys *new_subsys;
13915                                 new_subsys = ship_return_next_subsys(&Ships[En_objp->instance], subsys_type, &Pl_objp->pos);
13916                                 if ( new_subsys != NULL ) {
13917                                         set_targeted_subsys(aip, new_subsys, aip->target_objnum);
13918                                 } else {
13919                                         // AL 12-16-97: no more subsystems to attack... reset targeting info
13920                                         aip->target_objnum = -1;
13921                                         set_targeted_subsys(aip, NULL, -1);
13922                                 }
13923                         } else {
13924                                 // targeted subsys is destroyed, so stop attacking it
13925                                 set_targeted_subsys(aip, NULL, -1);
13926                         }
13927                 }
13928         }
13929
13930         ai_maybe_launch_cmeasure(Pl_objp, aip);
13931         ai_maybe_evade_locked_missile(Pl_objp, aip);
13932
13933         aip->target_time += flFrametime;
13934
13935         int in_formation = 0;
13936         if (aip->ai_flags & AIF_FORMATION) {
13937                 in_formation = !ai_formation();
13938         }
13939
13940         if ( !in_formation ) {
13941                 ai_execute_behavior(aip);
13942         }
13943
13944         process_subobjects(objnum);
13945         maybe_resume_previous_mode(Pl_objp, aip);
13946         
13947         if (Pl_objp->phys_info.flags & PF_AFTERBURNER_ON ) {
13948                 if (Missiontime > aip->afterburner_stop_time) {
13949                         //nprintf(("AI", "Frame %i, turning off afterburner.\n", AI_FrameCount));
13950                         afterburners_stop(Pl_objp);
13951                 }
13952         }
13953 //      validate_mode_submode(aip);
13954 }
13955
13956 int Waypoints_created = 0;
13957
13958 //      Find the ship with the name *name in the Ship_info array.
13959 int find_ship_name(char *name)
13960 {
13961         int     i;
13962
13963         for (i=0; i<Num_ship_types; i++)
13964                 if (!strcmp(Ship_info[i].name, name))
13965                         return i;
13966
13967         return -1;
13968 }
13969
13970 void create_waypoints()
13971 {
13972         int     i, j;
13973
13974         // Waypoints_created = 1;
13975
13976         if (Waypoints_created)
13977                 return;
13978
13979         for (j=0; j<Num_waypoint_lists; j++)
13980                 for (i=0; i<Waypoint_lists[j].count; i++) {
13981                         obj_create(OBJ_WAYPOINT, 0, j * 65536 + i, NULL,
13982                                 &Waypoint_lists[j].waypoints[i], 0.0f, OF_RENDERS);
13983                 }
13984
13985         Waypoints_created = 1;
13986 }
13987
13988 int Last_ai_obj = -1;
13989
13990 void ai_process( object * obj, int ai_index, float frametime )
13991 {
13992 //      if (Ships[obj->instance].flags & SF_DYING)
13993 //              nprintf(("AI", "Frame: %i Ship %s is dying!\n", Framecount, Ships[obj->instance].ship_name));
13994
13995         if (obj->flags & OF_SHOULD_BE_DEAD)
13996                 return;
13997
13998         // 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.
13999         if ((Ships[obj->instance].flags & SF_DYING ) && !(Ship_info[Ships[obj->instance].ship_info_index].flags & (SIF_HUGE_SHIP | SIF_BIG_SHIP))){
14000                 return;
14001         }
14002
14003         int rfc = 1;            //      Assume will be Reading Flying Controls.
14004
14005         SDL_assert( obj->type == OBJ_SHIP );
14006         SDL_assert( ai_index >= 0 );
14007
14008         init_ship_info();
14009
14010         create_waypoints();
14011
14012         AI_frametime = frametime;
14013         if (obj-Objects <= Last_ai_obj) {
14014                 AI_FrameCount++;
14015         }
14016
14017         memset( &AI_ci, 0, sizeof(AI_ci) );
14018
14019         ai_frame(obj-Objects);
14020
14021         AI_ci.pitch = 0.0f;
14022         AI_ci.bank = 0.0f;
14023         AI_ci.heading = 0.0f;
14024
14025         // the ships maximum velocity now depends on the energy flowing to engines
14026         obj->phys_info.max_vel.xyz.z = Ships[obj->instance].current_max_speed;
14027         ai_info *aip = &Ai_info[Ships[obj->instance].ai_index];
14028
14029         //      In certain circumstances, the AI says don't fly in the normal way.
14030         //      One circumstance is in docking and undocking, when the ship is moving
14031         //      under thruster control.
14032         switch (aip->mode) {
14033         case AIM_DOCK:
14034                 if ((aip->submode >= AIS_DOCK_2) && (aip->submode != AIS_UNDOCK_3))
14035                         rfc = 0;
14036                 break;
14037         case AIM_WARP_OUT:
14038                 if (aip->submode >= AIS_WARP_3)
14039                         rfc = 0;
14040                 break;
14041 //      case AIM_NONE:
14042 //              if (aip->submode == AIS_NONE_FORMATION)
14043 //                      rfc = 0;
14044 //              break;
14045         default:
14046                 break;
14047         }
14048
14049         if (rfc == 1) {
14050                 vector copy_desired_rotvel = obj->phys_info.rotvel;
14051                 physics_read_flying_controls( &obj->orient, &obj->phys_info, &AI_ci, frametime);
14052                 // if obj is in formation and not flight leader, don't update rotvel
14053                 if (aip->ai_flags & AIF_FORMATION) {
14054                         if (&Objects[aip->goal_objnum] != obj) {
14055                                 obj->phys_info.desired_rotvel = copy_desired_rotvel;
14056                                 obj->phys_info.rotvel = copy_desired_rotvel;
14057                         }
14058                 }
14059         }
14060
14061         Last_ai_obj = obj-Objects;
14062 }
14063
14064 //      Initialize ai_info struct of object objnum.
14065 void init_ai_object(int objnum)
14066 {
14067         int     ship_index, ai_index;
14068         ai_info *aip;
14069         int ship_type;
14070         object  *objp;
14071         vector  near_vec;                       //      A vector nearby and mainly in front of this object.
14072
14073         objp = &Objects[objnum];
14074         ship_index = objp->instance;
14075         ai_index = Ships[ship_index].ai_index;
14076         SDL_assert((ai_index >= 0) && (ai_index < MAX_AI_INFO));
14077
14078         aip = &Ai_info[ai_index];
14079
14080         ship_type = Ships[ship_index].ship_info_index;
14081
14082         vm_vec_scale_add(&near_vec, &objp->pos, &objp->orient.v.fvec, 100.0f);
14083         vm_vec_scale_add2(&near_vec, &objp->orient.v.rvec, 10.0f);
14084
14085         // Things that shouldn't have to get initialized, but initialize them just in case!
14086         aip->ai_flags = 0;
14087         aip->previous_mode = AIM_NONE;
14088         aip->mode_time = -1;
14089         aip->target_objnum = -1;
14090         aip->target_signature = -1;
14091         aip->previous_target_objnum = -1;
14092         aip->target_time = 0.0f;
14093         aip->enemy_wing = -1;
14094         aip->attacker_objnum = -1;
14095         aip->goal_objnum = -1;
14096         aip->goal_signature = -1;
14097         aip->guard_objnum = -1;
14098         aip->guard_signature = -1;
14099         aip->guard_wingnum = -1;
14100         aip->dock_signature = -1;
14101         aip->submode = 0;
14102         aip->previous_submode = 0;
14103         aip->best_dot_to_enemy = -1.0f;
14104         aip->best_dot_from_enemy = -1.0f;
14105         aip->best_dot_to_time = 0;
14106         aip->best_dot_from_time = 0;
14107         aip->submode_start_time = 0;
14108         aip->submode_parm0 = 0;
14109         aip->active_goal = -1;
14110         aip->goal_check_time = timestamp(0);
14111         aip->last_predicted_enemy_pos = near_vec;
14112         aip->prev_goal_point = near_vec;
14113         aip->goal_point = near_vec;
14114         aip->time_enemy_in_range = 0.0f;
14115         aip->last_attack_time = 0;
14116         aip->last_hit_time = 0;
14117         aip->last_hit_quadrant = 0;
14118         aip->hitter_objnum = -1;
14119         aip->hitter_signature = -1;
14120         aip->resume_goal_time = -1;
14121         aip->prev_accel = 0.0f;
14122         aip->prev_dot_to_goal = 0.0f;
14123
14124         aip->ignore_objnum = UNUSED_OBJNUM;
14125         aip->ignore_signature = -1;
14126
14127         // aip->mode = AIM_NONE;
14128
14129         // End of Things that shouldn't have to get initialized, but initialize them just in case!
14130
14131         aip->ai_courage = Ai_classes[Ship_info[ship_type].ai_class].ai_courage[Game_skill_level];
14132         aip->ai_patience = Ai_classes[Ship_info[ship_type].ai_class].ai_patience[Game_skill_level];
14133         aip->ai_evasion = Ai_classes[Ship_info[ship_type].ai_class].ai_evasion[Game_skill_level];
14134         aip->ai_accuracy = Ai_classes[Ship_info[ship_type].ai_class].ai_accuracy[Game_skill_level];
14135
14136         if (Num_waypoint_lists > 0) {
14137                 aip->wp_index = -1;
14138                 aip->wp_list = -1;
14139         } else {
14140                 aip->wp_index = -1;
14141                 aip->wp_list = -1;
14142         }
14143
14144         aip->attacker_objnum = -1;
14145         aip->goal_signature = -1;
14146
14147         Objects[objnum].phys_info.prev_fvec = Objects[objnum].orient.v.fvec;
14148
14149         aip->last_predicted_enemy_pos.xyz.x = 0.0f;     //      Says this value needs to be recomputed!
14150         aip->time_enemy_in_range = 0.0f;
14151
14152         aip->resume_goal_time = -1;                                     //      Say there is no goal to resume.
14153
14154         aip->active_goal = -1;
14155         aip->path_start = -1;
14156         aip->path_goal_dist = -1;
14157         aip->path_length = 0;
14158         aip->path_subsystem_next_check = 1;
14159         aip->dock_path_index = -1;
14160         aip->dock_index = -1;
14161         aip->dock_objnum = -1;
14162
14163         aip->danger_weapon_objnum = -1;
14164         aip->danger_weapon_signature = -1;
14165
14166         aip->lead_scale = 0.0f;
14167         aip->last_hit_target_time = Missiontime;
14168
14169         aip->nearest_locked_object = -1;
14170         aip->nearest_locked_distance = 99999.0f;
14171
14172         aip->targeted_subsys = NULL;
14173         aip->last_subsys_target = NULL;
14174         aip->targeted_subsys_parent = -1;
14175
14176         // The next two fields are used to time the rearming to allow useful sound effects for missile rearming
14177         aip->rearm_first_missile = TRUE;                //      flag to indicate that next missile to load is the first missile
14178         aip->rearm_release_delay = 0;                   //      timestamp to delay the separation of docked ships after rearm
14179
14180         aip->next_predict_pos_time = 0;
14181
14182         aip->afterburner_stop_time = 0;
14183         aip->last_objsig_hit = -1;                              // object signature of the ship most recently hit by aip
14184
14185         aip->path_next_create_time = timestamp(1);
14186         aip->path_create_pos = Objects[objnum].pos;
14187         aip->path_create_orient = Objects[objnum].orient;
14188
14189         aip->ignore_expire_timestamp = timestamp(1);
14190         aip->warp_out_timestamp = 0;
14191         aip->next_rearm_request_timestamp = timestamp(1);
14192         aip->primary_select_timestamp = timestamp(1);
14193         aip->secondary_select_timestamp = timestamp(1);
14194         aip->scan_for_enemy_timestamp = timestamp(1);
14195
14196         aip->choose_enemy_timestamp = timestamp(3*(NUM_SKILL_LEVELS-Game_skill_level) * ((rand_alt() % 500) + 500));
14197
14198         aip->shockwave_object = -1;
14199         aip->shield_manage_timestamp = timestamp(1);
14200         aip->self_destruct_timestamp = -1;      //      This is a flag that we have not yet set this.
14201         aip->ok_to_target_timestamp = timestamp(1);
14202         aip->pick_big_attack_point_timestamp = timestamp(1);
14203         vm_vec_zero(&aip->big_attack_point);
14204
14205         aip->avoid_check_timestamp = timestamp(1);
14206
14207         aip->abort_rearm_timestamp = -1;
14208
14209         // artillery stuff
14210         aip->artillery_objnum = -1;
14211         aip->artillery_sig = -1;        
14212
14213         // waypoint speed cap
14214         aip->waypoint_speed_cap = -1;
14215
14216         // set lethality to enemy team
14217         aip->lethality = 0.0f;
14218 }
14219
14220 void init_ai_objects()
14221 {
14222         int     i;
14223
14224         for (i=0; i<num_objects; i++){
14225                 if (Objects[i].type == OBJ_SHIP){
14226                         init_ai_object(i);
14227                 }
14228         }
14229 }
14230
14231 void init_ai_system()
14232 {
14233         // MWA -- removed next line of code on 11/12/97.  When a ship is created
14234         // it calls init_ai_object() on it's objnum.  Doing this init at the point where
14235         // this function gets called messes things up.
14236         //init_ai_objects();
14237
14238         Ppfp = Path_points;
14239         Waypoints_created = 0;
14240
14241         Dock_path_warning_given = 0;
14242
14243 /*      for (int i=0; i<MAX_IGNORE_OBJECTS; i++) {
14244                 Ignore_objects[i].objnum = -1;
14245                 Ignore_objects[i].signature = -1;
14246         }
14247 */
14248
14249 }
14250
14251 void ai_set_default_behavior(object *obj, int classnum)
14252 {
14253         ai_info *aip;
14254
14255         SDL_assert(obj != NULL);
14256         SDL_assert(obj->instance != -1);
14257         SDL_assert(Ships[obj->instance].ai_index != -1);
14258
14259         aip = &Ai_info[Ships[obj->instance].ai_index];
14260
14261         aip->behavior = classnum;
14262
14263 }
14264
14265 void ai_do_default_behavior(object *obj)
14266 {
14267         ai_info *aip;
14268         int             ship_flags;
14269
14270         SDL_assert(obj != NULL);
14271         SDL_assert(obj->instance != -1);
14272         SDL_assert(Ships[obj->instance].ai_index != -1);
14273
14274         aip = &Ai_info[Ships[obj->instance].ai_index];
14275
14276         ship_flags = Ship_info[Ships[obj->instance].ship_info_index].flags;
14277         if (!is_instructor(obj) && (ship_flags & (SIF_FIGHTER | SIF_BOMBER))) {
14278                 int enemy_objnum = find_enemy(OBJ_INDEX(obj), 1000.0f, Skill_level_max_attackers[Game_skill_level]);
14279                 set_target_objnum(aip, enemy_objnum);
14280                 aip->mode = AIM_CHASE;
14281                 aip->submode = SM_ATTACK;
14282         } else if (ship_flags & (SIF_SUPPORT)) {
14283                 aip->mode = AIM_SAFETY;
14284                 aip->submode = AISS_1;
14285                 aip->ai_flags &= ~(AIF_REPAIRING);
14286         } else if ( ship_flags & SIF_SENTRYGUN ) {
14287                 aip->mode = AIM_SENTRYGUN;
14288         } else {
14289                 aip->mode = AIM_NONE;
14290         }
14291         
14292         aip->submode_start_time = Missiontime;
14293         aip->active_goal = AI_GOAL_NONE;
14294 }
14295
14296 #define FRIENDLY_DAMAGE_THRESHOLD       50.0f           //      Display a message at this threshold.  Note, this gets scaled by Skill_level
14297
14298 // send the given message from objp.  called from the maybe_process_friendly_hit
14299 // code below when a message must get send to the player when he fires on friendlies
14300 void process_friendly_hit_message( int message, object *objp )
14301 {
14302         int index;
14303
14304         // no traitor in multiplayer
14305         if(Game_mode & GM_MULTIPLAYER){
14306                 return;
14307         }
14308
14309         // don't send this message if a player ship was hit.
14310         if ( objp->flags & OF_PLAYER_SHIP ){
14311                 return;
14312         }
14313
14314         // check if objp is a cargo contianer -- if so, then find a new ship to send the message
14315         index = objp->instance;
14316         if ( !(Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_FIGHTER|SIF_BOMBER)) ){
14317                 index = -1;
14318         }
14319
14320         // if the message is "oops" (the don't hit me message), always make come from Terran command
14321         if ( message == MESSAGE_OOPS ){
14322                 index = -1;
14323         }
14324
14325         if ( index >= 0){
14326                 message_send_builtin_to_player( message, &Ships[index], MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_ANYTIME, 0, 0, -1, -1 );
14327         } else {
14328                 message_send_builtin_to_player( message, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_ANYTIME, 0, 0, -1, -1 );
14329         }
14330 }
14331
14332 extern  void ship_set_subsystem_strength( ship *shipp, int type, float strength );
14333
14334 //      Object *objp_weapon, fired by *objp_hitter, hit object *objp_ship.
14335 void maybe_process_friendly_hit(object *objp_hitter, object *objp_hit, object *objp_weapon)
14336 {
14337         // no turning traitor in multiplayer
14338         if ( Game_mode & GM_MULTIPLAYER ) {
14339                 return;
14340         }
14341
14342         // ditto if mission says no traitors allowed
14343         if (The_mission.flags & MISSION_FLAG_NO_TRAITOR) {
14344                 return;
14345         }
14346
14347         if ((objp_hitter == Player_obj) && (Player_ship->team == TEAM_FRIENDLY)) {
14348
14349                 // AL 12-4-97: It is possible the Player is a OBJ_GHOST at this point.  If so, bail out.
14350                 if ( objp_hitter->type != OBJ_SHIP ) {
14351                         return;
14352                 }
14353
14354                 SDL_assert(objp_hitter->type == OBJ_SHIP);
14355                 SDL_assert(objp_hit->type == OBJ_SHIP);
14356                 SDL_assert(objp_weapon->type == OBJ_WEAPON);
14357
14358                 ship    *shipp_hitter = &Ships[objp_hitter->instance];
14359                 ship    *shipp_hit = &Ships[objp_hit->instance];
14360
14361                 if (shipp_hitter->team != shipp_hit->team) {
14362                         return;
14363                 }
14364
14365                 // get the player
14366                 player *pp = &Players[Player_num];
14367
14368                 // wacky stuff here
14369                 if (pp->friendly_hits != 0) {
14370                         float   time_since_last_hit = f2fl(Missiontime - pp->friendly_last_hit_time);
14371                         if ((time_since_last_hit >= 0.0f) && (time_since_last_hit < 10000.0f)) {
14372                                 if (time_since_last_hit > 60.0f) {
14373                                         pp->friendly_hits = 0;
14374                                         pp->friendly_damage = 0.0f;
14375                                 } else if (time_since_last_hit > 2.0f) {
14376                                         pp->friendly_hits -= (int) time_since_last_hit/2;
14377                                         pp->friendly_damage -= time_since_last_hit;
14378                                 }
14379
14380                                 if (pp->friendly_damage < 0.0f) {
14381                                         pp->friendly_damage = 0.0f;
14382                                 }
14383
14384                                 if (pp->friendly_hits < 0) {
14385                                         pp->friendly_hits = 0;
14386                                 }
14387                         }
14388                 }
14389
14390                 float   damage;         //      Damage done by weapon.  Gets scaled down based on size of ship.
14391
14392                 damage = Weapon_info[Weapons[objp_weapon->instance].weapon_info_index].damage;
14393                 
14394                 // wacky stuff here
14395                 ship_info *sip = &Ship_info[Ships[objp_hit->instance].ship_info_index];
14396                 if (sip->initial_hull_strength > 1000.0f) {
14397                         float factor = sip->initial_hull_strength / 1000.0f;
14398                         factor = min(100.0f, factor);
14399                         damage /= factor;
14400                 }
14401
14402                 //      Don't penalize much at all for hitting cargo
14403                 if (sip->flags & (SIF_CARGO | SIF_SENTRYGUN)) {
14404                         damage /= 10.0f;
14405                 }
14406
14407                 //      Hit ship, but not targeting it, so it's not so heinous, maybe an accident.
14408                 if (Ai_info[shipp_hitter->ai_index].target_objnum != OBJ_INDEX(objp_hit)) {
14409                         damage /= 5.0f;
14410                 }
14411
14412                 pp->friendly_last_hit_time = Missiontime;
14413                 pp->friendly_hits++;
14414
14415                 // cap damage and number of hits done this frame
14416                 float accredited_damage = min(MAX_BURST_DAMAGE, pp->damage_this_burst + damage) - pp->damage_this_burst;
14417                 pp->friendly_damage += accredited_damage;
14418                 pp->damage_this_burst += accredited_damage;
14419
14420                 // Done with adjustments to damage.  Evaluate based on current friendly_damage
14421                 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 ));
14422                 
14423                 if (is_instructor(objp_hit)) {
14424                         // it's not nice to hit your instructor
14425                         if (pp->friendly_damage > FRIENDLY_DAMAGE_THRESHOLD) {
14426                                 message_send_builtin_to_player( MESSAGE_INSTRUCTOR_ATTACK, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_IMMEDIATE, 0, 0, -1, -1);
14427                                 pp->last_warning_message_time = Missiontime;
14428                                 ship_set_subsystem_strength( Player_ship, SUBSYSTEM_WEAPONS, 0.0f);
14429
14430                                 training_fail();
14431
14432                                 //      Instructor warp out.
14433                                 ai_set_mode_warp_out(objp_hit, &Ai_info[Ships[objp_hit->instance].ai_index]);
14434                                 gameseq_post_event( GS_EVENT_PLAYER_WARPOUT_START_FORCED );     //      Force player to warp out.
14435
14436                                 //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) );
14437                                 //ship_apply_global_damage( objp_hitter, objp_hit, NULL, 1.0f );
14438                         } else if (Missiontime - pp->last_warning_message_time > F1_0*4) {
14439                                 // warning every 4 sec
14440                                 // use NULL as the message sender here since it is the Terran Command persona
14441                                 message_send_builtin_to_player( MESSAGE_INSTRUCTOR_HIT, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_IMMEDIATE, 0, 0, -1, -1);
14442                                 pp->last_warning_message_time = Missiontime;
14443                         }
14444
14445                 // not nice to hit your friends
14446                 } else if (pp->friendly_damage > FRIENDLY_DAMAGE_THRESHOLD * (1.0f + (float) (NUM_SKILL_LEVELS + 1 - Game_skill_level)/3.0f)) {
14447                         process_friendly_hit_message( MESSAGE_HAMMER_SWINE, objp_hit );
14448                         mission_goal_fail_all();
14449                         ai_abort_rearm_request( Player_obj );
14450
14451                         Player_ship->team = TEAM_TRAITOR;
14452
14453                 } else if ((damage > frand()) && (Missiontime - pp->last_warning_message_time > F1_0*4) && (pp->friendly_damage > FRIENDLY_DAMAGE_THRESHOLD)) {
14454                         // no closer than 4 sec intervals
14455                         //      Note: (damage > frand()) added on 12/9/97 by MK.  Since damage is now scaled down for big ships, we could get too
14456                         //      many warnings.  Kind of tedious.  frand() returns a value in 0..1, so this won't affect legit hits.
14457                         process_friendly_hit_message( MESSAGE_OOPS, objp_hit );
14458                         pp->last_warning_message_time = Missiontime;
14459                 }
14460         }
14461 }
14462
14463 //      Maybe make ship with ai_info *aip attack hitter_objnum as a dynamic goal
14464 void maybe_set_dynamic_chase(ai_info *aip, int hitter_objnum)
14465 {
14466         SDL_assert(Ship_info[Ships[aip->shipnum].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER));
14467
14468         // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
14469         if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
14470                 return;
14471         }
14472
14473         // only set as target if can be targeted.
14474         if (awacs_get_level(&Objects[hitter_objnum], &Ships[aip->shipnum], 1) < 1) {
14475                 return;
14476         }
14477
14478         if (aip->target_objnum != hitter_objnum)
14479                 aip->aspect_locked_time = 0.0f;
14480         set_target_objnum(aip, hitter_objnum);
14481         aip->resume_goal_time = Missiontime + i2f(20);  //      Only chase up to 20 seconds.
14482         aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
14483
14484         set_targeted_subsys(aip, NULL, -1);             //      Say not attacking any particular subsystem.
14485
14486         aip->previous_submode = aip->mode;
14487         aip->mode = AIM_CHASE;
14488         aip->submode = SM_ATTACK;
14489 }
14490
14491
14492 //      Return true if *objp has armed an aspect seeking bomb.
14493 //      This function written so a ship with an important bomb to fire will willingly take hits in the face to fire its bomb.
14494 int firing_aspect_seeking_bomb(object *objp)
14495 {
14496         ship    *shipp;
14497         int     bank_index;
14498         ship_weapon     *swp;
14499
14500         shipp = &Ships[objp->instance];
14501
14502         swp = &shipp->weapons;
14503
14504         bank_index = swp->current_secondary_bank;
14505
14506         if (bank_index != -1)
14507                 if (swp->secondary_bank_ammo[bank_index] > 0) {
14508                         if (Weapon_info[swp->secondary_bank_weapons[bank_index]].wi_flags & WIF_BOMB) {
14509                                 if (Weapon_info[swp->secondary_bank_weapons[bank_index]].wi_flags & WIF_HOMING_ASPECT) {
14510                                         return 1;
14511                                 }
14512                         }
14513                 }
14514
14515         return 0;
14516 }
14517
14518 //      *objp collided with big ship *big_objp at global point *collide_pos
14519 //      Make it fly away from the collision point.
14520 // collision_normal is NULL, when a collision is imminent and we just want to bug out.
14521 void big_ship_collide_recover_start(object *objp, object *big_objp, vector *collide_pos, vector *collision_normal)
14522 {
14523         ai_info *aip;
14524
14525         SDL_assert(objp->type == OBJ_SHIP);
14526
14527         aip = &Ai_info[Ships[objp->instance].ai_index];
14528
14529         if (!timestamp_elapsed(aip->big_recover_timestamp) && (aip->ai_flags & AIF_BIG_SHIP_COLLIDE_RECOVER_1))
14530                 return;
14531
14532         //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)));
14533         if (collision_normal) {
14534                 aip->big_recover_timestamp = timestamp(2000);
14535                 aip->big_collision_normal = *collision_normal;
14536         //      nprintf(("AI", " normal\n"));
14537         } else {
14538                 aip->big_recover_timestamp = timestamp(500);
14539         //      nprintf(("AI", " no normal\n"));
14540         }
14541
14542
14543         aip->ai_flags &= ~AIF_BIG_SHIP_COLLIDE_RECOVER_2;
14544         aip->ai_flags |= AIF_BIG_SHIP_COLLIDE_RECOVER_1;
14545
14546 //      vector  out_vec;
14547 //      vm_vec_normalized_dir(&out_vec, &objp->pos, collide_pos);
14548
14549         // big_recover_pos_1 is 100 m out along normal
14550         vector direction;
14551         if (collision_normal) {
14552                 direction = *collision_normal;
14553         } else {
14554                 vm_vec_copy_scale(&direction, &objp->orient.v.fvec, -1.0f);
14555         }
14556         vm_vec_scale_add(&aip->big_recover_pos_1, &objp->pos, &direction, 100.0f);
14557
14558         // go out 200 m from box closest box point
14559         get_world_closest_box_point_with_delta(&aip->big_recover_pos_2, big_objp, &aip->big_recover_pos_1, NULL, 300.0f);
14560
14561         accelerate_ship(aip, 0.0f);
14562 /*
14563         if (vm_vec_dot(collision_normal, &objp->orient.v.fvec) > 0.5f) {
14564 //              vm_vec_scale_add(&aip->big_recover_pos_1, &objp->pos, &out_vec, big_objp->radius/2.0f);
14565 //              vm_vec_scale_add(&aip->big_recover_pos_2, &aip->big_recover_pos_1, &objp->orient.v.uvec, big_objp->radius/2.0f);
14566 //              vm_vec_scale_add(&aip->big_recover_pos_2, &objp->pos, &out_vec, big_objp->radius*2.0f);
14567                 accelerate_ship(aip, 2.0f);
14568         } else {
14569 //              vm_vec_scale_add(&aip->big_recover_pos_1, &objp->pos, &out_vec, big_objp->radius/2.0f);
14570 //              vm_vec_scale_add(&aip->big_recover_pos_2, &aip->big_recover_pos_1, &objp->orient.v.uvec, big_objp->radius/2.0f);
14571                 accelerate_ship(aip, 0.0f);
14572         } */
14573 }
14574
14575 float max_lethality = 0.0f;
14576
14577 void ai_update_lethality(object *ship_obj, object *other_obj, float damage)
14578 {
14579         SDL_assert(ship_obj->type == OBJ_SHIP);
14580         SDL_assert(other_obj->type == OBJ_WEAPON || other_obj->type == OBJ_SHOCKWAVE);
14581         int dont_count = FALSE;
14582
14583         int parent = other_obj->parent;
14584         if (Objects[parent].type == OBJ_SHIP) {
14585                 if (Objects[parent].signature == other_obj->parent_sig) {
14586
14587                         // check damage done to enemy team
14588                         if (Ships[ship_obj->instance].team != Ships[Objects[parent].instance].team) {
14589
14590                                 // other is weapon
14591                                 if (other_obj->type == OBJ_WEAPON) {
14592                                         weapon *wp = &Weapons[other_obj->instance];
14593                                         weapon_info *wif = &Weapon_info[wp->weapon_info_index];
14594
14595                                         // if parent is BIG|HUGE, don't count beam
14596                                         if (Ship_info[Ships[Objects[parent].instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) {
14597                                                 if (wif->wi_flags & WIF_BEAM) {
14598                                                         dont_count = TRUE;
14599                                                 }
14600                                         }
14601                                 }
14602
14603                                 if (!dont_count) {
14604                                         float lethality = 0.025f * damage;      // 2 cyclops (@2000) put you at 100 lethality
14605
14606                                         // increase lethality weapon's parent ship
14607                                         ai_info *aip = &Ai_info[Ships[Objects[parent].instance].ai_index];
14608                                         aip->lethality += lethality;
14609                                         aip->lethality = min(110.0f, aip->lethality);
14610                                         // if you hit, don;t be less than 0
14611                                         aip->lethality = max(0.0f, aip->lethality);
14612
14613 //                                      if (aip->lethality > max_lethality) {
14614 //                                              max_lethality = aip->lethality;
14615 //                                              mprintf(("new lethalilty high: %.1f\n", max_lethality));
14616 //                                      }
14617
14618                                         // if parent is player, show his lethality
14619 //                                      if (Objects[parent].flags & OF_PLAYER_SHIP) {
14620 //                                              mprintf(("Player lethality: %.1f\n", aip->lethality));
14621 //                                      }
14622                                 }
14623                         }
14624                 }
14625         }
14626 }
14627
14628
14629 //      Object *objp_ship was hit by either weapon *objp_weapon or collided into by ship hit_objp at point *hitpos.
14630 void ai_ship_hit(object *objp_ship, object *hit_objp, vector *hitpos, int shield_quadrant, vector *hit_normal)
14631 {
14632         int             hitter_objnum = -2;
14633         object  *objp_hitter = NULL;
14634         ship            *shipp;
14635         ai_info *aip, *hitter_aip;
14636
14637         shipp = &Ships[objp_ship->instance];
14638         aip = &Ai_info[shipp->ai_index];
14639
14640         if (objp_ship->flags & OF_PLAYER_SHIP)
14641                 return;
14642
14643         if ((aip->mode == AIM_WARP_OUT) || (aip->mode == AIM_PLAY_DEAD))
14644                 return;
14645
14646         if (hit_objp->type == OBJ_SHIP) {
14647                 //      If the object that this ship collided with is a big ship
14648                 if (Ship_info[Ships[hit_objp->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
14649                         //      And the current object is _not_ a big ship
14650                         if (!(Ship_info[Ships[objp_ship->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
14651                                 //      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.
14652                                 big_ship_collide_recover_start(objp_ship, hit_objp, hitpos, hit_normal);
14653                         }
14654                 }
14655         }
14656
14657         if (hit_objp->type == OBJ_WEAPON) {
14658                 //      Make sure the object that fired this weapon is still alive.  If not, abort.
14659                 // SDL_assert(hit_objp->parent >= 0);
14660                 if(hit_objp->parent < 0){
14661                         return;
14662                 }
14663                 if ( hit_objp->parent_sig != Objects[hit_objp->parent].signature ){
14664                         return;
14665                 }
14666
14667                 //      Hit by a protected ship, don't attack it.
14668                 if (Objects[hit_objp->parent].flags & OF_PROTECTED) {
14669                         if ((Ship_info[shipp->ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER)) && (aip->target_objnum == -1)) {
14670                                 if (aip->mode == AIM_CHASE) {
14671                                         if (aip->submode != SM_EVADE_WEAPON) {
14672                                                 aip->mode = AIM_CHASE;
14673                                                 aip->submode = SM_EVADE_WEAPON;
14674                                                 aip->submode_start_time = Missiontime;
14675                                         }
14676                                 } else if (aip->mode != AIM_EVADE_WEAPON) {
14677                                         aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
14678                                         aip->previous_mode = aip->mode;
14679                                         aip->previous_submode = aip->submode;
14680                                         aip->mode = AIM_EVADE_WEAPON;
14681                                         aip->submode = -1;
14682                                         aip->submode_start_time = Missiontime;
14683                                         aip->mode_time = timestamp(MAX_EVADE_TIME);     //      Evade for up to five seconds.
14684                                 }
14685
14686                         }
14687                         return;
14688                 }
14689
14690                 hitter_objnum = hit_objp->parent;
14691                 SDL_assert((hitter_objnum >= 0) && (hitter_objnum < MAX_OBJECTS));
14692                 objp_hitter = &Objects[hitter_objnum];
14693                 maybe_process_friendly_hit(objp_hitter, objp_ship, hit_objp);           //      Deal with player's friendly fire.
14694
14695                 if ( (shipp->team & TEAM_FRIENDLY) && !(Game_mode & GM_MULTIPLAYER) ) {
14696                         ship_maybe_ask_for_help(shipp);
14697                 }
14698         } else if (hit_objp->type == OBJ_SHIP) {
14699                 if (shipp->team == Ships[hit_objp->instance].team)              //      Don't have AI react to collisions between teammates.
14700                         return;
14701                 objp_hitter = hit_objp;
14702                 hitter_objnum = hit_objp-Objects;
14703         } else {
14704                 Int3(); //      Hmm, what kind of object hit this if not weapon or ship?  Get MikeK.
14705                 return;
14706         }
14707
14708         //      Collided into a protected ship, don't attack it.
14709         if (hit_objp->flags & OF_PROTECTED)
14710                 return;
14711
14712         SDL_assert(objp_hitter != NULL);
14713         hitter_aip = &Ai_info[Ships[objp_hitter->instance].ai_index];
14714         hitter_aip->last_hit_target_time = Missiontime;
14715         
14716         // store the object signature of objp_ship into ai_info, since we want to track the last ship hit by 'hitter_objnum'
14717         hitter_aip->last_objsig_hit = objp_ship->signature; 
14718
14719         aip->last_hit_time = Missiontime;
14720
14721         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
14722                 return;
14723
14724         //      If this ship is awaiting repair, abort!
14725         if (aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED)) {
14726                 ship_info       *sip = &Ship_info[shipp->ship_info_index];
14727
14728                 if (objp_ship->hull_strength/sip->initial_hull_strength < 0.3f) {
14729                         //      No, only abort if hull below a certain level.
14730                         aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP/2);  //      Might request again after 15 seconds.
14731                         if ( !(objp_ship->flags & OF_PLAYER_SHIP) )                                             // mwa -- don't abort rearm for a player
14732                                 ai_abort_rearm_request(objp_ship);
14733                 }
14734         }
14735
14736         //      If firing a bomb, ignore enemy fire so we can gain lock drop the bomb.
14737         //      Only ignore fire if aspect_locked_time > 0.5f, as this means we're in range.
14738         if (firing_aspect_seeking_bomb(objp_ship)) {
14739                 if ((aip->ai_flags & AIF_SEEK_LOCK) && (aip->aspect_locked_time > 0.1f))
14740                         return;
14741         }
14742
14743         //      If in AIM_STRAFE mode and got hit by target, maybe attack turret if appropriate
14744         if (aip->mode == AIM_STRAFE) {
14745                 SDL_assert(hitter_objnum != -2);
14746                 if (aip->target_objnum == hitter_objnum) {
14747                         if ( hit_objp->type == OBJ_WEAPON ) {
14748                                 ai_big_strafe_maybe_attack_turret(objp_ship, hit_objp);
14749                         }
14750                         return;
14751                 }
14752                 else {
14753                                 // AL 11-10-97:
14754                         ;       // do nothing here, we'll attack this hitter if it is a fighter or bomber (this is handled
14755                                 // in code later in this function
14756                 }
14757         }
14758
14759         if (objp_ship == Player_obj)
14760                 return;         //      We don't do AI for the player.
14761
14762         maybe_update_guard_object(objp_ship, objp_hitter);
14763
14764         //      Big ships don't go any further.
14765         if (!(Ship_info[shipp->ship_info_index].flags & SIF_SMALL_SHIP))
14766                 return;
14767
14768         //      If the hitter object is the ignore object, don't attack it.
14769         ship_info       *sip = &Ship_info[shipp->ship_info_index];
14770         if ((is_ignore_object(aip, objp_hitter-Objects)) && (sip->flags & (SIF_BOMBER | SIF_FIGHTER))) {
14771                 if (aip->mode == AIM_NONE) {
14772                         aip->mode = AIM_CHASE;  //      This will cause the ship to move, if not attack.
14773                         aip->submode = SM_EVADE;
14774                 }
14775                 return;
14776         }
14777
14778         //      Maybe abort based on mode.
14779         switch (aip->mode) {
14780         case AIM_CHASE:
14781                 if (aip->submode == SM_ATTACK_FOREVER)
14782                         return;
14783
14784                 if ( hit_objp->type == OBJ_WEAPON ) {
14785                         if ( ai_big_maybe_enter_strafe_mode(objp_ship, OBJ_INDEX(hit_objp), 1) )
14786                                 return;
14787                 }
14788
14789         case AIM_GUARD:
14790                 //      If in guard mode and far away from guard object, don't pursue guy that hit me.
14791                         if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
14792                                 if (vm_vec_dist_quick(&objp_ship->pos, &Objects[aip->guard_objnum].pos) > 500.0f) {
14793                                         return;
14794                                 }
14795                         }
14796         case AIM_STILL:
14797         case AIM_STAY_NEAR:
14798                 // Note: Dealt with above, at very top.  case AIM_PLAY_DEAD:
14799         case AIM_STRAFE:
14800                 break;
14801         case AIM_EVADE_WEAPON:
14802         case AIM_EVADE:
14803         case AIM_GET_BEHIND:
14804         case AIM_AVOID:
14805         case AIM_DOCK:
14806         case AIM_BIGSHIP:
14807         case AIM_PATH:
14808         case AIM_NONE:
14809         case AIM_BAY_DEPART:
14810         case AIM_SENTRYGUN:
14811                 return;
14812         case AIM_BAY_EMERGE:
14813                 // If just leaving the docking bay, don't react to enemy fire... just keep flying away from docking bay
14814                 if ( (Missiontime - aip->submode_start_time) < 5*F1_0 ) {
14815                         return;
14816                 }
14817                 break;
14818         case AIM_WAYPOINTS:
14819                 if (sip->flags & (SIF_FIGHTER | SIF_BOMBER))
14820                         break;
14821                 else
14822                         return;
14823                 break;
14824         case AIM_SAFETY:
14825                 if ((aip->submode != AISS_1) || (Missiontime - aip->submode_start_time > i2f(1))) {
14826                         aip->submode = AISS_1;
14827                         aip->submode_start_time = Missiontime;
14828                 }
14829                 return;
14830                 break;
14831         case AIM_WARP_OUT:
14832                 return;
14833                 break;
14834         default:
14835                 Int3(); //      Bogus mode!
14836         }
14837
14838         if (timestamp_elapsed(aip->ok_to_target_timestamp))
14839                 aip->ai_flags &= ~AIF_FORMATION;                        //      If flying in formation, bug out!
14840
14841         aip->hitter_objnum = hitter_objnum;
14842         aip->hitter_signature = Objects[hitter_objnum].signature;
14843
14844         //      If the hitter is not on the same team as the hittee, do some stuff.
14845         if (shipp->team != Ships[objp_hitter->instance].team) {
14846                 //nprintf(("AI", "Object %i attacking %i, who just hit him!\n", objp_ship-Objects, hitter_objnum));
14847
14848                 if ((hitter_objnum != aip->target_objnum) && (sip->flags & (SIF_FIGHTER | SIF_BOMBER))) {
14849                         maybe_set_dynamic_chase(aip, hitter_objnum);
14850                         maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14851                 } else {
14852                         if ((aip->mode == AIM_CHASE) && ((objp_ship->hull_strength/sip->initial_hull_strength > 0.9f) || (get_shield_strength(objp_ship)/sip->shields > 0.8f))) {
14853                                 switch (aip->submode) {
14854                                 case SM_ATTACK:
14855                                 case SM_SUPER_ATTACK:
14856                                 case SM_GET_AWAY:
14857                                         break;
14858                                 default:
14859                                         if (sip->flags & (SIF_FIGHTER | SIF_BOMBER)) {
14860                                                 maybe_set_dynamic_chase(aip, hitter_objnum);
14861                                         }
14862                                         maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14863                                         break;
14864                                 }
14865                         } else if (aip->mode == AIM_CHASE) {
14866                                 switch (aip->submode) {
14867                                 case SM_ATTACK:
14868                                         aip->submode = SM_EVADE;
14869                                         aip->submode_start_time = Missiontime;
14870                                         break;
14871                                 case SM_SUPER_ATTACK:
14872                                         if (Missiontime - aip->submode_start_time > i2f(1)) {
14873                                                 aip->submode = SM_EVADE;
14874                                                 aip->submode_start_time = Missiontime;
14875                                         }
14876                                         break;
14877                                 case SM_EVADE_BRAKE:
14878                                         break;
14879                                 case SM_EVADE_SQUIGGLE:
14880                                         aip->submode = SM_EVADE;
14881                                         aip->submode_start_time = Missiontime;
14882                                         break;
14883                                 default:
14884                                         if (sip->flags & (SIF_BOMBER | SIF_FIGHTER)) {
14885                                                 maybe_set_dynamic_chase(aip, hitter_objnum);
14886                                                 maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14887                                         }
14888
14889                                         break;
14890                                 }
14891                         } else {
14892                                 // AL 3-15-98: Prevent escape pods from entering chase mode
14893                                 if ( (sip->flags & (SIF_BOMBER | SIF_FIGHTER)) ) {
14894                                         maybe_set_dynamic_chase(aip, hitter_objnum);
14895                                 }
14896                                 maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14897                         }
14898                 }
14899         }
14900 }
14901
14902 //      Ship shipnum has been destroyed.
14903 //      Cleanup.
14904 // the parameter 'method' is used to tell is this ship was destroyed or it departed normally.
14905 // This function will get called in either case, and there are things that should be done if
14906 // the ship actually gets destroyed which shouldn't get done if it departed.
14907 void ai_ship_destroy(int shipnum, int method)
14908 {
14909         int             objnum;
14910         object  *other_objp;
14911         ship            *shipp;
14912         ship_obj        *so;
14913         ai_info *dead_aip;
14914
14915         SDL_assert((shipnum >= 0) && (shipnum < MAX_SHIPS));
14916         objnum = Ships[shipnum].objnum;
14917         dead_aip = &Ai_info[Ships[shipnum].ai_index];
14918
14919         // if I was getting repaired, or awaiting repair, then cleanup the repair mode.  When awaiting repair, the dock_objnum
14920         // is -1.  When the support ship is on the way, the dock_objnum >= 0 (points to support ship).
14921         if ( dead_aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED) ) {
14922                 if ( dead_aip->dock_objnum >= 0 )
14923                         ai_do_objects_repairing_stuff( &Objects[objnum], &Objects[dead_aip->dock_objnum], REPAIR_INFO_END);
14924                 else
14925                         ai_do_objects_repairing_stuff( &Objects[objnum], NULL, REPAIR_INFO_END );
14926         }
14927
14928         //      For all objects that had this ship as a target, wipe it out, forcing find of a new enemy.
14929         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
14930                 other_objp = &Objects[so->objnum];
14931                 SDL_assert(other_objp->instance != -1);
14932
14933                 shipp = &Ships[other_objp->instance];
14934                 SDL_assert(shipp->ai_index != -1);
14935
14936                 ai_info *aip = &Ai_info[shipp->ai_index];
14937
14938                 // MWA 2/11/98
14939                 // code commented out below is taken care of in ai_cleanup_dock_mode when gets called when the
14940                 // support ship starts it's death roll.
14941
14942                 //      If the destroyed ship was on its way to repair the current ship
14943                 if (aip->dock_objnum == objnum) {
14944
14945                         // clean up the flags for any kind of docking mode.  If aip was part of a goal of dock/undock
14946                         // then it will get cleaned up by the goal code.
14947                         ai_do_objects_undocked_stuff( other_objp, NULL );
14948
14949                         if ( aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED) ) {
14950                                 int abort_reason;
14951                                 if ( method == SEF_DEPARTED ) {
14952                                         abort_reason = REPAIR_INFO_ABORT;
14953                                 } else {
14954                                         abort_reason = REPAIR_INFO_KILLED;
14955                                 }
14956                                 ai_do_objects_repairing_stuff( other_objp, NULL, abort_reason );
14957                         }
14958                 }
14959
14960                 if (aip->target_objnum == objnum) {
14961                         set_target_objnum(aip, -1);
14962                         //      If this ship had a dynamic goal of chasing the dead ship, clear the dynamic goal.
14963                         if (aip->resume_goal_time != -1)
14964                                 aip->active_goal = AI_GOAL_NONE;
14965                 }
14966
14967                 if (aip->goal_objnum == objnum) {
14968                         aip->goal_objnum = -1;
14969                         aip->goal_signature = -1;
14970                 }
14971
14972                 if (aip->guard_objnum == objnum) {
14973                         aip->guard_objnum = -1;
14974                         aip->guard_signature = -1;
14975                 }
14976
14977                 if ((aip->guard_wingnum != -1) && (aip->guard_wingnum == Ai_info[Ships[Objects[objnum].instance].ai_index].wing)) {
14978                         if (aip->guard_wingnum != aip->wing)
14979                                 ai_set_guard_wing(other_objp, aip->guard_wingnum);
14980                 }
14981
14982                 if (aip->hitter_objnum == objnum)
14983                         aip->hitter_objnum = -1;
14984
14985         }
14986
14987 }
14988
14989 /*
14990 //      Interface function to goals code.
14991 //      Make object *objp fly to point *vp and warp out.
14992 void ai_warp_out(object *objp, vector *vp)
14993 {
14994         ai_info *aip;
14995
14996         aip = &Ai_info[Ships[objp->instance].ai_index];
14997
14998         if (aip->mode != AIM_WARP_OUT) {
14999                 ai_set_mode_warp_out(objp, aip);
15000         }
15001         float   dist;
15002         float   dot;
15003         vector  v2v;
15004         ai_info *aip;
15005
15006         dist = vm_vec_normalized_dir(&v2v, vp, &objp->pos);
15007
15008         if (dist < objp->radius + 5.0f) {
15009
15010                 // Start the warp out effect 
15011                 shipfx_warpout_start(objp);
15012
15013         } else {
15014                 dot = vm_vec_dot(&objp->orient.v.fvec, &v2v);
15015
15016                 aip = &Ai_info[Ships[objp->instance].ai_index];
15017
15018                 if (dist > 500.0f)
15019                         accelerate_ship(aip, 1.0f);
15020                 else
15021                         accelerate_ship(aip, (3*dot + 1.0f)/4.0f);
15022
15023                 turn_towards_point(objp, vp, NULL, 0.0f);
15024         }
15025 }
15026 */
15027
15028
15029 //      Do stuff at start of deathroll.
15030 void ai_deathroll_start(object *ship_obj)
15031 {
15032         ai_info *aip;
15033         ship            *shipp, *other_ship;
15034
15035         shipp = &Ships[ship_obj->instance];
15036         aip = &Ai_info[shipp->ai_index];
15037
15038         // mark object we are docked with so we can do damage and separate during deathroll
15039         // keep dock_objnum_when_dead from being changed if already set (only allow to be set when -1)
15040         if (Ships[ship_obj->instance].dock_objnum_when_dead == -1) {
15041                 Ships[ship_obj->instance].dock_objnum_when_dead = aip->dock_objnum;
15042                 // set other_ship dock_objnum_when_dead, if other_ship exits.
15043                 if (Ships[ship_obj->instance].dock_objnum_when_dead != -1) {
15044                         other_ship = &Ships[Objects[aip->dock_objnum].instance];
15045                         other_ship->dock_objnum_when_dead = shipp->objnum;
15046                 }
15047         }
15048
15049         ai_cleanup_dock_mode(aip, shipp);
15050
15051         aip->mode = AIM_NONE;
15052 }
15053
15054 //      Object *requester_objp tells rearm ship to abort rearm.
15055 //      Returns true if it succeeded, else false.
15056 //      To succeed means you were previously rearming.
15057 int ai_abort_rearm_request(object *requester_objp)
15058 {
15059         ship            *requester_shipp;
15060         ai_info *requester_aip;
15061
15062         SDL_assert(requester_objp->type == OBJ_SHIP);
15063         if(requester_objp->type != OBJ_SHIP){
15064                 return 0;
15065         }
15066         SDL_assert((requester_objp->instance >= 0) && (requester_objp->instance < MAX_SHIPS));  
15067         if((requester_objp->instance < 0) || (requester_objp->instance >= MAX_SHIPS)){
15068                 return 0;
15069         }
15070         requester_shipp = &Ships[requester_objp->instance];
15071         SDL_assert((requester_shipp->ai_index >= 0) && (requester_shipp->ai_index < MAX_AI_INFO));              
15072         if((requester_shipp->ai_index < 0) || (requester_shipp->ai_index >= MAX_AI_INFO)){
15073                 return 0;
15074         }       
15075         requester_aip = &Ai_info[requester_shipp->ai_index];
15076         
15077         if (requester_aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED)){
15078
15079                 // dock_objnum is always valid once a rearm repair has been requested.  It points to the
15080                 // ship that is coming to repair me.
15081                 if (requester_aip->dock_objnum != -1) {
15082                         object  *repair_objp;
15083                         ai_info *repair_aip;
15084
15085                         repair_objp = &Objects[requester_aip->dock_objnum];
15086                         repair_aip = &Ai_info[Ships[repair_objp->instance].ai_index];
15087
15088                         //      Make sure signatures match.  This prevents nasty bugs in which an object
15089                         //      that was repairing another is destroyed and is replaced by another ship
15090                         //      before this code comes around.
15091                         if (repair_objp->signature == requester_aip->dock_signature) {
15092
15093                                 SDL_assert( repair_objp->type == OBJ_SHIP );
15094
15095                                 // if support ship is in the process of undocking, don't do anything.
15096                                 if ( repair_aip->submode < AIS_UNDOCK_0 ) {
15097                                         ai_do_objects_repairing_stuff( requester_objp, repair_objp, REPAIR_INFO_ABORT );
15098
15099                                         if ( repair_aip->submode == AIS_DOCK_4 )
15100                                                 repair_aip->submode = AIS_UNDOCK_0;
15101                                         else
15102                                                 repair_aip->submode = AIS_UNDOCK_3;
15103
15104                                         repair_aip->submode_start_time = Missiontime;
15105                                 } else {
15106                                         nprintf(("AI", "Not aborting rearm since already undocking\n"));
15107                                 }
15108                         }
15109                 } else {
15110                         // setting these flags is the safe things to do.  There may not be a corresponding repair
15111                         // ship for this guys since a repair ship may be currently repairing someone else.
15112                         ai_do_objects_repairing_stuff( requester_objp, NULL, REPAIR_INFO_ABORT );
15113
15114                         // try and remove this guy from an arriving support ship.
15115                         mission_remove_scheduled_repair(requester_objp);
15116                 }
15117
15118                 return 1;
15119         } else if ( requester_aip->ai_flags & AIF_REPAIRING ) {
15120                 // a support ship can request to abort when he is told to do something else (like warp out).
15121                 // see if this support ships goal_objnum is valid.  If so, then issue this ai_abort comment
15122                 // for the ship that he is enroute to repair
15123                 if ( requester_aip->goal_objnum != -1 ) {
15124                         int val;
15125
15126                         val = ai_abort_rearm_request( &Objects[requester_aip->goal_objnum] );
15127                         return val;
15128                 }
15129         }
15130
15131         return 0;
15132 }
15133
15134 // function which gets called from ai-issue_rearm_request and from code in missionparse.cpp
15135 // to actually issue the rearm goal (support_obj to rearm requester_obj);
15136 void ai_add_rearm_goal( object *requester_objp, object *support_objp )
15137 {
15138         ship *support_shipp, *requester_shipp;
15139         ai_info *support_aip, *requester_aip;
15140
15141         support_shipp = &Ships[support_objp->instance];
15142         requester_shipp = &Ships[requester_objp->instance];
15143         requester_aip = &Ai_info[requester_shipp->ai_index];
15144
15145         SDL_assert( support_shipp->ai_index != -1 );
15146         support_aip = &Ai_info[support_shipp->ai_index];
15147
15148         // if the requester is a player object, issue the order as the squadmate messaging code does.  Doing so
15149         // ensures that the player get a higher priority!
15150         requester_aip->ai_flags |= AIF_AWAITING_REPAIR; //      Tell that I'm awaiting repair.
15151         if ( requester_objp->flags & OF_PLAYER_SHIP )
15152                 ai_add_ship_goal_player( AIG_TYPE_PLAYER_SHIP, AI_GOAL_REARM_REPAIR, -1, requester_shipp->ship_name, support_aip );
15153         else
15154                 ai_add_goal_ship_internal( support_aip, AI_GOAL_REARM_REPAIR, requester_shipp->ship_name, -1, -1 );
15155
15156 }
15157
15158 //      Object *requester_objp requests rearming.
15159 //      Returns objnum of ship coming to repair requester on success
15160 //      Success means you found someone to rearm you and you weren't previously rearming.
15161 int ai_issue_rearm_request(object *requester_objp)
15162 {
15163         object  *objp;
15164         ship            *requester_shipp;
15165         ai_info *requester_aip;
15166
15167         SDL_assert(requester_objp->type == OBJ_SHIP);
15168         SDL_assert((requester_objp->instance >= 0) && (requester_objp->instance < MAX_SHIPS));
15169         requester_shipp = &Ships[requester_objp->instance];
15170         SDL_assert((requester_shipp->ai_index >= 0) && (requester_shipp->ai_index < MAX_AI_INFO));
15171         requester_aip = &Ai_info[requester_shipp->ai_index];
15172         
15173         //      Make sure not already awaiting repair.
15174         if (requester_aip->ai_flags & AIF_AWAITING_REPAIR) {
15175                 nprintf(("AI", "Ship %s already awaiting rearm by ship %s.\n", requester_shipp->ship_name, &Ships[Objects[requester_aip->dock_objnum].instance].ship_name));    
15176                 return -1;
15177         }
15178
15179         if ( !is_support_allowed(requester_objp) )
15180                 return -1;
15181
15182         //nprintf(("AI", "Ship %s requesting rearming.\n", requester_shipp->ship_name));
15183         requester_aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP);  //      Might request again after this much time.
15184
15185         // call ship_find_repair_ship to get a support ship.  If none is found, then we will warp one in.  This
15186         // function will return the next available ship which can repair requester
15187         objp = ship_find_repair_ship( requester_objp );
15188         ai_do_objects_repairing_stuff( requester_objp, objp, REPAIR_INFO_QUEUE );
15189         if ( objp ) {
15190
15191                 // MWA 5/14/98 -- moved next item into the ai_do_objects_repairing_stuff function so that clients
15192                 // would properly update their hud support view
15193                 //ai_add_rearm_goal( requester_objp, objp );
15194                 return OBJ_INDEX(objp);
15195
15196         } else {
15197                 // call to warp in repair ship!!!!  for now, warp in any number of ships needed.  Should cap it to
15198                 // some reasonable max (or let support ships warp out).  We should assume here that ship_find_repair_ship()
15199                 // would have returned a valid object if there are too many support ships already in the mission
15200                 mission_warp_in_support_ship( requester_objp );
15201
15202                 return -1;
15203         }
15204
15205 }
15206
15207 // make objp rearm and repair goal_objp
15208 void ai_rearm_repair( object *objp, object  *goal_objp, int priority, int docker_index, int dockee_index )
15209 {
15210         ai_info *aip, *goal_aip;
15211
15212         aip = &Ai_info[Ships[objp->instance].ai_index];
15213         aip->goal_objnum = goal_objp-Objects;
15214
15215         // nprintf(("AI", "Ship %s preparing to rearm ship %s.\n", shipp->ship_name, requester_shipp->ship_name));
15216
15217         ai_dock_with_object(objp, goal_objp, priority, AIDO_DOCK, docker_index, dockee_index);
15218         aip->ai_flags |= AIF_REPAIRING;                                         //      Tell that repair guy is busy trying to repair someone.
15219
15220         goal_aip = &Ai_info[Ships[goal_objp->instance].ai_index];
15221         goal_aip->dock_objnum = objp-Objects;           //      Tell which object is coming to repair.
15222         goal_aip->dock_signature = objp->signature;
15223
15224         ai_do_objects_repairing_stuff( goal_objp, objp, REPAIR_INFO_ONWAY );
15225
15226         goal_aip->abort_rearm_timestamp = timestamp(NEXT_REARM_TIMESTAMP*3/2);
15227 }
15228
15229 // Given a dockee object and the index of the dockbay for that object (ie the dockbay index
15230 // into polymodel->dockbays[] for the model associated with the object), return the index
15231 // of a path_num associated with than dockbay (this is an index into polymodel->paths[])
15232 int ai_return_path_num_from_dockbay(object *dockee_objp, int dockbay_index)
15233 {
15234         if ( dockbay_index < 0 || dockee_objp == NULL ) {
15235                 Int3();         // should never happen
15236                 return -1;
15237         }
15238
15239         if ( dockee_objp->type == OBJ_SHIP ) {
15240                 int                     path_num;
15241                 polymodel       *pm;
15242
15243                 pm = model_get( Ships[dockee_objp->instance].modelnum );
15244
15245                 // sanity checks
15246                 SDL_assert(pm->n_docks > dockbay_index);
15247                 SDL_assert(pm->docking_bays[dockbay_index].num_spline_paths > 0);
15248                 SDL_assert(pm->docking_bays[dockbay_index].splines != NULL);
15249                 if(pm->n_docks <= dockbay_index){
15250                         return -1;
15251                 }
15252                 if(pm->docking_bays[dockbay_index].num_spline_paths <= 0){
15253                         return -1;
15254                 }
15255                 if(pm->docking_bays[dockbay_index].splines == NULL){
15256                         return -1;
15257                 }
15258
15259                 // We only need to return one path for the dockbay, so return the first
15260                 path_num = pm->docking_bays[dockbay_index].splines[0];
15261                 return path_num;
15262         } else {
15263                 return -1;
15264         }
15265 }
15266
15267 //      Actually go ahead and fire the synaptics.
15268 void cheat_fire_synaptic(object *objp, ship *shipp, ai_info *aip)
15269 {
15270         ship_weapon     *swp;
15271         swp = &shipp->weapons;
15272         int     current_bank = swp->current_secondary_bank;
15273
15274         ai_select_secondary_weapon(objp, swp, WIF_SPAWN, 0);
15275         if (timestamp_elapsed(swp->next_secondary_fire_stamp[current_bank])) {
15276                 if (ship_fire_secondary(objp)) {
15277                         nprintf(("AI", "ship %s cheat fired synaptic!\n", shipp->ship_name));
15278                         swp->next_secondary_fire_stamp[current_bank] = timestamp(2500);
15279                 }
15280         }
15281 }
15282
15283 //      For the subspace mission (sm3-09a)
15284 //              for delta wing
15285 //                      if they're sufficiently far into the mission
15286 //                              if they're near one or more enemies
15287 //                                      every so often
15288 //                                              fire a synaptic if they have one.
15289 void maybe_cheat_fire_synaptic(object *objp, ai_info *aip)
15290 {
15291         //      Only do in subspace missions.
15292         if ( The_mission.flags & MISSION_FLAG_SUBSPACE )        {
15293                 ship    *shipp;
15294                 int     num, time;
15295
15296                 shipp = &Ships[objp->instance];
15297
15298                 if (!(SDL_strncasecmp(shipp->ship_name, NOX("delta"), 5))) {
15299                         num = shipp->ship_name[6] - '1';
15300
15301                         if ((num >= 0) && (num <= 3)) {
15302                                 time = Missiontime >> 16;       //      Convert to seconds.
15303
15304                                 time -= 2*60;   //      Subtract off two minutes.
15305
15306                                 if (time > 0) {
15307                                         int modulus = 17 + num*3;
15308
15309                                         if ((time % modulus) < 2) {
15310                                                 int count = num_nearby_fighters(get_enemy_team_mask(OBJ_INDEX(objp)), &objp->pos, 1500.0f);
15311
15312                                                 if (count > 0) {
15313                                                         cheat_fire_synaptic(objp, shipp, aip);
15314                                                 }
15315                                         }
15316                                 }
15317                         }
15318                 }
15319         }
15320
15321 }
15322