]> icculus.org git repositories - taylor/freespace2.git/blob - src/ship/aicode.cpp
replace setjmp with try-catch
[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                 try {
1112                         parse_aitbl();                  
1113                 } catch (parse_error_t rval) {
1114                         Error(LOCATION, "Error parsing 'ai.tbl'\r\nError code = %i.\r\n", (int)rval);
1115                 }
1116
1117                 ai_inited = 1;
1118         }
1119
1120         init_semirand();
1121         
1122         ai_level_init();
1123 }
1124
1125 // this inits the ai.  You should be able to call this between
1126 // levels to reset everything.
1127 void ai_level_init()
1128 {
1129         int i;
1130  
1131         // Do the stuff to reset all ai stuff here
1132         for (i=0; i<MAX_AI_INFO ; i++) {
1133                 Ai_info[i].shipnum = -1;
1134         }
1135         Ai_goal_signature = 0;
1136         Ai_friendly_rearm_timestamp = timestamp(-1);
1137         Ai_hostile_rearm_timestamp = timestamp(-1);
1138         Ai_neutral_rearm_timestamp = timestamp(-1);
1139         Ai_traitor_rearm_timestamp = timestamp(-1);
1140
1141         // clear out the stuff needed for AI firing powerful secondary weapons
1142         ai_init_secondary_info();
1143
1144         Ai_last_arrive_path=0;
1145 }
1146
1147 // BEGIN STEALTH
1148 // -----------------------------------------------------------------------------
1149 // Check if object is a stealth ship
1150 int is_object_stealth_ship(object* objp)
1151 {
1152         if (objp->type == OBJ_SHIP) {
1153                 if (Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_STEALTH) {
1154                         return 1;
1155                 }
1156         }
1157
1158         // not stealth ship
1159         return 0;
1160 }
1161
1162 // -----------------------------------------------------------------------------
1163 // Init necessary ai info for new stealth target
1164 void init_ai_stealth_info(ai_info *aip, object *stealth_objp)
1165 {
1166         SDL_assert(is_object_stealth_ship(stealth_objp));
1167
1168         // set necessary ai info for new stealth target
1169         aip->stealth_last_pos = stealth_objp->pos;
1170         aip->stealth_velocity = stealth_objp->phys_info.vel;
1171         aip->stealth_last_visible_stamp = timestamp();
1172 }
1173
1174 // -----------------------------------------------------------------------------
1175 // Check whether Pl_objp can see a stealth ship object
1176 #define STEALTH_INVISIBLE                       0
1177 #define STEALTH_VISIBLE                         1
1178 #define STEALTH_FULLY_TARGETABLE        2
1179
1180 float get_skill_stealth_dist_scaler()
1181 {
1182         // return dist scaler based on skill level
1183         switch (Game_skill_level) {
1184         case 0: // very easy
1185                 return 0.65f;
1186
1187         case 1: // easy
1188                 return 0.9f;
1189
1190         case 2: // medium
1191                 return 1.0f;
1192
1193         case 3: // hard
1194                 return 1.1f;
1195
1196         case 4: // insane
1197                 return 1.3f;
1198
1199         default:
1200                 Int3();
1201         }
1202
1203         return 1.0f;
1204 }
1205
1206 float get_skill_stealth_dot_scaler()
1207 {
1208         // return multiplier on dot based on skill level
1209         switch (Game_skill_level) {
1210         case 0: // very easy
1211                 return 1.3f;
1212
1213         case 1: // easy
1214                 return 1.1f;
1215
1216         case 2: // medium
1217                 return 1.0f;
1218
1219         case 3: // hard
1220                 return 0.9f;
1221
1222         case 4: // insane
1223                 return 0.7f;
1224
1225         default:
1226                 Int3();
1227         }
1228
1229         return 1.0f;
1230 }
1231
1232 int ai_is_stealth_visible(object *viewer_objp, object *stealth_objp)
1233 {
1234         ship *shipp;
1235         vector vec_to_stealth;
1236         float dot_to_stealth, dist_to_stealth, max_stealth_dist;
1237
1238         SDL_assert(stealth_objp->type == OBJ_SHIP);
1239         shipp = &Ships[stealth_objp->instance];
1240         SDL_assert(viewer_objp->type == OBJ_SHIP);
1241
1242         // check if stealth ship
1243         SDL_assert(Ship_info[shipp->ship_info_index].flags & SIF_STEALTH);
1244
1245         // check if in neb and below awac level for visible
1246         if ( !ship_is_visible_by_team(stealth_objp->instance, Ships[viewer_objp->instance].team) ) {
1247                 vm_vec_sub(&vec_to_stealth, &stealth_objp->pos, &viewer_objp->pos);
1248                 dist_to_stealth = vm_vec_mag_quick(&vec_to_stealth);
1249                 dot_to_stealth = vm_vec_dotprod(&viewer_objp->orient.v.fvec, &vec_to_stealth) / dist_to_stealth;
1250
1251                 // get max dist at which stealth is visible
1252                 max_stealth_dist = get_skill_stealth_dist_scaler() * STEALTH_MAX_VIEW_DIST;
1253
1254                 // now check if within view frustrum
1255                 float needed_dot_to_stealth;
1256                 if (dist_to_stealth < 100) {
1257                         needed_dot_to_stealth = 0.0f;
1258                 } else {
1259                         needed_dot_to_stealth = get_skill_stealth_dot_scaler() * float(STEALTH_VIEW_CONE_DOT) * (dist_to_stealth / max_stealth_dist);
1260                 }
1261                 if (dot_to_stealth > needed_dot_to_stealth) {
1262                         if (dist_to_stealth < max_stealth_dist) {
1263                                 return STEALTH_VISIBLE;
1264                         }
1265                 }
1266
1267                 // not within frustrum
1268                 return STEALTH_INVISIBLE;
1269         }
1270
1271         // visible by awacs level
1272         return STEALTH_FULLY_TARGETABLE;
1273 }
1274
1275 // END STEALTH
1276
1277 //      Compute dot product of direction vector and forward vector.
1278 //      Direction vector is vector from one object to other object.
1279 //      Forward vector is the forward vector of the ship.
1280 //      If from_dot == NULL, don't fill it in.
1281 float compute_dots(object *objp, object *other_objp, float *to_dot, float *from_dot)
1282 {
1283         vector  v2o;
1284         float           dist;
1285
1286         dist = vm_vec_normalized_dir(&v2o, &other_objp->pos, &objp->pos);
1287
1288         *to_dot = vm_vec_dot(&objp->orient.v.fvec, &v2o);
1289
1290         if (from_dot != NULL)
1291                 *from_dot = - vm_vec_dot(&other_objp->orient.v.fvec, &v2o);
1292
1293         return dist;
1294 }
1295
1296 // -----------------------------------------------------------------------------
1297 // update estimated stealth info
1298 // this is a "cheat" update
1299 // error increases with time not seen, true distance away, dot to enemey
1300 // this is done only if we can not see the stealth target
1301 // need to infer its position either by weapon fire pos or last know pos
1302 void update_ai_stealth_info_with_error(ai_info *aip/*, int no_error*/)
1303 {
1304 //      object *ship;
1305         object *stealth_objp;
1306         /*
1307         float error_time_mult, error_dist_mult, error_dot_mult, error_mult;
1308         float pos_error, vel_error;
1309         vector error_vec, vec_to_stealth;
1310         float dist_to_stealth, dot_to_stealth;
1311         float delta_time, delta_capped;
1312         */
1313
1314         // make sure I am targeting a stealth ship
1315         SDL_assert( is_object_stealth_ship(&Objects[aip->target_objnum]) );
1316         stealth_objp = &Objects[aip->target_objnum];
1317
1318         // my_ship
1319 //      ship = &Objects[Ships[aip->shipnum].objnum];
1320
1321         // if update is due to weapon fire, get exact stealth position
1322 //      if (no_error) {
1323         aip->stealth_last_pos = stealth_objp->pos;
1324         aip->stealth_velocity = stealth_objp->phys_info.vel;
1325         aip->stealth_last_visible_stamp = timestamp();
1326 //              return;
1327 //      }
1328 /*
1329         // get time since last seen
1330         delta_time = 0.001f * (timestamp() - aip->stealth_last_visible_stamp);
1331
1332         // we don't want our "cheat" guess to more off than what we would get from extrapolating from last visible
1333         // only update if stealth info is "old"
1334         if ( (delta_time) < 0.5 ) {
1335                 return;
1336         }
1337
1338         // find vec_to_stealth and dist
1339         vm_vec_sub(&vec_to_stealth, &stealth_objp->pos, &ship->pos);
1340         dist_to_stealth = vm_vec_normalize_quick(&vec_to_stealth);
1341         dot_to_stealth = vm_vec_dotprod(&vec_to_stealth, &ship->orient.v.fvec);
1342
1343         // put cap on time
1344         delta_capped = delta_time;
1345         if (delta_time > 5.0) {
1346                 delta_capped = 5.0f;
1347         }
1348
1349         // erorr_time_mult (for 0-5) -> (1-6)
1350         error_time_mult = (1.0f + delta_capped);
1351
1352         // error_dot_mult (-1 to 1) -> (1-3)
1353         error_dot_mult = (2 - dot_to_stealth);
1354
1355         // error_dist_mult (0-1000+) -> (1-4)
1356         error_dist_mult = dist_to_stealth * 4.0f * 0.001f;
1357         if (error_dist_mult < 1) {
1358                 error_dist_mult = 1.0f;
1359         } else if (error_dist_mult > 4) {
1360                 error_dist_mult = 4.0f;
1361         }
1362
1363         // multiply error out
1364         error_mult = error_time_mult * error_dot_mult * error_dist_mult;
1365
1366         float base_pos_error = 10;
1367         float base_vel_error = 2;
1368
1369         // find the position and velocity error magnitude;
1370         pos_error = base_pos_error * error_mult;
1371         vel_error = base_vel_error * error_mult;
1372
1373         // get an error that changes slowly over time
1374         static_randvec( ((int)aip ^ (Missiontime >> 18)) & 7, &error_vec);
1375         vm_vec_zero(&error_vec);
1376
1377         // update pos and vel with error
1378         vm_vec_scale_add(&aip->stealth_velocity, &stealth_objp->phys_info.vel, &error_vec, vel_error);
1379
1380         // revise last "known" position to arrive at last pos with given error
1381         vm_vec_scale_add(&aip->stealth_last_pos, &stealth_objp->pos, &error_vec, pos_error);
1382         vm_vec_scale_add2(&aip->stealth_last_pos, &aip->stealth_velocity, -(0.001f * delta_time));
1383         */
1384 }
1385
1386 //      Update danger_weapon_objnum and signature in ai_info to say this weapon is to be avoided.
1387 void ai_update_danger_weapon(int attacked_objnum, int weapon_objnum)
1388 {
1389         object  *objp, *weapon_objp;
1390         ai_info *aip;
1391         float           old_dist, new_dist;
1392         float           old_dot, new_dot;
1393         object  *old_weapon_objp = NULL;
1394
1395         if ((attacked_objnum == -1) || (weapon_objnum == -1)) {
1396                 return;
1397         }
1398
1399         objp = &Objects[attacked_objnum];
1400
1401         // AL 2-24-98: If this isn't a ship, we don't need to worry about updating weapon_objnum (ie it would be
1402         //                                      an asteroid or bomb).
1403         if ( objp->type != OBJ_SHIP ) {
1404                 return;
1405         }
1406
1407         weapon_objp = &Objects[weapon_objnum];
1408
1409         aip = &Ai_info[Ships[objp->instance].ai_index];
1410
1411         // if my taraget is a stealth ship and is not visible
1412         if (aip->target_objnum >= 0) {
1413                 if ( is_object_stealth_ship(&Objects[aip->target_objnum]) ) {
1414                         if ( ai_is_stealth_visible(objp, &Objects[aip->target_objnum]) == STEALTH_INVISIBLE ) {
1415                                 // and the weapon is coming from that stealth ship
1416                                 if (weapon_objp->parent == aip->target_objnum) {
1417                                         // update my position estimate for stealth ship
1418                                         update_ai_stealth_info_with_error(aip/*, 1*/);
1419                                 }
1420                         }
1421                 }
1422         }
1423
1424         if (aip->danger_weapon_objnum != -1) {
1425                 old_weapon_objp = &Objects[aip->danger_weapon_objnum];
1426                 if ((old_weapon_objp->type == OBJ_WEAPON) && (old_weapon_objp->signature == aip->danger_weapon_signature)) {
1427                         ;
1428                 } else {
1429                         aip->danger_weapon_objnum = -1;
1430                 }
1431         }
1432
1433         new_dist = compute_dots(weapon_objp, objp, &new_dot, NULL);
1434
1435         if (aip->danger_weapon_objnum == -1) {
1436                 if (new_dist < 1500.0f) {
1437                         if (new_dot > 0.5f) {
1438                                 aip->danger_weapon_objnum = weapon_objnum;
1439                                 aip->danger_weapon_signature = weapon_objp->signature;
1440                         }
1441                 }
1442         } else {
1443                 SDL_assert(old_weapon_objp != NULL);
1444                 old_dist = compute_dots(old_weapon_objp, objp, &old_dot, NULL);
1445         
1446                 if (old_dot < 0.5f) {
1447                         aip->danger_weapon_objnum = -1;
1448                         old_dist = 9999.9f;
1449                 }
1450
1451                 if ((new_dot > 0.5f) && (new_dot > old_dot-0.01f)) {
1452                         if (new_dist < old_dist) {
1453                                 aip->danger_weapon_objnum = weapon_objnum;
1454                                 aip->danger_weapon_signature = weapon_objp->signature;
1455                         }
1456                 }
1457         }
1458 }
1459
1460 //      If rvec != NULL, use it to match bank by calling vm_matrix_interpolate.
1461 //      (rvec defaults to NULL)
1462 void ai_turn_towards_vector(vector *dest, object *objp, 
1463                                                                          float frametime, float turn_time, vector *slide_vec, vector *rel_pos, float bank_override, int flags, vector *rvec)
1464 {
1465         //matrix        goal_orient;
1466         matrix  curr_orient;
1467         vector  vel_in, vel_out, desired_fvec, src;
1468         float           delta_time;
1469         physics_info    *pip;
1470         vector  vel_limit, acc_limit;
1471         float           delta_bank;
1472
1473         //      Don't allow a ship to turn if it has no engine strength.
1474         // AL 3-12-98: objp may not always be a ship!
1475         if ( objp->type == OBJ_SHIP ) {
1476                 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f)
1477                         return;
1478         }
1479                         
1480         //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));
1481         pip = &objp->phys_info;
1482
1483         vel_in = pip->rotvel;
1484         curr_orient = objp->orient;
1485         delta_time = flFrametime;
1486
1487         SDL_assert(turn_time > 0.0f);
1488         
1489         //      Scale turn_time based on skill level and team.
1490         if (!(flags & AITTV_FAST)){
1491                 if (objp->type == OBJ_SHIP){
1492                         if (Ships[objp->instance].team != Ships[Player_obj->instance].team){
1493                                 turn_time *= Turn_time_skill_level_scale[Game_skill_level];
1494                         }
1495                 }
1496         }
1497
1498         //      Set max turn rate.
1499         vel_limit.xyz.x = 2*PI/turn_time;
1500         vel_limit.xyz.y = 2*PI/turn_time;
1501         vel_limit.xyz.z = 2*PI/turn_time;
1502
1503         //      Set rate at which ship can accelerate to its rotational velocity.
1504         //      For now, weapons just go much faster.
1505         acc_limit = vel_limit;
1506         if (objp->type == OBJ_WEAPON)
1507                 vm_vec_scale(&acc_limit, 8.0f);
1508
1509         src = objp->pos;
1510
1511         if (rel_pos != NULL) {
1512                 vector  gun_point;
1513                 vm_vec_unrotate(&gun_point, rel_pos, &objp->orient);
1514                 vm_vec_add2(&src, &gun_point);
1515         }
1516
1517         vm_vec_normalized_dir(&desired_fvec, dest, &src);
1518
1519         //      Since ship isn't necessarily moving in the direction it's pointing, sometimes it's better
1520         //      to be moving towards goal rather than just pointing.  So, if slide_vec is !NULL, try to
1521         //      make ship move towards goal, not point at goal.
1522         if (slide_vec != NULL) {
1523                 vm_vec_add2(&desired_fvec, slide_vec);
1524                 vm_vec_normalize(&desired_fvec);
1525         }
1526
1527         //      Should be more general case here.  Currently, anything that is not a weapon will bank when it turns.
1528         if (objp->type == OBJ_WEAPON)
1529                 delta_bank = 0.0f;
1530         else if ((bank_override) && (Ships[objp->instance].team & opposing_team_mask(Player_ship->team))) {     //      Theoretically, this will only happen for Shivans.
1531                 delta_bank = bank_override;
1532                 //nprintf(("AI", "%i: %7.3f\n", Framecount, bank_override));
1533         } else {
1534                 delta_bank = vm_vec_dot(&curr_orient.v.rvec, &objp->last_orient.v.rvec);
1535                 delta_bank = 100.0f * (1.0f - delta_bank);
1536                 if (vm_vec_dot(&objp->last_orient.v.fvec, &objp->orient.v.rvec) < 0.0f)
1537                         delta_bank = -delta_bank;
1538
1539                 //nprintf(("AI", "%s: Frame %i: delta bank = %7.3f\n", Ships[objp->instance].ship_name, Framecount, delta_bank));
1540         }
1541
1542         //      Dave Andsager: The non-indented lines here are debug code to help you track down the problem in the physics
1543         //      that is causing ships to inexplicably rotate very far.  If you hit the Int3(), set the next statement to be
1544         //      the one marked "HERE".  (Do this clicking the cursor there, then right clicking.  Choose the right option.)
1545         //      This will allow you to rerun vm_forward_interpolate() with the values that caused the error.
1546         //      Note, you'll need to enable the Int3() about ten lines below.
1547 #ifndef NDEBUG
1548 vector tvec = objp->orient.v.fvec;
1549 vector  vel_in_copy;
1550 matrix  objp_orient_copy;
1551
1552 vel_in_copy = vel_in;
1553 objp_orient_copy = objp->orient;
1554
1555 vel_in = vel_in_copy;   //      HERE
1556 objp->orient = objp_orient_copy;
1557 #endif
1558         if (rvec != NULL) {
1559                 matrix  out_orient, goal_orient;
1560
1561                 vm_vector_2_matrix(&goal_orient, &desired_fvec, NULL, rvec);
1562                 vm_matrix_interpolate(&goal_orient, &curr_orient, &vel_in, delta_time, &out_orient, &vel_out, &vel_limit, &acc_limit);
1563                 objp->orient = out_orient;
1564         } else {
1565                 vm_forward_interpolate(&desired_fvec, &curr_orient, &vel_in, delta_time, delta_bank, &objp->orient, &vel_out, &vel_limit, &acc_limit);
1566         }
1567 #ifndef NDEBUG
1568 if (!((objp->type == OBJ_WEAPON) && (Weapon_info[Weapons[objp->instance].weapon_info_index].subtype == WP_MISSILE))) {
1569         if (delta_time < 0.25f && vm_vec_dot(&objp->orient.v.fvec, &tvec) < 0.1f)
1570                 Int3(); //      Get Andsager.  A ship has turned too far in one frame.
1571 }
1572 #endif
1573
1574         pip->rotvel = vel_out;
1575 }
1576
1577 void init_ship_info()
1578 {
1579         int     i;
1580
1581         if (Ship_info_inited)
1582                 return;
1583
1584         for (i=0; i<MAX_SHIP_TYPES; i++) {
1585                 Ship_info[i].min_speed = - Ship_info[i].max_rear_vel;
1586                 Ship_info[i].max_accel = Ship_info[i].max_vel.xyz.z;
1587         }
1588
1589         Ship_info_inited = 1;
1590
1591 }
1592
1593 //      Set aip->target_objnum to objnum
1594 //      Update aip->previous_target_objnum.
1595 //      If new target (objnum) is different than old target, reset target_time.
1596 int set_target_objnum(ai_info *aip, int objnum)
1597 {
1598 /*
1599         char    old_name[32], new_name[32];
1600
1601         if (!timestamp_elapsed(aip->ok_to_target_timestamp))
1602                 return aip->target_objnum;
1603
1604         if (Player_ship && (Ships[aip->shipnum].team == Player_ship->team)) {
1605                 if (aip->target_objnum == -1)
1606                         strcpy(old_name, "none");
1607                 else
1608                         strcpy(old_name, Ships[Objects[aip->target_objnum].instance].ship_name);
1609
1610                 if (objnum == -1)
1611                         strcpy(new_name, "none");
1612                 else
1613                         strcpy(new_name, Ships[Objects[objnum].instance].ship_name);
1614
1615                 nprintf(("AI", "Ship %s changing target from %s to %s\n", Ships[aip->shipnum].ship_name, old_name, new_name));
1616         }
1617 */
1618
1619         // AL 2-25-97: Ensure that a protected ship isn't being set as a target (for non-players only)
1620         /*
1621         if ( objnum >= 0 ) {
1622                 if ( !(Objects[Ships[aip->shipnum].objnum].flags & OF_PLAYER_SHIP) ) {
1623                         if ( Objects[objnum].flags & OF_PROTECTED ) {
1624                                 // AL 2-26-97: removing Int3() until issue with setting OF_PROTECTED in ai_set_attack_subsystem()
1625                                 //Int3();                                                               // this should not happen
1626                                 return aip->target_objnum;              // don't change targets
1627                         }
1628                 }
1629         }
1630         */
1631
1632         if ((aip != Player_ai) && (!timestamp_elapsed(aip->ok_to_target_timestamp))) {
1633                 return aip->target_objnum;
1634         }
1635
1636         if (aip->target_objnum == objnum) {
1637                 aip->previous_target_objnum = aip->target_objnum;
1638         } else {
1639                 aip->previous_target_objnum = aip->target_objnum;
1640
1641                 // ignore this assert if a multiplayer observer
1642                 if((Game_mode & GM_MULTIPLAYER) && (aip == Player_ai) && (Player_obj->type == OBJ_OBSERVER)){
1643                 } else {
1644                         SDL_assert(objnum != Ships[aip->shipnum].objnum);       //      make sure not targeting self
1645                 }
1646
1647                 // if stealth target, init ai_info for stealth
1648                 if ( (objnum > 0) && is_object_stealth_ship(&Objects[objnum]) ) {
1649                         init_ai_stealth_info(aip, &Objects[objnum]);
1650                 }
1651
1652                 aip->target_objnum = objnum;
1653                 aip->target_time = 0.0f;
1654                 aip->target_signature = Objects[objnum].signature;
1655                 // clear targeted subsystem
1656                 set_targeted_subsys(aip, NULL, -1);
1657         }
1658         
1659         return aip->target_objnum;
1660 }
1661
1662 int ai_select_primary_weapon(object *objp, object *other_objp, int flags);
1663
1664 //      Make new_subsys the targeted subsystem of ship *aip.
1665 ship_subsys *set_targeted_subsys(ai_info *aip, ship_subsys *new_subsys, int parent_objnum)
1666 {
1667         SDL_assert(aip != NULL);
1668
1669         aip->last_subsys_target = aip->targeted_subsys;
1670         aip->targeted_subsys = new_subsys;
1671         aip->targeted_subsys_parent = parent_objnum;
1672
1673         if ( new_subsys ) {
1674                 // Make new_subsys target
1675                 if (new_subsys->system_info->type == SUBSYSTEM_ENGINE) {
1676                         if ( aip != Player_ai ) {
1677                                 ai_select_primary_weapon(&Objects[Ships[aip->shipnum].objnum], &Objects[parent_objnum], WIF_PUNCTURE);
1678                                 ship_primary_changed(&Ships[aip->shipnum]);     // AL: maybe send multiplayer information when AI ship changes primaries
1679                         }
1680                 }
1681
1682                 if ( aip == Player_ai ) {
1683                         hud_lock_reset(0.5f);
1684                 }
1685
1686         } else {
1687                 // Cleanup any subsys path information if it exists
1688                 ai_big_subsys_path_cleanup(aip);
1689         }
1690         
1691         return aip->targeted_subsys;
1692 }                                                                                         
1693
1694 // called to init the data for single ai object.  At this point,
1695 // the ship and the object and the ai_info are are correctly
1696 // linked together. Ai_info[ai_index].shipnum is the only valid field 
1697 // in ai_info.
1698 //      This is called right when the object is parsed, so you can't assume much
1699 //      has been initialized.  For example, wings, waypoints, goals are probably
1700 //      not yet loaded. --MK, 10/8/96
1701 void ai_object_init(object * obj, int ai_index)
1702 {
1703         ai_info *aip;
1704         SDL_assert(ai_index >= 0 && ai_index < MAX_AI_INFO);
1705
1706         aip = &Ai_info[ai_index];
1707
1708         aip->type = 0;          //      0 means not in use.
1709         aip->wing = -1;         //      Member of what wing? -1 means none.
1710         aip->ai_class = Ship_info[Ships[obj->instance].ship_info_index].ai_class;
1711         aip->behavior = AIM_NONE;
1712 }
1713
1714 //      If *aip is docked, set max acceleration to A->mass/(A->mass + B->mass) where A is *aip and B is dock object
1715 void adjust_accel_for_docking(ai_info *aip)
1716 {
1717         if (aip->dock_objnum != -1) {
1718                 object  *obj2p = &Objects[aip->dock_objnum];
1719                 object  *obj1p;
1720
1721                 obj1p = &Objects[Ships[aip->shipnum].objnum];
1722
1723                 if (obj2p->signature == aip->dock_signature) {
1724                         float   ratio;
1725
1726                         ratio = obj1p->phys_info.mass / (obj1p->phys_info.mass + obj2p->phys_info.mass);
1727
1728                         // put cap on how much ship can slow down
1729 #ifdef MAKE_FS1
1730                         // FS1 can go slower, perhaps down to 0, but I'll cap it at .25 just in case
1731                         if (ratio < 0.25f) {
1732                                 ratio = 0.25f;
1733                         }
1734 #else
1735                         if (ratio < 0.8) {
1736                                 ratio = 0.8f;
1737                         }
1738 #endif
1739
1740                         if (AI_ci.forward > ratio) {
1741                                 AI_ci.forward = ratio;
1742                         }
1743                 }
1744         }
1745 }
1746
1747 // -------------------------------------------------------------------
1748 void accelerate_ship(ai_info *aip, float accel)
1749 {
1750         aip->prev_accel = accel;
1751         AI_ci.forward = accel;
1752         adjust_accel_for_docking(aip);
1753 }
1754
1755 //      --------------------------------------------------------------------------
1756 void change_acceleration(ai_info *aip, float delta_accel)
1757 {
1758         float   new_accel;
1759
1760         if (delta_accel < 0.0f) {
1761                 if (aip->prev_accel > 0.0f)
1762                         aip->prev_accel = 0.0f;
1763         } else if (aip->prev_accel < 0.0f)
1764                 aip->prev_accel = 0.0f;
1765
1766         new_accel = aip->prev_accel + delta_accel * flFrametime;
1767
1768         if (new_accel > 1.0f)
1769                 new_accel = 1.0f;
1770         else if (new_accel < -1.0f)
1771                 new_accel = -1.0f;
1772         
1773         aip->prev_accel = new_accel;
1774
1775         AI_ci.forward = new_accel;
1776         adjust_accel_for_docking(aip);
1777 }
1778
1779 void set_accel_for_target_speed(object *objp, float tspeed)
1780 {
1781         float   max_speed;
1782         ai_info *aip;
1783
1784         aip = &Ai_info[Ships[objp->instance].ai_index];
1785
1786         max_speed = Ships[objp->instance].current_max_speed;
1787
1788         AI_ci.forward = tspeed/max_speed;
1789         aip->prev_accel = AI_ci.forward;
1790
1791         adjust_accel_for_docking(aip);
1792 }
1793
1794 //      Stuff perim_point with a point on the perimeter of the sphere defined by object *objp
1795 //      on the vector from the center of *objp through the point *vp.
1796 void project_point_to_perimeter(vector *perim_point, vector *pos, float radius, vector *vp)
1797 {
1798         vector  v1;
1799         float           mag;
1800
1801         vm_vec_sub(&v1, vp, pos);
1802         mag = vm_vec_mag(&v1);
1803
1804         if (mag == 0.0f) {
1805                 Warning(LOCATION, "projectable point is at center of sphere.");
1806                 (void) vm_vec_make(&v1, 0.0f, radius, 0.0f);
1807         } else {
1808                 vm_vec_normalize(&v1);
1809                 vm_vec_scale(&v1, 1.1f * radius + 10.0f);
1810         }
1811
1812         vm_vec_add2(&v1, pos);
1813         *perim_point = v1;
1814 }
1815
1816 //      Stuff tan1 with tangent point on sphere.  tan1 is point nearer to *p1
1817 //      *p0 is point through which tangents pass.
1818 //      *centerp is center of sphere.
1819 //      *p1 is another point in space to define the plane in which tan1, tan2 reside.
1820 //      radius is the radius of the sphere.
1821 //      Note, this is a very approximate function just for AI.
1822 //      Note also: On 12/26/96, p1 is used to define the plane perpendicular to that which
1823 //      contains the tangent point.
1824 void get_tangent_point(vector *tan1, vector *p0, vector *centerp, vector *p1, float radius)
1825 {
1826         vector  dest_vec, v2c, perp_vec, temp_vec, v2;
1827         float           dist, ratio;
1828
1829         //      Detect condition of point inside sphere.
1830         if (vm_vec_dist(p0, centerp) < radius)
1831                 project_point_to_perimeter(tan1, centerp, radius, p0);
1832         else {
1833                 vm_vec_normalized_dir(&v2c, centerp, p0);
1834
1835                 //      Compute perpendicular vector using p0, centerp, p1
1836                 vm_vec_normal(&temp_vec, p0, centerp, p1);
1837                 vm_vec_sub(&v2, centerp, p0);
1838                 vm_vec_cross(&perp_vec, &temp_vec, &v2);
1839
1840                 vm_vec_normalize(&perp_vec);
1841
1842                 dist = vm_vec_dist_quick(p0, centerp);
1843                 ratio = dist / radius;
1844
1845                 if (ratio < 2.0f)
1846                         vm_vec_scale_add(&dest_vec, &perp_vec, &v2c, ratio-1.0f);
1847                 else
1848                         vm_vec_scale_add(&dest_vec, &v2c, &perp_vec, (1.0f + 1.0f/ratio));
1849
1850                 vm_vec_scale_add(tan1, p0, &dest_vec, dist + radius);
1851         }
1852 }
1853
1854 //      --------------------------------------------------------------------------
1855 //      Given an object and a point, turn towards the point, resulting in
1856 // approach behavior.
1857 void turn_towards_point(object *objp, vector *point, vector *slide_vec, float bank_override)
1858 {
1859         ai_info *aip;
1860         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
1861         
1862         // check if in formation and if not leader, don't change rotvel.xyz.z (bank to match leader elsewhere)
1863         if (aip->ai_flags & AIF_FORMATION) {
1864                 if (&Objects[aip->goal_objnum] != objp) {
1865                         float rotvel_z = objp->phys_info.rotvel.xyz.z;
1866                         ai_turn_towards_vector(point, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, slide_vec, NULL, bank_override, 0);
1867                         objp->phys_info.rotvel.xyz.z = rotvel_z;
1868                 }
1869         } else {
1870                 // normal turn
1871                 ai_turn_towards_vector(point, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, slide_vec, NULL, bank_override, 0);
1872         }
1873 }
1874
1875 //      --------------------------------------------------------------------------
1876 //      Given an object and a point, turn away from the point, resulting in avoidance behavior.
1877 //      Note: Turn away at full speed, not scaled down by skill level.
1878 void turn_away_from_point(object *objp, vector *point, float bank_override)
1879 {
1880         vector  opposite_point;
1881
1882         vm_vec_sub(&opposite_point, &objp->pos, point);
1883         vm_vec_add2(&opposite_point, &objp->pos);
1884
1885         ai_turn_towards_vector(&opposite_point, objp, flFrametime, Ship_info[Ships[objp->instance].ship_info_index].srotation_time, NULL, NULL, bank_override, AITTV_FAST);
1886 }
1887
1888
1889 //      --------------------------------------------------------------------------
1890 //      Given an object and a point, turn tangent to the point, resulting in
1891 // a circling behavior.
1892 //      Make object *objp turn around the point *point with a radius of radius.
1893 //      Note that this isn't the same as following a circle of radius radius with
1894 //      center *point, but it should be adequate.
1895 //      Note that if you want to circle an object without hitting it, you should use
1896 //      about twice that object's radius for radius, else you'll certainly bump into it.
1897 //      Return dot product to goal point.
1898 float turn_towards_tangent(object *objp, vector *point, float radius)
1899 {
1900         vector  vec_to_point;
1901         vector  goal_point;
1902         vector  perp_point;                             //      point radius away from *point on vector to objp->pos
1903         vector  up_vec, perp_vec;
1904
1905         vm_vec_normalized_dir(&vec_to_point, point, &objp->pos);
1906         vm_vec_crossprod(&up_vec, &vec_to_point, &objp->orient.v.fvec);
1907         vm_vec_crossprod(&perp_vec, &vec_to_point, &up_vec);
1908
1909         vm_vec_scale_add(&perp_point, point, &vec_to_point, -radius);
1910         if (vm_vec_dot(&objp->orient.v.fvec, &perp_vec) > 0.0f) {
1911                 vm_vec_scale_add(&goal_point, &perp_point, &perp_vec, radius);
1912         } else {
1913                 vm_vec_scale_add(&goal_point, &perp_point, &perp_vec, -radius);
1914         }
1915
1916 //      Ai_info[Ships[objp->instance].ai_index].goal_point = goal_point;
1917         turn_towards_point(objp, &goal_point, NULL, 0.0f);
1918
1919         vector  v2g;
1920
1921         vm_vec_normalized_dir(&v2g, &goal_point, &objp->pos);
1922         return vm_vec_dot(&objp->orient.v.fvec, &v2g);
1923 }
1924
1925 float turn_toward_tangent_with_axis(object *objp, object *center_objp, float radius)
1926 {
1927         vector r_vec, theta_vec;
1928         vector center_vec, vec_on_cylinder, sph_r_vec;
1929         float center_obj_z;
1930
1931         // find closest z of center objp
1932         vm_vec_sub(&sph_r_vec, &objp->pos, &center_objp->pos);
1933         center_obj_z = vm_vec_dotprod(&sph_r_vec, &center_objp->orient.v.fvec);
1934
1935         // find pt on axis with closest z
1936         vm_vec_scale_add(&center_vec, &center_objp->pos, &center_objp->orient.v.fvec, center_obj_z);
1937
1938         // get r_vec
1939         vm_vec_sub(&r_vec, &objp->pos, &center_vec);
1940 //      float r_mag = vm_vec_normalize_quick(&r_vec);
1941 //      mprintf(("cur_r: %.1f, desired_r: %.1f\n", r_mag, radius));
1942         SDL_assert( (vm_vec_dotprod(&r_vec, &center_objp->orient.v.fvec) < 0.0001));
1943
1944         // get theta vec - perp to r_vec and z_vec
1945         vm_vec_crossprod(&theta_vec, &center_objp->orient.v.fvec, &r_vec);
1946
1947 #ifndef NDEBUG
1948         float mag = vm_vec_normalize(&theta_vec);
1949         SDL_assert(mag > 0.9999 && mag < 1.0001);
1950 #endif
1951
1952         vector temp;
1953         vm_vec_crossprod(&temp, &r_vec, &theta_vec);
1954
1955 #ifndef NDEBUG
1956         float dot = vm_vec_dotprod(&temp, &center_objp->orient.v.fvec);
1957         SDL_assert( dot >0.9999 && dot < 1.0001);
1958 #endif
1959
1960         // find pt on clylinder with closest z
1961         vm_vec_scale_add(&vec_on_cylinder, &center_vec, &r_vec, radius);
1962
1963         vector goal_pt, v2g;
1964         vm_vec_scale_add(&goal_pt, &vec_on_cylinder, &theta_vec, radius);
1965
1966 //      Ai_info[Ships[objp->instance].ai_index].goal_point = goal_pt;
1967         turn_towards_point(objp, &goal_pt, NULL, 0.0f);
1968
1969         vm_vec_normalized_dir(&v2g, &goal_pt, &objp->pos);
1970         return vm_vec_dot(&objp->orient.v.fvec, &v2g);
1971 }
1972
1973 //      Returns a point radius units away from *point that *objp should turn towards to orbit *point
1974 void get_tangent_point(vector *goal_point, object *objp, vector *point, float radius)
1975 {
1976         vector  vec_to_point;
1977         vector  perp_point;                             //      point radius away from *point on vector to objp->pos
1978         vector  up_vec, perp_vec;
1979
1980         vm_vec_normalized_dir(&vec_to_point, point, &objp->pos);
1981         vm_vec_crossprod(&up_vec, &vec_to_point, &objp->orient.v.fvec);
1982         vm_vec_crossprod(&perp_vec, &vec_to_point, &up_vec);
1983         vm_vec_normalize(&perp_vec);
1984
1985         vm_vec_scale_add(&perp_point, point, &vec_to_point, -radius);
1986
1987         if (vm_vec_dot(&objp->orient.v.fvec, &perp_vec) > 0.0f) {
1988                 vm_vec_scale_add(goal_point, &perp_point, &perp_vec, radius);
1989         } else {
1990                 vm_vec_scale_add(goal_point, &perp_point, &perp_vec, -radius);
1991         }
1992 }
1993
1994 int     Player_attacking_enabled = 1;
1995
1996 // -----------------------------------------------------------------------------
1997 // Determine whether an object is targetable within a nebula
1998 int object_is_targetable(object *target, ship *viewer)
1999 {
2000         int stealth_ship = 0;
2001
2002         // if target is ship, check if visible by team
2003         if (target->type == OBJ_SHIP) {
2004                 stealth_ship = (Ship_info[Ships[target->instance].ship_info_index].flags & SIF_STEALTH);
2005                 if ( ship_is_visible_by_team(target->instance, viewer->team) == 1) {
2006                         return 1;
2007                 }
2008         }
2009
2010         // for AI partially targetable works as fully targetable, except for stealth ship
2011         if (stealth_ship) {
2012                 // if not team targetable, check if within frustrum
2013                 if ( ai_is_stealth_visible(&Objects[viewer->objnum], target) == STEALTH_VISIBLE ) {
2014                         return 1;
2015                 } else {
2016                         return 0;
2017                 }
2018         }
2019
2020         // if not fully targetable by team, check awacs level with viewer
2021         // allow targeting even if only only partially targetable to player
2022         float radar_return = awacs_get_level(target, viewer);
2023         if ( radar_return > 0.4 ) {
2024                 return 1;
2025         } else {
2026                 return 0;
2027         }
2028 }
2029
2030 //      Return number of enemies attacking object objnum
2031 //
2032 // AL 10.26.97: Also include turrets on large ships when couting enemies attacking
2033 int num_enemies_attacking(int objnum)
2034 {
2035         object          *objp;
2036         ship                    *sp;
2037         ship_subsys     *ssp;
2038         ship_obj                *so;
2039         int                     count;
2040
2041         count = 0;
2042
2043         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2044                 objp = &Objects[so->objnum];
2045                 SDL_assert(objp->instance != -1);
2046                 sp = &Ships[objp->instance];
2047
2048                 if (Ai_info[sp->ai_index].target_objnum == objnum)
2049                         count++;
2050
2051                 // consider turrets that may be attacking objnum (but only turrets on SIF_BIG_SHIP ships)
2052                 if ( Ship_info[sp->ship_info_index].flags & SIF_BIG_SHIP ) {
2053
2054                         // loop through all the subsystems, check if turret has objnum as a target
2055                         ssp = GET_FIRST(&sp->subsys_list);
2056                         while ( ssp != END_OF_LIST( &sp->subsys_list ) ) {
2057
2058                                 if ( ssp->system_info->type == SUBSYSTEM_TURRET ) {
2059                                         if ( (ssp->turret_enemy_objnum == objnum) && (ssp->current_hits > 0) ) {
2060                                                 count++;
2061                                         }
2062                                 }
2063                                 ssp = GET_NEXT( ssp );
2064                         } // end while
2065                 }
2066         }
2067
2068         return count;
2069 }
2070
2071 //      Get the team to fire on given an object.
2072 int get_enemy_team_mask(int objnum)
2073 {
2074         int     my_team, enemy_team_mask;
2075
2076         my_team = Ships[Objects[objnum].instance].team;
2077
2078         if (Mission_all_attack) {
2079                 //      All teams attack all teams.
2080                 switch (my_team) {
2081                 case TEAM_FRIENDLY:
2082                         enemy_team_mask = TEAM_HOSTILE | TEAM_NEUTRAL | TEAM_TRAITOR;
2083                         break;
2084                 case TEAM_HOSTILE:
2085                         enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_TRAITOR;
2086                         break;
2087                 case TEAM_NEUTRAL:
2088                         enemy_team_mask = TEAM_FRIENDLY | TEAM_HOSTILE | TEAM_TRAITOR;
2089                         break;
2090                 case TEAM_UNKNOWN:
2091                         enemy_team_mask = TEAM_HOSTILE;
2092                         break;
2093                 case TEAM_TRAITOR:
2094                         enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_HOSTILE | TEAM_TRAITOR;
2095                         break;
2096                 default:
2097                         enemy_team_mask = TEAM_HOSTILE;
2098                         Int3();                 //      Illegal value for team!
2099                         break;
2100                 }
2101         } else {
2102                 switch (my_team) {
2103                 case TEAM_FRIENDLY:
2104                         enemy_team_mask = TEAM_HOSTILE | TEAM_NEUTRAL | TEAM_TRAITOR;
2105                         break;
2106                 case TEAM_HOSTILE:
2107                         enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_TRAITOR;
2108                         break;
2109                 case TEAM_NEUTRAL:
2110                         enemy_team_mask = TEAM_FRIENDLY | TEAM_TRAITOR;
2111                         break;
2112                 case TEAM_UNKNOWN:
2113                         enemy_team_mask = TEAM_HOSTILE;
2114                         break;
2115                 case TEAM_TRAITOR:
2116                         enemy_team_mask = TEAM_FRIENDLY | TEAM_NEUTRAL | TEAM_HOSTILE | TEAM_TRAITOR;
2117                         break;
2118                 default:
2119                         enemy_team_mask = TEAM_HOSTILE;
2120                         Int3();                 //      Illegal value for team!
2121                         break;
2122                 }
2123         }
2124
2125         return enemy_team_mask;
2126 }
2127
2128 //      Scan all the ships in *objp's wing.
2129 //      Return the lowest maximum speed of a ship in the wing.
2130 //      Current maximum speed (based on energy settings) is shipp->current_max_speed
2131 float get_wing_lowest_max_speed(object *objp)
2132 {
2133         ship            *shipp;
2134         ai_info *aip;
2135         float           lowest_max_speed;
2136         int             wingnum;
2137         object  *o;
2138         ship_obj        *so;
2139
2140         SDL_assert(objp->type == OBJ_SHIP);
2141         SDL_assert((objp->instance >= 0) && (objp->instance < MAX_OBJECTS));
2142         shipp = &Ships[objp->instance];
2143         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
2144         aip = &Ai_info[shipp->ai_index];
2145
2146         wingnum = aip->wing;
2147
2148         lowest_max_speed = shipp->current_max_speed;
2149
2150         if ( wingnum == -1 )
2151                 return lowest_max_speed;
2152
2153         SDL_assert(wingnum >= 0);
2154
2155         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2156                 o = &Objects[so->objnum];
2157                 ship    *oshipp = &Ships[o->instance];
2158                 ai_info *oaip = &Ai_info[oshipp->ai_index];
2159
2160                 if ((oaip->mode == AIM_WAYPOINTS) && (oaip->wing == wingnum)) {
2161                         //      Note: If a ship in the wing has a super low max speed, probably its engines are disabled.  So, fly along and
2162                         //      ignore the poor guy.
2163                         float   cur_max = oshipp->current_max_speed;
2164
2165                         if (oaip->ai_flags & AIF_DOCKED) {
2166                                 if (oaip->dock_objnum > -1)
2167                                         if (Objects[oaip->dock_objnum].type == OBJ_SHIP) 
2168                                                 cur_max *= o->phys_info.mass/(o->phys_info.mass + Objects[oaip->dock_objnum].phys_info.mass);
2169                         }
2170                                                         
2171                         if ((oshipp->current_max_speed > 5.0f) && (cur_max < lowest_max_speed)) {
2172                                 lowest_max_speed = cur_max;
2173                         }
2174                 }
2175         }
2176
2177         return lowest_max_speed;
2178 }
2179
2180 /*
2181 //      Tell everyone to ignore object objnum.
2182 void set_global_ignore_object(int objnum)
2183 {
2184         int     i;
2185
2186         SDL_assert(Objects[objnum].type == OBJ_SHIP);
2187
2188         nprintf(("AI", "Telling everyone to ignore object %s\n", Ships[Objects[objnum].instance].ship_name));
2189
2190         for (i=0; i<MAX_IGNORE_OBJECTS; i++) {
2191                 if (Ignore_objects[i].objnum == -1) {
2192                         Ignore_objects[i].objnum = objnum;
2193                         Ignore_objects[i].signature = Objects[objnum].signature;
2194                         break;
2195                 }
2196         }
2197
2198         if (i == MAX_IGNORE_OBJECTS) {
2199                 //      Couldn't find a free slot, but maybe one of these objects has died.
2200                 for (i=0; i<MAX_IGNORE_OBJECTS; i++) {
2201                         int     o = Ignore_objects[i].objnum;
2202                         if (Objects[o].type != OBJ_SHIP)
2203                                 break;          //      Not a ship, so use this slot.
2204                         if (Objects[o].signature != Ignore_objects[i].signature)
2205                                 break;          //      Signatures don't match, so use this slot.
2206                 }
2207
2208                 if (i != MAX_IGNORE_OBJECTS) {
2209                         Ignore_objects[i].objnum = objnum;
2210                         Ignore_objects[i].signature = Objects[objnum].signature;
2211                 } else {
2212                         nprintf(("Warning", "Ignore_objects buffer full.  Stealing a slot to ignore object #%i\n"));
2213                         Int3();
2214
2215                         int     r;
2216
2217                         r = objnum % MAX_IGNORE_OBJECTS;
2218
2219                         Ignore_objects[r].objnum = objnum;
2220                         Ignore_objects[r].signature = Objects[objnum].signature;
2221                 }
2222         }
2223 }
2224
2225 */
2226
2227 //      Determine if object objnum is supposed to be ignored by object with ai_info *aip.
2228 //      Return:
2229 //              TRUE    if objnum is aip->ignore_objnum (and signatures match)
2230 //                              or objnum is in ignore wing
2231 //              FALSE   otherwise
2232 int is_ignore_object(ai_info *aip, int objnum)
2233 {
2234
2235 /*      //      First, scan all objects in global array of objects to be ignored.
2236         for (int i=0; i<MAX_IGNORE_OBJECTS; i++)
2237                 if (Ignore_objects[i].objnum != -1)
2238                         if (objnum == Ignore_objects[i].objnum)
2239                                 if (Objects[Ignore_objects[i].objnum].signature == Ignore_objects[i].signature)
2240                                         return 1;
2241 */
2242
2243         //      Didn't find in global list.  Now check 
2244         if (aip->ignore_objnum == UNUSED_OBJNUM)
2245                 return 0;                                                                       //      Not ignoring anything.
2246         else if (aip->ignore_objnum >= 0) {             //      This means it's ignoring an object, not a wing.
2247                 if (aip->ignore_objnum == objnum) {
2248                         if (Objects[aip->ignore_objnum].signature == aip->ignore_signature) {
2249                                 return 1;
2250                         } else {
2251                                 aip->ignore_objnum = UNUSED_OBJNUM;
2252                                 return 0;
2253                         }
2254                 } else {
2255                         return 0;
2256                 }
2257         } else {                                                                                        //      Ignoring a wing.
2258                 Int3(); // Should never happen.  I thought I removed this behavior! -- MK, 5/17/98
2259                 return 0;
2260 /*              int     ignore_wingnum = -(aip->ignore_objnum + 1);
2261
2262                 SDL_assert(ignore_wingnum < MAX_WINGS);
2263                 SDL_assert(aip->shipnum >= 0);
2264                 return (Ships[Objects[objnum].instance].wingnum == ignore_wingnum);
2265 */      }
2266 }
2267
2268 // -----------------------------------------------------------------------------
2269
2270 // given a ship with bounding box and a point, find the closest point on the bbox
2271 int get_nearest_bbox_point(object *ship_obj, vector *start, vector *box_pt)
2272 {
2273         vector temp, rf_start;
2274         polymodel *pm;
2275         pm = model_get(Ship_info[Ships[ship_obj->instance].ship_info_index].modelnum);
2276
2277         // get start in ship rf
2278         vm_vec_sub(&temp, start, &ship_obj->pos);
2279         vm_vec_rotate(&rf_start, &temp, &ship_obj->orient);
2280
2281         // find box_pt
2282         int inside = project_point_onto_bbox(&pm->mins, &pm->maxs, &rf_start, &temp);
2283
2284         // get box_pt in world rf
2285         vm_vec_unrotate(box_pt, &temp, &ship_obj->orient);
2286         vm_vec_add2(box_pt, &ship_obj->pos);
2287
2288         return inside;
2289 }
2290
2291
2292 typedef struct eval_nearest_objnum {
2293         int     objnum;
2294         object *trial_objp;
2295         int     enemy_team_mask;
2296         int     enemy_wing;
2297         float   range;
2298         int     max_attackers;
2299         int     nearest_objnum;
2300         float   nearest_dist;
2301         int     check_danger_weapon_objnum;
2302 } eval_nearest_objnum;
2303
2304
2305 void evaluate_object_as_nearest_objnum(eval_nearest_objnum *eno)
2306 {
2307         ai_info *aip;
2308         ship_subsys     *attacking_subsystem;
2309
2310         aip = &Ai_info[Ships[Objects[eno->objnum].instance].ai_index];
2311
2312         attacking_subsystem = aip->targeted_subsys;
2313
2314         if ((attacking_subsystem != NULL) || !(eno->trial_objp->flags & OF_PROTECTED)) {
2315                 if ( OBJ_INDEX(eno->trial_objp) != eno->objnum ) {
2316 #ifndef NDEBUG
2317                         if (!Player_attacking_enabled && (eno->trial_objp == Player_obj))
2318                                 return;
2319 #endif
2320                         //      If only supposed to attack ship in a specific wing, don't attack other ships.
2321                         if ((eno->enemy_wing != -1) && (Ships[eno->trial_objp->instance].wingnum != eno->enemy_wing))
2322                                 return;
2323
2324                         //      Don't keep firing at a ship that is in its death throes.
2325                         if (Ships[eno->trial_objp->instance].flags & SF_DYING)
2326                                 return;
2327
2328                         if (is_ignore_object(aip, ((eno->trial_objp)-Objects)))
2329                                 return;
2330
2331                         if (eno->trial_objp->flags & OF_PROTECTED)
2332                                 return;
2333
2334                         if (Ships[eno->trial_objp->instance].flags & SF_ARRIVING)
2335                                 return;
2336
2337                         ship_info *sip = &Ship_info[Ships[eno->trial_objp->instance].ship_info_index];
2338
2339                         if (sip->flags & (SIF_NO_SHIP_TYPE | SIF_NAVBUOY))
2340                                 return;
2341
2342                         if (Ships[eno->trial_objp->instance].team & eno->enemy_team_mask) {
2343                                 float   dist;
2344                                 int     num_attacking;
2345
2346                                 // Allow targeting of stealth in nebula by his firing at me
2347                                 // This is done for a specific ship, not generally.
2348                                 if ( !eno->check_danger_weapon_objnum ) {
2349                                         // check if can be targeted if inside nebula
2350                                         if ( !object_is_targetable(eno->trial_objp, &Ships[Objects[eno->objnum].instance]) ) {
2351                                                 // check if stealth ship is visible, but not "targetable"
2352                                                 if ( !((sip->flags & SIF_STEALTH) && ai_is_stealth_visible(&Objects[eno->objnum], eno->trial_objp)) ) {
2353                                                         return;
2354                                                 }
2355                                         }
2356                                 }
2357
2358                                 // if objnum is BIG or HUGE, find distance to bbox
2359                                 if (sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
2360                                         vector box_pt;
2361                                         // check if inside bbox
2362                                         int inside = get_nearest_bbox_point(eno->trial_objp, &Objects[eno->objnum].pos, &box_pt);
2363                                         if (inside) {
2364                                                 dist = 10.0f;
2365                                                 // on the box
2366                                         } else {
2367                                                 dist = vm_vec_dist_quick(&Objects[eno->objnum].pos, &box_pt);
2368                                         }
2369                                 } else {
2370                                         dist = vm_vec_dist_quick(&Objects[eno->objnum].pos, &eno->trial_objp->pos);
2371                                 }
2372                                 
2373                                 //      Make it more likely that fighters (or bombers) will be picked as an enemy by scaling up distance for other types.
2374                                 if ((Ship_info[Ships[eno->trial_objp->instance].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER))) {
2375                                         dist = dist * 0.5f;
2376                                 }
2377
2378                                 num_attacking = num_enemies_attacking(eno->trial_objp-Objects);
2379                                 if ((sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) || (num_attacking < eno->max_attackers)) {
2380                                         if (!(sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))){
2381                                                 dist *= (float) (num_attacking+2)/2.0f;                         //      prevents lots of ships from attacking same target
2382                                         }
2383
2384                                         if (eno->trial_objp->flags & OF_PLAYER_SHIP){
2385                                                 dist *= 1.0f + (NUM_SKILL_LEVELS - Game_skill_level - 1)/NUM_SKILL_LEVELS;      //      Favor attacking non-players based on skill level.
2386                                         }
2387
2388                                         if (dist < eno->nearest_dist) {
2389                                                 eno->nearest_dist = dist;
2390                                                 eno->nearest_objnum = eno->trial_objp-Objects;
2391                                         }
2392                                 }
2393                         }
2394                 }
2395         }
2396
2397 }
2398
2399
2400 //      Given an object and an enemy team, return the index of the nearest enemy object.
2401 //      Unless aip->targeted_subsys != NULL, don't allow to attack objects
2402 //      with OF_PROTECTED bit set.
2403 //      Ship must be within range "range".
2404 //      Don't attack a ship that already has at least max_attackers attacking it.
2405 int get_nearest_objnum(int objnum, int enemy_team_mask, int enemy_wing, float range, int max_attackers)
2406 {
2407         object  *danger_weapon_objp;
2408         ai_info *aip;
2409         ship_obj        *so;
2410
2411         // initialize eno struct
2412         eval_nearest_objnum eno;
2413         eno.enemy_team_mask = enemy_team_mask;
2414         eno.enemy_wing = enemy_wing;
2415         eno.max_attackers = max_attackers;
2416         eno.objnum = objnum;
2417         eno.range = range;
2418         eno.nearest_dist = range;
2419         eno.nearest_objnum = -1;
2420         eno.check_danger_weapon_objnum = 0;
2421
2422         // go through the list of all ships and evaluate as potential targets
2423         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2424                 eno.trial_objp = &Objects[so->objnum];
2425                 evaluate_object_as_nearest_objnum(&eno);
2426
2427         }
2428
2429         // check if danger_weapon_objnum has will show a stealth ship
2430         aip = &Ai_info[Ships[Objects[objnum].instance].ai_index];
2431         if (aip->danger_weapon_objnum >= 0) {
2432                 danger_weapon_objp = &Objects[aip->danger_weapon_objnum];
2433                 // validate weapon
2434                 if (danger_weapon_objp->signature == aip->danger_weapon_signature) {
2435                         SDL_assert(danger_weapon_objp->type == OBJ_WEAPON);
2436                         // check if parent is a ship
2437                         if (danger_weapon_objp->parent >= 0) {
2438                                 if ( is_object_stealth_ship(&Objects[danger_weapon_objp->parent]) ) {
2439                                         // check if stealthy
2440                                         if ( ai_is_stealth_visible(&Objects[objnum], &Objects[danger_weapon_objp->parent]) != STEALTH_FULLY_TARGETABLE ) {
2441                                                 // check if weapon is laser
2442                                                 if (Weapon_info[Weapons[danger_weapon_objp->instance].weapon_info_index].subtype == WP_LASER) {
2443                                                         // check stealth ship by its laser fire
2444                                                         eno.check_danger_weapon_objnum = 1;
2445                                                         eno.trial_objp = &Objects[danger_weapon_objp->parent];
2446                                                         evaluate_object_as_nearest_objnum(&eno);
2447                                                 }
2448                                         }
2449                                 }
2450                         }
2451                 }
2452         }
2453
2454         //      If only looking for target in certain wing and couldn't find anything in
2455         //      that wing, look for any object.
2456         if ((eno.nearest_objnum == -1) && (enemy_wing != -1)) {
2457                 return get_nearest_objnum(objnum, enemy_team_mask, -1, range, max_attackers);
2458         }
2459
2460         return eno.nearest_objnum;
2461 }
2462
2463 //      Given an object and an enemy team, return the index of the nearest enemy object.
2464 //      Unlike find_enemy or find_nearest_objnum, this doesn't care about things like the protected flag or number
2465 //      of enemies attacking.
2466 //      It is used to find the nearest enemy to determine things like whether to rearm.
2467 int find_nearby_hostile(int objnum, int enemy_team_mask, float range, int *count)
2468 {
2469         int             nearest_objnum;
2470         float           nearest_dist;
2471         object  *objp;
2472         ship_obj        *so;
2473
2474         nearest_objnum = -1;
2475         nearest_dist = range;
2476
2477         *count = 0;
2478
2479         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2480                 objp = &Objects[so->objnum];
2481
2482                 if ( OBJ_INDEX(objp) != objnum ) {
2483                         if (Ships[objp->instance].flags & SF_DYING)
2484                                 continue;
2485
2486                         if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_NO_SHIP_TYPE | SIF_NAVBUOY))
2487                                 continue;
2488
2489                         if (Ships[objp->instance].team & enemy_team_mask) {
2490                                 float   dist;
2491
2492                                 dist = vm_vec_dist_quick(&Objects[objnum].pos, &objp->pos) - objp->radius*0.75f;
2493                                 
2494                                 if (dist < range) {
2495                                         (*count)++;
2496
2497                                         if (dist < nearest_dist) {
2498                                                 nearest_dist = dist;
2499                                                 nearest_objnum = objp-Objects;
2500                                         }
2501                                 }
2502                         }
2503                 }
2504         }
2505
2506         return nearest_objnum;
2507 }
2508
2509 // return !0 if objp can be considered for a turret target, 0 otherwise
2510 // input:       objp                            =>      object that turret is considering as an enemy
2511 //                              turret_parent   =>      object index for ship that turret sits on
2512 int valid_turret_enemy(object *objp, object *turret_parent)
2513 {
2514         if ( objp == turret_parent ) {
2515                 return 0;
2516         }
2517
2518         if ( objp->type == OBJ_ASTEROID ) {
2519                 return 1;
2520         }
2521
2522         if ( objp->type == OBJ_SHIP ) {
2523                 ship *shipp;
2524                 shipp = &Ships[objp->instance];
2525
2526                 // don't fire at ships with protected bit set!!!
2527                 if ( objp->flags & OF_PROTECTED ) {
2528                         return 0;
2529                 }
2530
2531                 if ( !(Ship_info[shipp->ship_info_index].flags & SIF_DO_COLLISION_CHECK)) {
2532                         return 0;
2533                 }
2534
2535                 if (shipp->flags & SF_ARRIVING) {
2536                         return 0;
2537                 }
2538
2539                 return 1;
2540         }
2541
2542         if ( objp->type == OBJ_WEAPON ) {
2543                 if ( Weapon_info[Weapons[objp->instance].weapon_info_index].wi_flags & WIF_BOMB ) {
2544                         if ( obj_team(turret_parent) != Weapons[objp->instance].team ) {
2545                                 return 1;
2546                         }
2547                 }
2548         }
2549
2550         return 0;
2551 }
2552
2553 // return 1 if objp is in fov of the specified turret, tp.  Otherwise return 0.
2554 //      dist = distance from turret to center point of object
2555 int object_in_turret_fov(object *objp, model_subsystem *tp, vector *tvec, vector *tpos, float dist)
2556 {
2557         vector  v2e;
2558         float           dot;
2559         vm_vec_normalized_dir(&v2e, &objp->pos, tpos);
2560         dot = vm_vec_dot(&v2e, tvec);
2561
2562         dot += objp->radius / (dist + objp->radius);
2563
2564         if ( dot >= tp->turret_fov ) {
2565                 return 1;
2566         }
2567
2568         return 0;
2569 }
2570
2571 // return 1 if bomb_objp is headed towards ship_objp
2572 int bomb_headed_towards_ship(object *bomb_objp, object *ship_objp)
2573 {
2574         float           dot;
2575         vector  bomb_to_ship_vector;
2576
2577         vm_vec_normalized_dir(&bomb_to_ship_vector, &ship_objp->pos, &bomb_objp->pos);
2578         dot = vm_vec_dot(&bomb_objp->orient.v.fvec, &bomb_to_ship_vector);
2579
2580         if ( dot > 0 ) {
2581                 return 1;
2582         }
2583
2584         return 0;
2585 }
2586
2587 // nubmer of live turrets with target_objnum 
2588 int num_turrets_attacking(object *turret_parent, int target_objnum) 
2589 {
2590         ship_subsys *ss;
2591         ship *shipp;
2592         int count = 0;
2593         shipp = &Ships[turret_parent->instance];
2594
2595         SDL_assert(turret_parent->type == OBJ_SHIP);
2596         SDL_assert(Objects[target_objnum].type == OBJ_SHIP);
2597
2598         for (ss=GET_FIRST(&shipp->subsys_list); ss!=END_OF_LIST(&shipp->subsys_list); ss=GET_NEXT(ss)) {
2599                 // check if subsys is alive
2600                 if (ss->current_hits <= 0.0f) {
2601                         continue;
2602                 }
2603
2604                 // check if it's a turret
2605                 if (ss->system_info->type != SUBSYSTEM_TURRET) {
2606                         continue;
2607                 }
2608
2609                 // if the turret is locked
2610                 if(ss->weapons.flags & SW_FLAG_TURRET_LOCK){
2611                         continue;
2612                 }               
2613
2614                 // check if turret is targeting target_objnum
2615                 if (ss->turret_enemy_objnum == target_objnum) {
2616                         count++;
2617                 }
2618         }
2619
2620         return count;
2621 }
2622
2623 float Lethality_range_const = 2.0f;
2624 DCF(lethality_range, "N for modifying range: 1 / (1+N) at 100")
2625 {
2626         dc_get_arg(ARG_FLOAT);
2627         Lethality_range_const = Dc_arg_float;
2628 }
2629
2630 float Player_lethality_bump[NUM_SKILL_LEVELS] = {
2631         // 0.0f, 5.0f, 10.0f, 25.0f, 40.0f
2632         0.0f, 0.0f, 0.0f, 0.0f, 0.0f
2633 };
2634
2635 // evaluate obj as posssible target for turret
2636 void evaluate_obj_as_target(object *objp, eval_enemy_obj_struct *eeo)
2637 {
2638         object  *turret_parent_obj = &Objects[eeo->turret_parent_objnum];
2639         ship            *shipp;
2640         model_subsystem *tp = eeo->turret_subsys->system_info;
2641         float dist;
2642
2643         // Don't look for bombs when weapon system is not ok
2644         if (objp->type == OBJ_WEAPON && !eeo->weapon_system_ok) {
2645                 return;
2646         }
2647
2648         if ( !valid_turret_enemy(objp, turret_parent_obj) ) {
2649                 return;
2650         }
2651
2652 #ifndef NDEBUG
2653         if (!Player_attacking_enabled && (objp == Player_obj)) {
2654                 return;
2655         }
2656 #endif
2657
2658         if ( objp->type == OBJ_SHIP ) {
2659                 shipp = &Ships[objp->instance];
2660
2661                 // check on enemy team
2662                 if ( !(shipp->team & eeo->enemy_team_mask) ) {
2663                         return;
2664                 }
2665
2666                 // check if protected
2667                 if (objp->flags & OF_PROTECTED) {
2668                         return;
2669                 }
2670
2671                 // check if beam protected
2672                 if (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM) {
2673                         if (objp->flags & OF_BEAM_PROTECTED) {
2674                                 return;
2675                         }
2676                 }
2677
2678                 if (eeo->big_only_flag) {
2679                         if (!(Ship_info[shipp->ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
2680                                 return;
2681                         }
2682                 }
2683
2684                 // check if     turret flagged to only target tagged ships
2685                 if ( (eeo->turret_subsys->weapons.flags & SW_FLAG_TAGGED_ONLY) && !ship_is_tagged(objp) ) {
2686                         return;
2687                 }
2688
2689                 // check if valid target in nebula
2690                 if ( !object_is_targetable(objp, &Ships[Objects[eeo->turret_parent_objnum].instance]) ) {
2691                         // BYPASS ocassionally for stealth
2692                         int try_anyway = FALSE;
2693                         if ( is_object_stealth_ship(objp) ) {
2694                                 float turret_stealth_find_chance = 0.5f;
2695                                 float speed_mod = -0.1f + vm_vec_mag_quick(&objp->phys_info.vel) / 70.0f;
2696                                 if (frand() > (turret_stealth_find_chance + speed_mod)) {
2697                                         try_anyway = TRUE;
2698                                 }
2699                         }
2700
2701                         if (!try_anyway) {
2702                                 return;
2703                         }
2704                 }
2705
2706         } else {
2707                 shipp = NULL;
2708         }
2709
2710         // modify dist for BIG|HUGE, getting closest point on bbox, if not inside
2711         dist = vm_vec_dist_quick(eeo->tpos, &objp->pos) - objp->radius;
2712         if (dist < 0.0f) {
2713                 dist = 0.0f;
2714         }
2715
2716         // check if object is a bomb attacking the turret parent
2717         // check if bomb is homing on the turret parent ship
2718         if (objp->type == OBJ_WEAPON) {
2719                 if ( Weapons[objp->instance].homing_object == &Objects[eeo->turret_parent_objnum] ) {
2720                         if ( dist < eeo->nearest_homing_bomb_dist ) {
2721                                 if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2722                                         eeo->nearest_homing_bomb_dist = dist;
2723                                         eeo->nearest_homing_bomb_objnum = OBJ_INDEX(objp);
2724                                 }
2725                         }
2726                 // if not homing, check if bomb is flying towards ship
2727                 } else if ( bomb_headed_towards_ship(objp, &Objects[eeo->turret_parent_objnum]) ) {
2728                         if ( dist < eeo->nearest_bomb_dist ) {
2729                                 if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2730                                         eeo->nearest_bomb_dist = dist;
2731                                         eeo->nearest_bomb_objnum = OBJ_INDEX(objp);
2732                                 }
2733                         }
2734                 }
2735         } // end weapon section
2736
2737         // maybe recalculate dist for big or huge ship
2738 //      if (shipp && (Ship_info[shipp->ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
2739 //              fvi_ray_boundingbox(min, max, start, direction, hit);
2740 //              dist = vm_vec_dist_quick(hit, tvec);
2741 //      }
2742
2743         // check for nearest attcker
2744         if ( (shipp) && (dist < eeo->weapon_travel_dist) ) {
2745                 ai_info *aip = &Ai_info[shipp->ai_index];
2746
2747                 // modify distance based on number of turrets from my ship attacking enemy (add 10% per turret)
2748                 // dist *= (num_enemies_attacking(OBJ_INDEX(objp))+2)/2;        //      prevents lots of ships from attacking same target
2749                 int num_att_turrets = num_turrets_attacking(turret_parent_obj, OBJ_INDEX(objp));
2750                 dist *= (1.0f + 0.1f*num_att_turrets);
2751
2752                 // return if we're over the cap
2753                 int max_turrets = 3 + Game_skill_level * Game_skill_level;
2754                 if (num_att_turrets > max_turrets) {
2755                         return;
2756                 }
2757
2758                 // modify distance based on lethality of objp to my ship
2759                 float active_lethality = aip->lethality;
2760                 if (objp->flags & OF_PLAYER_SHIP) {
2761                         active_lethality += Player_lethality_bump[Game_skill_level];
2762                 }
2763
2764                 dist /= (1.0f + 0.01f*Lethality_range_const*active_lethality);
2765
2766                 // Make level 2 tagged ships more likely to be targeted
2767                 if (shipp->level2_tag_left > 0.0f) {
2768                         dist *= 0.3f;
2769                 }
2770
2771                 // check if objp is targeting the turret's ship, or if objp has just hit the turret's ship
2772                 if ( aip->target_objnum == eeo->turret_parent_objnum || aip->last_objsig_hit == Objects[eeo->turret_parent_objnum].signature ) {
2773                         // A turret will always target a ship that is attacking itself... self-preservation!
2774                         if ( aip->targeted_subsys == eeo->turret_subsys ) {
2775                                 dist *= 0.5f;   // highest priority
2776                         }
2777                 }
2778
2779                 // maybe update nearest attacker
2780                 if ( dist < eeo->nearest_attacker_dist ) {
2781                         if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2782                                 // 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));
2783                                 eeo->nearest_attacker_dist = dist;
2784                                 eeo->nearest_attacker_objnum = OBJ_INDEX(objp);
2785                         }
2786                 }
2787         } // end ship section
2788
2789 #ifdef MAKE_FS1
2790         // check if object is an asteroid attacking the turret parent - taylor
2791         if (objp->type == OBJ_ASTEROID) {
2792                 if ( eeo->turret_parent_objnum == asteroid_collide_objnum(objp) ) {
2793                         // give priority to the closest asteroid *impact* (ms intervals)
2794                         dist *= 0.9f + (0.01f * asteroid_time_to_impact(objp));
2795
2796                         if (dist < eeo->nearest_dist ) {
2797                                 if ( (eeo->current_enemy == -1) || object_in_turret_fov(objp, tp, eeo->tvec, eeo->tpos, dist + objp->radius) ) {
2798                                         eeo->nearest_dist = dist;
2799                                         eeo->nearest_objnum = OBJ_INDEX(objp);
2800                                 }
2801                         }
2802                 }
2803         } // end asteroid selection
2804 #endif
2805 }
2806
2807 // return 0 only if objnum is beam protected and turret is beam turret
2808 int is_target_beam_valid(ship_subsys *turret_subsys, int objnum)
2809 {
2810         // check if turret has beam weapon
2811         model_subsystem *tp = turret_subsys->system_info;
2812
2813         if (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM) {
2814                 if (Objects[objnum].flags & OF_BEAM_PROTECTED) {
2815                         return 0;
2816                 }
2817
2818                 if (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_HUGE) {
2819                         if (Objects[objnum].type == OBJ_SHIP && !(Ship_info[Ships[Objects[objnum].instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) ) {
2820                                 return 0;
2821                         }
2822                 }
2823         }
2824
2825         return 1;
2826 }
2827
2828
2829 //      Given an object and an enemy team, return the index of the nearest enemy object.
2830 //
2831 // input:
2832 //                              turret_parent_objnum    => parent objnum for the turret
2833 //                              turret_subsys                   => pointer to system_info for the turret subsystem
2834 //                              enemy_team_mask         => OR'ed TEAM_ flags for the enemy of the turret parent ship
2835 //                              tpos                                            => position of turret (world coords)
2836 //                              tvec                                            => forward vector of turret (world coords)
2837 //                              current_enemy                   =>      objnum of current turret target
2838 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)
2839 {
2840         float                                   weapon_travel_dist;
2841         int                                     weapon_system_ok;
2842         object                          *objp;
2843         model_subsystem *tp;
2844         eval_enemy_obj_struct eeo;
2845
2846         // list of stuff to go thru
2847         ship_obj                *so;
2848         missile_obj *mo;
2849
2850         tp = turret_subsys->system_info;
2851         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);
2852
2853         // Set flag based on strength of weapons subsystem.  If weapons subsystem is destroyed, don't let turrets fire at bombs
2854         weapon_system_ok = 0;
2855         if ( ship_get_subsystem_strength( &Ships[Objects[turret_parent_objnum].instance], SUBSYSTEM_WEAPONS ) > 0 ) {
2856                 weapon_system_ok = 1;
2857         }
2858
2859         // Initialize eeo struct.
2860         eeo.turret_parent_objnum = turret_parent_objnum;
2861         eeo.weapon_system_ok = weapon_system_ok;
2862         eeo.weapon_travel_dist = weapon_travel_dist;
2863         eeo.big_only_flag = big_only_flag;
2864         eeo.enemy_team_mask = enemy_team_mask;
2865         eeo.current_enemy = current_enemy;
2866         eeo.tpos = tpos;
2867         eeo.tvec = tvec;
2868         eeo.turret_subsys = turret_subsys;
2869
2870         eeo.nearest_attacker_dist = 99999.0f;
2871         eeo.nearest_attacker_objnum = -1;
2872
2873         eeo.nearest_homing_bomb_dist = 99999.0f;
2874         eeo.nearest_homing_bomb_objnum = -1;
2875
2876         eeo.nearest_bomb_dist = 99999.0f;
2877         eeo.nearest_bomb_objnum = -1;
2878
2879         eeo.nearest_dist = 99999.0f;
2880         eeo.nearest_objnum = -1;
2881
2882
2883         // Missile_obj_list
2884         for( mo = GET_FIRST(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
2885                 objp = &Objects[mo->objnum];
2886                 evaluate_obj_as_target(objp, &eeo);
2887         }
2888         // highest priority
2889         if ( eeo.nearest_homing_bomb_objnum != -1 ) {                                   // highest priority is an incoming homing bomb
2890                 return eeo.nearest_homing_bomb_objnum;
2891         } else if ( eeo.nearest_bomb_objnum != -1 ) {                                   // next highest priority is an incoming dumbfire bomb
2892                 return eeo.nearest_bomb_objnum;
2893         }
2894
2895
2896         // Ship_used_list
2897         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
2898                 objp = &Objects[so->objnum];
2899                 evaluate_obj_as_target(objp, &eeo);
2900         }
2901
2902         SDL_assert(eeo.nearest_attacker_objnum < 0 || is_target_beam_valid(turret_subsys, eeo.nearest_attacker_objnum));
2903                 // next highest priority is attacking ship
2904         if ( eeo.nearest_attacker_objnum != -1 ) {                      // next highest priority is an attacking ship
2905                 return eeo.nearest_attacker_objnum;
2906          }
2907
2908
2909 #if !(defined(FS2_DEMO) || defined(FS1_DEMO))
2910                 asteroid_obj *ao;
2911         // Asteroid_obj_list
2912         for( ao = GET_FIRST(&Asteroid_obj_list); ao != END_OF_LIST(&Asteroid_obj_list); ao = GET_NEXT(ao) ) {
2913                 objp = &Objects[ao->objnum];
2914                 evaluate_obj_as_target(objp, &eeo);
2915         }
2916 #endif
2917
2918         return eeo.nearest_objnum;                                                                              // lowest priority is the closest enemy objnum
2919 }
2920
2921 //      Return timestamp until a ship can find an enemy.
2922 //      Yes, no parameters.  Based solely on skill level.
2923 int get_enemy_timestamp()
2924 {
2925         return (NUM_SKILL_LEVELS - Game_skill_level) * ( (myrand() % 500) + 500);
2926 }
2927
2928 // -------------------------------------------------------------------
2929 //      Return objnum if enemy found, else return -1;
2930 //      Don't attack a ship that already has at least max_attackers attacking it.
2931 int find_enemy(int objnum, float range, int max_attackers)
2932 {
2933         int     enemy_team_mask;
2934
2935         enemy_team_mask = get_enemy_team_mask(objnum);
2936
2937         //      if target_objnum != -1, use that as goal.
2938         ai_info *aip = &Ai_info[Ships[Objects[objnum].instance].ai_index];
2939         if (timestamp_elapsed(aip->choose_enemy_timestamp)) {
2940                 aip->choose_enemy_timestamp = timestamp(get_enemy_timestamp());
2941                 if (aip->target_objnum != -1) {
2942                         int     target_objnum = aip->target_objnum;
2943
2944                         // DKA don't undo object as target in nebula missions.
2945                         // This could cause attack on ship on fringe on nebula to stop if attackee moves our of nebula range.  (BAD)
2946                         if (Objects[target_objnum].signature == aip->target_signature) {
2947                                 if (Ships[Objects[target_objnum].instance].team & enemy_team_mask) {
2948                                         if (!(Objects[target_objnum].flags & OF_PROTECTED)) {
2949                                                 // nprintf(("AI", "Frame %i: Object %i resuming goal of object %i\n", AI_FrameCount, objnum, target_objnum));
2950                                                 return target_objnum;
2951                                         }
2952                                 }
2953                         } else {
2954                                 aip->target_objnum = -1;
2955                                 aip->target_signature = -1;
2956                         }
2957                 }
2958                 return get_nearest_objnum(objnum, enemy_team_mask, aip->enemy_wing, range, max_attackers);
2959         } else {
2960                 aip->target_objnum = -1;
2961                 aip->target_signature = -1;
2962                 return -1;
2963         }
2964
2965 }
2966
2967 int Use_parent_target = 0;
2968 DCF_BOOL(use_parent_target, Use_parent_target)
2969
2970 // -------------------------------------------------------------------
2971 //      Return objnum if enemy found, else return -1;
2972 //
2973 // input:
2974 //                              turret_subsys   => pointer to turret subsystem
2975 //                              objnum                  => parent objnum for the turret
2976 //                              tpos                            => position of turret (world coords)
2977 //                              tvec                            => forward vector of turret (world coords)
2978 //                              current_enemy   =>      objnum of current turret target
2979 int find_turret_enemy(ship_subsys *turret_subsys, int objnum, vector *tpos, vector *tvec, int current_enemy, float fov, int big_only_flag = 0)
2980 {
2981         int                                     enemy_team_mask, enemy_objnum;
2982         model_subsystem *tp;
2983         ship_info                       *sip;
2984
2985         tp = turret_subsys->system_info;
2986         enemy_team_mask = get_enemy_team_mask(objnum);
2987
2988         //      If a small ship and target_objnum != -1, use that as goal.
2989         ai_info *aip = &Ai_info[Ships[Objects[objnum].instance].ai_index];
2990         sip = &Ship_info[Ships[Objects[objnum].instance].ship_info_index];
2991
2992         if ((sip->flags & SIF_SMALL_SHIP) && (aip->target_objnum != -1)) {
2993                 int target_objnum = aip->target_objnum;
2994
2995                 if (Objects[target_objnum].signature == aip->target_signature) {
2996                         if (Ships[Objects[target_objnum].instance].team & enemy_team_mask) {
2997                                 if ( !(Objects[target_objnum].flags & OF_PROTECTED) ) {         // check this flag as well.
2998                                         // nprintf(("AI", "Frame %i: Object %i resuming goal of object %i\n", AI_FrameCount, objnum, target_objnum));
2999                                         return target_objnum;
3000                                 }
3001                         }
3002                 } else {
3003                         aip->target_objnum = -1;
3004                         aip->target_signature = -1;
3005                 }
3006         // Not small or small with target objnum
3007         } else {
3008                 // maybe use aip->target_objnum as next target
3009                 if ((frand() < 0.8f) && (aip->target_objnum != -1) && Use_parent_target) {
3010
3011                         //check if aip->target_objnum is valid target
3012                         int target_flags = Objects[aip->target_objnum].flags;
3013                         if ( target_flags & OF_PROTECTED ) {
3014                                 // AL 2-27-98: why is a protected ship being targeted?
3015                                 set_target_objnum(aip, -1);
3016                                 return -1;
3017                         }
3018
3019                         // maybe use ship target_objnum if valid for turret
3020                         // check for beam weapon and beam protected
3021                         if ( !((target_flags & OF_BEAM_PROTECTED) && (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM)) ) {
3022                                 if ( Objects[aip->target_objnum].type == OBJ_SHIP ) {
3023                                         // check for huge weapon and huge ship
3024                                         if ( !big_only_flag || (Ship_info[Ships[Objects[aip->target_objnum].instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) ) {
3025                                                 // check for tagged only and tagged ship
3026                                                 if ( (turret_subsys->weapons.flags & SW_FLAG_TAGGED_ONLY) && ship_is_tagged(&Objects[aip->target_objnum]) ) {
3027                                                         // select new target if aip->target_objnum is out of field of view
3028                                                         vector v2e;
3029                                                         float dot;//, dist;
3030                                                         /*dist =*/ vm_vec_normalized_dir(&v2e, &Objects[aip->target_objnum].pos, tpos);
3031                                                         dot = vm_vec_dot(&v2e, tvec);
3032                                                         //      MODIFY FOR ATTACKING BIG SHIP
3033                                                         // dot += (0.5f * Objects[aip->target_objnum].radius / dist);
3034                                                         if (dot > fov) {
3035                                                                 return aip->target_objnum;
3036                                                         }
3037                                                 }
3038                                         }
3039                                 }
3040                         }
3041                 }
3042         }
3043
3044         enemy_objnum = get_nearest_turret_objnum(objnum, turret_subsys, enemy_team_mask, tpos, tvec, current_enemy, big_only_flag);
3045         if ( enemy_objnum >= 0 ) {
3046                 SDL_assert( !((Objects[enemy_objnum].flags & OF_BEAM_PROTECTED) && (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM)) );
3047                 if ( Objects[enemy_objnum].flags & OF_PROTECTED ) {
3048                         Int3();
3049                         enemy_objnum = aip->target_objnum;
3050                 }
3051         }
3052
3053         return enemy_objnum;
3054 }
3055
3056 //      If issued an order to a ship that's awaiting repair, abort that process.
3057 //      However, do not abort process for an object that is currently being repaired -- let it finish.
3058 void ai_set_goal_maybe_abort_dock(object *objp, ai_info *aip)
3059 {
3060         if (aip->ai_flags & AIF_AWAITING_REPAIR) {
3061                 object  *repair_obj;
3062
3063                 if (aip->dock_objnum == -1) {
3064                         repair_obj = NULL;
3065                 } else {
3066                         repair_obj = &Objects[aip->dock_objnum];
3067                 }
3068                 ai_do_objects_repairing_stuff( objp, repair_obj, REPAIR_INFO_ABORT );
3069         }
3070         aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP);    //      Might request again after 30 seconds.
3071 }
3072
3073 void force_avoid_player_check(object *objp, ai_info *aip)
3074 {
3075         if (Ships[objp->instance].team == Player_ship->team){
3076                 aip->avoid_check_timestamp = timestamp(0);              //      Force a check for collision next frame.
3077         }
3078 }
3079
3080 //      --------------------------------------------------------------------------
3081 //      Set *attacked as object to attack for object *attacker
3082 //      If attacked == NULL, then attack any enemy object.
3083 //      Attack point *rel_pos on object.  This is for supporting attacking subsystems.
3084 void ai_attack_object(object *attacker, object *attacked, int priority, ship_subsys *ssp)
3085 {
3086         ai_info *aip;
3087
3088         SDL_assert(attacker != NULL);
3089         SDL_assert(attacker->instance != -1);
3090         SDL_assert(Ships[attacker->instance].ai_index != -1);
3091
3092         aip = &Ai_info[Ships[attacker->instance].ai_index];
3093         force_avoid_player_check(attacker, aip);
3094
3095         aip->ok_to_target_timestamp = timestamp(0);             //      Guarantee we can target.
3096
3097 //      if (!SDL_strncasecmp(Ships[attacker->instance].ship_name, NOX("Kami"), 4)) {
3098 //              aip->ai_flags |= AIF_KAMIKAZE;
3099 //              aip->ai_flags |= AIF_NO_DYNAMIC;
3100 //      }
3101
3102         if (attacker == attacked) {
3103                 Int3();         //      Bogus!  Who tried to get me to attack myself!  Trace out and fix!
3104                 return;
3105         }
3106
3107         //      Only set to chase if a fighter or bomber, otherwise just return.
3108         if (!(Ship_info[Ships[attacker->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
3109 //              nprintf(("AI","Note: AI ship %s refusing to set AI mode to AIM_CHASE\n", Ships[attacker->instance].ship_name));
3110 //              return;
3111                 nprintf(("AI", "AI ship %s is large ship ordered to attack %s\n", Ships[attacker->instance].ship_name, Ships[attacked->instance].ship_name));
3112         }
3113
3114         //      This is how "engage enemy" gets processed
3115         if (attacked == NULL) {
3116                 aip->choose_enemy_timestamp = timestamp(0);
3117                 // nebula safe
3118                 set_target_objnum(aip, find_enemy(attacker-Objects, 99999.9f, 4));
3119         } else {
3120                 // check if we can see atacked in nebula
3121                 if (aip->target_objnum != attacked - Objects) {
3122                         aip->aspect_locked_time = 0.0f;
3123                 }
3124                 set_target_objnum(aip, attacked - Objects);
3125         }
3126
3127         ai_set_goal_maybe_abort_dock(attacker, aip);
3128         aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);     //      No dynamic targeting for 7 seconds.
3129
3130         if (is_ignore_object(aip, aip->target_objnum)) {
3131                 aip->ignore_objnum = UNUSED_OBJNUM;
3132         }
3133
3134         aip->mode = AIM_CHASE;
3135         aip->submode = SM_ATTACK;       // AL 12-15-97: need to set submode?  I got an assert() where submode was bogus
3136                                                                                 //                                       for AIM_CHASE... it may have been not set correctly here
3137         if (ssp == NULL) {
3138                 set_targeted_subsys(aip, NULL, -1);
3139                 if (aip->target_objnum != -1) {
3140                         //nprintf(("AI", "Unprotecting ship %s\n", Ships[Objects[aip->target_objnum].instance].ship_name));
3141                         Objects[aip->target_objnum].flags &= ~OF_PROTECTED;     //      If ship had been protected, unprotect it.
3142                 }
3143         } else {
3144                 Int3(); //      Not supported yet!
3145         }
3146 }
3147
3148 //      --------------------------------------------------------------------------
3149 //      Set *attacked as object to attack for object *attacker
3150 //      Attack point *rel_pos on object.  This is for supporting attacking subsystems.
3151 void ai_attack_wing(object *attacker, int wingnum, int priority)
3152 {
3153         ai_info *aip;
3154
3155         SDL_assert(attacker != NULL);
3156         SDL_assert(attacker->instance != -1);
3157         SDL_assert(Ships[attacker->instance].ai_index != -1);
3158
3159         aip = &Ai_info[Ships[attacker->instance].ai_index];
3160
3161         aip->enemy_wing = wingnum;
3162         aip->mode = AIM_CHASE;
3163         aip->submode = SM_ATTACK;       // AL 12-15-97: need to set submode?  I got an assert() where submode was bogus
3164                                                                                 //                                       for AIM_CHASE... it may have been not set correctly here
3165
3166         aip->ok_to_target_timestamp = timestamp(0);             //      Guarantee we can target.
3167
3168         int count = Wings[wingnum].current_count;
3169         if (count > 0) {
3170                 int     index;
3171
3172                 index = (int) (frand() * count);
3173
3174                 if (index >= count)
3175                         index = 0;
3176
3177                 set_target_objnum(aip, Ships[Wings[wingnum].ship_index[index]].objnum);
3178
3179                 ai_set_goal_maybe_abort_dock(attacker, aip);
3180                 aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);     //      No dynamic targeting for 7 seconds.
3181         }
3182 }
3183
3184 //      --------------------------------------------------------------------------
3185 //      Set *evaded as object for *evader to evade.
3186 void ai_evade_object(object *evader, object *evaded, int priority)
3187 {
3188         ai_info *aip;
3189
3190         SDL_assert(evader != NULL);
3191         SDL_assert(evaded != NULL);
3192         SDL_assert(evader->instance != -1);
3193         SDL_assert(Ships[evader->instance].ai_index != -1);
3194
3195         if (evaded == evader) {
3196                 Int3(); //      Bogus!  Who tried to get me to evade myself!  Trace out and fix!
3197                 return;
3198         }
3199
3200         aip = &Ai_info[Ships[evader->instance].ai_index];
3201
3202         set_target_objnum(aip, evaded - Objects);
3203         aip->mode = AIM_EVADE;
3204
3205 }
3206
3207 //      Ignore some object without changing mode.
3208 void ai_ignore_object(object *ignorer, object *ignored, int priority)
3209 {
3210         ai_info *aip;
3211
3212         SDL_assert(ignorer != NULL);
3213         SDL_assert(ignored != NULL);
3214         SDL_assert(ignorer->instance != -1);
3215         SDL_assert(Ships[ignorer->instance].ai_index != -1);
3216         SDL_assert(ignorer != ignored);
3217
3218         aip = &Ai_info[Ships[ignorer->instance].ai_index];
3219
3220         //      MK, 5/17/98, removing ignoring of wings.
3221         //      It's too confusing.  It often causes mysterious behavior in which fighters unexpectedly refuse to attack anything.
3222 /*      if (Ships[ignored->instance].wingnum > -1) {
3223                 int wingnum, i;
3224
3225                 wingnum = Ships[ignored->instance].wingnum;
3226                 aip->ignore_objnum = -(wingnum+1);
3227                 // set protected bit for each ship in a wing
3228                 //      MK, 4/23/98: Only set for fighters if they are the original "ignored" object
3229                 for (i = 0; i < Wings[wingnum].current_count; i++ ) {
3230                         object  *objp;
3231
3232                         objp = &Objects[Ships[Wings[wingnum].ship_index[i]].objnum];
3233                         if (objp != ignored) {
3234                                 if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER))
3235                                         continue;
3236                         }
3237
3238                         Objects[Ships[Wings[wingnum].ship_index[i]].objnum].flags |= OF_PROTECTED;
3239                 }
3240
3241         } else {
3242         */ {
3243                 aip->ignore_objnum = ignored - Objects;
3244                 aip->ignore_signature = ignored->signature;
3245                 aip->ai_flags &= ~AIF_TEMPORARY_IGNORE;
3246                 ignored->flags |= OF_PROTECTED;                                 // set protected bit of ignored ship.
3247         }
3248
3249 }
3250
3251 //      Ignore some object without changing mode.
3252 void ai_ignore_wing(object *ignorer, int wingnum, int priority)
3253 {
3254         ai_info *aip;
3255
3256         SDL_assert(ignorer != NULL);
3257         SDL_assert(ignorer->instance != -1);
3258         SDL_assert(Ships[ignorer->instance].ai_index != -1);
3259         SDL_assert((wingnum >= 0) && (wingnum < MAX_WINGS));
3260
3261         aip = &Ai_info[Ships[ignorer->instance].ai_index];
3262
3263         aip->ignore_objnum = -(wingnum +1);
3264         aip->ai_flags &= ~AIF_TEMPORARY_IGNORE;
3265 }
3266
3267
3268 //      Add a path point in the global buffer Path_points.
3269 //      modify_index = index in Path_points at which to store path point.
3270 //      If modify_index == -1, then create a new point.
3271 //      If a new point is created (ie, modify_index == -1), then Ppfp is updated.
3272 void add_path_point(vector *pos, int path_num, int path_index, int modify_index)
3273 {
3274         pnode   *pnp;
3275
3276         if (modify_index == -1) {
3277                 SDL_assert(Ppfp-Path_points < MAX_PATH_POINTS-1);
3278                 pnp = Ppfp;
3279                 Ppfp++;
3280         } else {
3281                 SDL_assert((modify_index >= 0) && (modify_index < MAX_PATH_POINTS-1));
3282                 pnp = &Path_points[modify_index];
3283         }
3284
3285         pnp->pos = *pos;
3286         pnp->path_num = path_num;
3287         pnp->path_index = path_index;
3288 }
3289
3290 //      Given two points on a sphere, the center of the sphere and the radius, return a
3291 //      point on the vector through the midpoint of the chord on the sphere.
3292 void bisect_chord(vector *p0, vector *p1, vector *centerp, float radius)
3293 {
3294         vector  tvec;
3295         vector  new_pnt;
3296
3297         vm_vec_add(&tvec, p0, p1);
3298         vm_vec_sub2(&tvec, centerp);
3299         vm_vec_sub2(&tvec, centerp);
3300         if (vm_vec_mag_quick(&tvec) < 0.1f) {
3301                 vm_vec_sub(&tvec, p0, p1);
3302                 if (fl_abs(tvec.xyz.x) <= fl_abs(tvec.xyz.z)){
3303                         tvec.xyz.x = -tvec.xyz.z;
3304                 } else {
3305                         tvec.xyz.y = -tvec.xyz.x;
3306                 }
3307         }
3308
3309         vm_vec_normalize(&tvec);
3310         vm_vec_scale(&tvec, radius);
3311         vm_vec_add(&new_pnt, centerp, &tvec);
3312
3313         add_path_point(&new_pnt, -1, -1, -1);
3314 }
3315                         
3316 //      Create a path from the current position to a goal position.
3317 //      The current position is in the current object and the goal position is
3318 //      in the goal object.
3319 //      It is ok to intersect the current object, but not the goal object.
3320 //      This function is useful for creating a path to an initial point near a large
3321 //      object.
3322 //
3323 // input:       subsys_path:    optional param (default 0), indicates this is a path to a subsystem
3324 void create_path_to_point(vector *curpos, vector *goalpos, object *curobjp, object *goalobjp, int subsys_path)
3325 {
3326         //      If can't cast vector to goalpos, then create an intermediate point.
3327         if (pp_collide(curpos, goalpos, goalobjp, curobjp->radius)) {
3328                 vector  tan1;
3329                 float           radius;
3330
3331                 // If this is a path to a subsystem, use SUBSYS_PATH_DIST as the radius for the object you are
3332                 // trying to avoid.  This is needed since subsystem paths extend out to SUBSYS_PATH_DIST, and we
3333                 // want ships to reach their path destination without flying to points that sit on the radius of
3334                 // a small ship
3335                 radius = goalobjp->radius;
3336                 if (subsys_path) {
3337                         if ( SUBSYS_PATH_DIST > goalobjp->radius ) {
3338                                 radius = SUBSYS_PATH_DIST;
3339                         }
3340                 }
3341
3342                 //      The intermediate point is at the intersection of:
3343                 //              tangent to *goalobjp sphere at point *goalpos
3344                 //              tangent to *goalobjp sphere through point *curpos in plane defined by *curpos, *goalpos, goalobjp->pos
3345                 //      Note, there are two tangents through *curpos, unless *curpos is on the
3346                 //      sphere.  The tangent that causes the nearer intersection (to *goalpos) is chosen.
3347                 get_tangent_point(&tan1, curpos, &goalobjp->pos, goalpos, radius);
3348
3349                 //      If we can't reach tan1 from curpos, insert a new point.
3350                 if (pp_collide(&tan1, curpos, goalobjp, curobjp->radius))
3351                         bisect_chord(curpos, &tan1, &goalobjp->pos, radius);
3352
3353                 add_path_point(&tan1, -1, -1, -1);
3354
3355                 //      If we can't reach goalpos from tan1, insert a new point.
3356                 if (pp_collide(goalpos, &tan1, goalobjp, curobjp->radius))
3357                         bisect_chord(goalpos, &tan1, &goalobjp->pos, radius);
3358         }
3359
3360 }
3361
3362 //      Given an object and a model path, globalize the points on the model
3363 //      and copy into the global path list.
3364 //      If pnp != NULL, then modify, in place, the path points.  This is used to create new
3365 //      globalized points when the base object has moved.
3366 // input:       randomize_pnt   => optional parameter (default value -1), add random vector in sphere to this path point
3367 void copy_xlate_model_path_points(object *objp, model_path *mp, int dir, int count, int path_num, pnode *pnp, int randomize_pnt)
3368 {
3369         matrix  m;
3370         int             i;
3371         vector  v1;
3372         int             pp_index;               //      index in Path_points at which to store point, if this is a modify-in-place (pnp ! NULL)
3373         int             start_index, finish_index;
3374         
3375         // nprintf(("AI", "Creating path for object %s in frame #%i\n", Ships[objp->instance].ship_name, AI_FrameCount));
3376         
3377         //      Initialize pp_index.
3378         //      If pnp == NULL, that means we're creating new points.  If not NULL, then modify in place.
3379         if (pnp == NULL)
3380                 pp_index = -1;                  //      This tells add_path_point to create a new point.
3381         else
3382                 pp_index = 0;                   //      pp_index will get assigned to index in Path_points to reuse.
3383
3384         vm_copy_transpose_matrix(&m, &objp->orient);
3385
3386         if (dir == 1) {
3387                 start_index = 0;
3388                 finish_index = min(count, mp->nverts);
3389         } else {
3390                 SDL_assert(dir == -1);  //      direction must be up by 1 or down by 1 and it's neither!
3391                 start_index = mp->nverts-1;
3392                 finish_index = max(-1, mp->nverts-1-count);
3393         }
3394
3395         int offset = 0;
3396         for (i=start_index; i != finish_index; i += dir) {
3397                 //      Globalize the point.
3398                 vm_vec_rotate(&v1, &mp->verts[i].pos, &m);
3399                 vm_vec_add2(&v1, &objp->pos);
3400
3401                 if ( randomize_pnt == i ) {
3402                         vector v_rand;
3403                         static_randvec(OBJ_INDEX(objp), &v_rand);
3404                         vm_vec_scale(&v_rand, 30.0f);
3405                         vm_vec_add2(&v1, &v_rand);
3406                 }
3407
3408                 if (pp_index != -1)
3409                         pp_index = pnp-Path_points + offset;
3410
3411                 add_path_point(&v1, path_num, i, pp_index);
3412                 offset++;
3413         }
3414 }
3415
3416
3417 //      For pl_objp, create a path along path path_num into mobjp.
3418 //      The tricky part of this problem is creating the entry to the first point on the
3419 //      predefined path.  The points on this entry path are based on the location of Pl_objp
3420 //      relative to the start of the path.
3421 //
3422 // input:
3423 //                              subsys_path:    optional param (default 0), indicating this is a path to a subsystem
3424 void create_model_path(object *pl_objp, object *mobjp, int path_num, int subsys_path)
3425 {       
3426         ship                    *shipp = &Ships[pl_objp->instance];
3427         ai_info         *aip = &Ai_info[shipp->ai_index];
3428
3429         ship_info       *osip = &Ship_info[Ships[mobjp->instance].ship_info_index];
3430         polymodel       *pm = model_get(osip->modelnum);
3431         int                     num_points;
3432         model_path      *mp;
3433         pnode                   *ppfp_start = Ppfp;
3434         matrix          m;
3435         vector          gp0;
3436
3437         SDL_assert(path_num >= 0);
3438
3439         //      Do garbage collection if necessary.
3440         if (Ppfp-Path_points + 64 > MAX_PATH_POINTS) {
3441                 garbage_collect_path_points();
3442                 ppfp_start = Ppfp;
3443         }
3444
3445         aip->path_start = Ppfp - Path_points;
3446         SDL_assert(path_num < pm->n_paths);
3447         
3448         mp = &pm->paths[path_num];
3449         num_points = mp->nverts;
3450
3451         SDL_assert(Ppfp-Path_points + num_points + 4 < MAX_PATH_POINTS);
3452
3453         vm_copy_transpose_matrix(&m, &mobjp->orient);
3454         vm_vec_rotate(&gp0, &mp->verts[0].pos, &m);
3455         vm_vec_add2(&gp0, &mobjp->pos);
3456
3457         if (pp_collide(&pl_objp->pos, &gp0, mobjp, pl_objp->radius)) {
3458                 vector  perim_point1;
3459                 vector  perim_point2;
3460
3461                 perim_point2 = pl_objp->pos;
3462                 
3463                 //      If object that wants to dock is inside bounding sphere of object it wants to dock with, make it fly out.
3464                 //      Assume it can fly "straight" out to the bounding sphere.
3465                 if (vm_vec_dist_quick(&pl_objp->pos, &mobjp->pos) < mobjp->radius) {
3466                         project_point_to_perimeter(&perim_point2, &mobjp->pos, mobjp->radius, &pl_objp->pos);
3467                         add_path_point(&perim_point2, path_num, -1, -1);
3468                 }
3469
3470                 //      If last point on pre-defined path is inside bounding sphere, create a new point on the surface of the sphere.
3471                 if (vm_vec_dist_quick(&mobjp->pos, &gp0) < mobjp->radius) {
3472                         project_point_to_perimeter(&perim_point1, &mobjp->pos, mobjp->radius, &gp0);
3473                         create_path_to_point(&perim_point2, &perim_point1, pl_objp, mobjp, subsys_path);
3474                         add_path_point(&perim_point1, path_num, -1, -1);
3475                 } else {                //      The predefined path extends outside the sphere.  Create path to that point.
3476                         create_path_to_point(&perim_point2, &gp0, pl_objp, mobjp, subsys_path);
3477                 }
3478         }
3479
3480         // AL 12-31-97: If following a subsystem path, add random vector to second last path point
3481         if ( subsys_path ) {
3482                 copy_xlate_model_path_points(mobjp, mp, 1, mp->nverts, path_num, NULL, mp->nverts-2);
3483         } else {
3484                 copy_xlate_model_path_points(mobjp, mp, 1, mp->nverts, path_num, NULL);
3485         }
3486
3487         aip->path_cur = aip->path_start;
3488         aip->path_dir = PD_FORWARD;
3489         aip->path_objnum = mobjp-Objects;
3490         aip->mp_index = path_num;
3491         aip->path_length = Ppfp - ppfp_start;
3492         aip->path_next_check_time = timestamp(1);
3493
3494         aip->path_goal_obj_hash = create_object_hash(&Objects[aip->path_objnum]);
3495
3496         aip->path_next_create_time = timestamp(1000);   //      OK to try to create one second later
3497         aip->path_create_pos = pl_objp->pos;
3498         aip->path_create_orient = pl_objp->orient;
3499
3500         aip->ai_flags &= ~AIF_USE_EXIT_PATH;                    // ensure this flag is cleared
3501 }
3502
3503 //      For pl_objp, create a path along path path_num into mobjp.
3504 //      The tricky part of this problem is creating the entry to the first point on the
3505 //      predefined path.  The points on this entry path are based on the location of pl_objp
3506 //      relative to the start of the path.
3507 void create_model_exit_path(object *pl_objp, object *mobjp, int path_num, int count)
3508 {       
3509         ship                    *shipp = &Ships[pl_objp->instance];
3510         ai_info         *aip = &Ai_info[shipp->ai_index];
3511
3512         ship_info       *osip = &Ship_info[Ships[mobjp->instance].ship_info_index];
3513         polymodel       *pm = model_get(osip->modelnum);
3514         int                     num_points;
3515         model_path      *mp;
3516         pnode                   *ppfp_start = Ppfp;
3517
3518         aip->path_start = Ppfp - Path_points;
3519         SDL_assert(path_num < pm->n_paths);
3520         
3521         mp = &pm->paths[path_num];
3522         num_points = mp->nverts;
3523
3524         SDL_assert(Ppfp-Path_points + num_points + 4 < MAX_PATH_POINTS);
3525
3526         copy_xlate_model_path_points(mobjp, mp, -1, count, path_num, NULL);
3527
3528         aip->path_cur = aip->path_start;
3529         aip->path_dir = PD_FORWARD;
3530         aip->path_objnum = mobjp-Objects;
3531         aip->mp_index = path_num;
3532         aip->path_length = Ppfp - ppfp_start;
3533         aip->path_next_check_time = timestamp(1);
3534
3535         aip->ai_flags |= AIF_USE_EXIT_PATH;             // mark as exit path, referenced in maybe
3536 }
3537
3538 //      Return true if the vector from curpos to goalpos intersects with any ship other than the ignore objects.
3539 //      Calls pp_collide
3540 int pp_collide_any(vector *curpos, vector *goalpos, float radius, object *ignore_objp1, object *ignore_objp2, int big_only_flag)
3541 {
3542         ship_obj        *so;    
3543
3544         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
3545                 object *objp = &Objects[so->objnum];
3546
3547                 if (big_only_flag) {
3548                         if (!(Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)))
3549                                 continue;
3550                 }
3551
3552                 if ((objp != ignore_objp1) && (objp != ignore_objp2)) {
3553                         if (pp_collide(curpos, goalpos, objp, radius))
3554                                 return OBJ_INDEX(objp);
3555                 }
3556         }
3557
3558         return -1;
3559 }
3560
3561 //      Used to create docking paths and other pre-defined paths through ships.
3562 //      Creates a path in absolute space.
3563 //      Create a path into the object objnum.
3564 //
3565 // input:
3566 //      pl_objp:                        object that will use the path
3567 //      objnum:                 Object to find path to.
3568 //      path_num:               model path index to use
3569 //      exit_flag:              true means this is an exit path in the model
3570 // subsys_path: optional param (default 0) that indicates this is a path to a subsystem
3571 //      Exit:
3572 //      ai_info struct in Pl_objp gets stuffed with information to enable Pl_objp to fly the path.
3573 void ai_find_path(object *pl_objp, int objnum, int path_num, int exit_flag, int subsys_path)
3574 {
3575         ai_info *aip = &Ai_info[Ships[pl_objp->instance].ai_index];
3576
3577         SDL_assert(path_num >= 0);
3578
3579         //      This is test code, find an object with paths.
3580         if (objnum != -1) {
3581                 object  *objp = &Objects[objnum];
3582
3583                 if (objp->type == OBJ_SHIP) {
3584                         polymodel *pm;
3585
3586                         ship    *shipp = &Ships[objp->instance];
3587                         pm = model_get( shipp->modelnum );
3588                         SDL_assert(pm->n_paths > path_num);
3589                         aip->goal_objnum = objp-Objects;
3590                         aip->goal_signature = objp->signature;
3591                         if (exit_flag)
3592                                 create_model_exit_path(pl_objp, objp, path_num);
3593                         else
3594                                 create_model_path(pl_objp, objp, path_num, subsys_path);
3595                         return;
3596                 }
3597
3598         }
3599 }
3600
3601 extern int vector_object_collision(vector *start_pos, vector *end_pos, object *objp, float radius_scale);
3602
3603 //      Maybe make *objp avoid a player object.
3604 //      For now, 4/6/98, only check Player_obj.
3605 //      If player collision would occur, set AIF_AVOIDING_SMALL_SHIP bit in ai_flags.
3606 //      Set aip->avoid_goal_point
3607 int maybe_avoid_player(object *objp, vector *goal_pos)
3608 {
3609         ai_info *aip;
3610         vector  cur_pos, new_goal_pos;
3611         object  *player_objp;
3612         vector  n_vec_to_goal, n_vec_to_player;
3613
3614         aip = &Ai_info[Ships[objp->instance].ai_index];
3615
3616         if (!timestamp_elapsed(aip->avoid_check_timestamp))
3617                 return 0;
3618
3619         player_objp = Player_obj;
3620
3621         float   speed_time;
3622
3623         //      How far two ships could be apart and still collide within one second.
3624         speed_time = player_objp->phys_info.speed + objp->phys_info.speed;
3625
3626         float   obj_obj_dist;
3627
3628         obj_obj_dist = vm_vec_dist_quick(&player_objp->pos, &objp->pos);
3629
3630         if (obj_obj_dist > speed_time*2.0f)
3631                 return 0;
3632
3633         cur_pos = objp->pos;
3634
3635         new_goal_pos = *goal_pos;
3636
3637         float dist = vm_vec_normalized_dir(&n_vec_to_goal, goal_pos, &objp->pos);
3638         vm_vec_normalized_dir(&n_vec_to_player, &player_objp->pos, &objp->pos);
3639
3640         if (dist > speed_time*2.0f) {
3641                 vm_vec_scale_add(&new_goal_pos, &objp->pos, &n_vec_to_goal, 200.0f);
3642         }
3643
3644         if (vector_object_collision(&objp->pos, &new_goal_pos, player_objp, 1.5f)) {
3645                 aip->ai_flags |= AIF_AVOIDING_SMALL_SHIP;
3646
3647                 vector  avoid_vec;
3648
3649                 vm_vec_sub(&avoid_vec, &n_vec_to_goal, &n_vec_to_player);
3650                 if (vm_vec_mag_quick(&avoid_vec) < 0.01f) {
3651                         vm_vec_copy_scale(&avoid_vec, &objp->orient.v.rvec, frand()-0.5f);
3652                         vm_vec_scale_add2(&avoid_vec, &objp->orient.v.uvec, frand()-0.5f);
3653                         vm_vec_normalize(&avoid_vec);
3654                 } else {
3655                         vector  tvec1;
3656                         vm_vec_normalize(&avoid_vec);
3657                         vm_vec_crossprod(&tvec1, &n_vec_to_goal, &avoid_vec);
3658                         vm_vec_crossprod(&avoid_vec, &tvec1, &n_vec_to_player);
3659                 }
3660
3661                 //      Now, avoid_vec is a vector perpendicular to the vector to the player and the direction *objp
3662                 //      should fly in to avoid the player while still approaching its goal.
3663                 vm_vec_scale_add(&aip->avoid_goal_point, &player_objp->pos, &avoid_vec, 400.0f);
3664
3665                 aip->avoid_check_timestamp = timestamp(1000);
3666
3667                 return 1;
3668         } else {
3669                 aip->ai_flags &= ~AIF_AVOIDING_SMALL_SHIP;
3670                 aip->avoid_check_timestamp = timestamp((int) (obj_obj_dist/200.0f) + 500);
3671
3672                 return 0;
3673         }
3674 }
3675
3676 //      Make object *still_objp enter AIM_STILL mode.
3677 //      Make it point at view_pos.
3678 void ai_stay_still(object *still_objp, vector *view_pos)
3679 {
3680         ship    *shipp;
3681         ai_info *aip;
3682
3683         SDL_assert(still_objp->type == OBJ_SHIP);
3684         SDL_assert((still_objp->instance >= 0) && (still_objp->instance < MAX_OBJECTS));
3685
3686         shipp = &Ships[still_objp->instance];
3687         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
3688
3689         aip = &Ai_info[shipp->ai_index];
3690
3691         aip->mode = AIM_STILL;
3692
3693         //      If view_pos not NULL, point at that point.  Else, point at a point directly in front of ship.  Ie, don't turn.
3694         if (view_pos != NULL)
3695                 aip->goal_point = *view_pos;
3696         else
3697                 vm_vec_scale_add(&aip->goal_point, &still_objp->pos, &still_objp->orient.v.fvec, 100.0f);
3698 }
3699
3700 // code which is called from ai_dock_with_object and ai_dock to set flags and apprioriate variable
3701 // when two objects have completed docking.  used because we can dock object initially at misison load
3702 // time (meaning that ai_dock() might never get called).  docker has docked with dockee (i.e. docker
3703 // would be a freighter and dockee would be a cargo).
3704 void ai_do_objects_docked_stuff(object *docker, object *dockee)
3705 {
3706         ai_info *aip, *other_aip;
3707
3708         aip = &Ai_info[Ships[docker->instance].ai_index];
3709         other_aip = &Ai_info[Ships[dockee->instance].ai_index];
3710
3711         // set the flags and dock_objnum for both objects
3712         aip->ai_flags |= AIF_DOCKED;
3713         aip->dock_objnum = OBJ_INDEX(dockee);
3714         other_aip->ai_flags |= AIF_DOCKED;
3715         other_aip->dock_objnum = OBJ_INDEX(docker);
3716         aip->dock_signature = dockee->signature;
3717         other_aip->dock_signature = docker->signature;
3718
3719         // add multiplayer hook here to deal with docked objects.  We need to only send information
3720         // about the object that is docking.  Both flags will get updated.
3721         if ( MULTIPLAYER_MASTER )
3722                 send_ai_info_update_packet( docker, AI_UPDATE_DOCK );
3723
3724 }
3725
3726 // code which is called when objects become undocked. Equivalent of above function.
3727 // dockee might not be valid since this code can get called to cleanup after a ship
3728 // has blown up!
3729 void ai_do_objects_undocked_stuff( object *docker, object *dockee )
3730 {
3731         ai_info *aip, *other_aip;
3732
3733         // add multiplayer hook here to deal with undocked objects.  Do it before we
3734         // do anything else.  We don't need to send info for both objects, since we can find
3735         // it be dock_objnum
3736         if ( MULTIPLAYER_MASTER )
3737                 send_ai_info_update_packet( docker, AI_UPDATE_UNDOCK );
3738
3739         aip = &Ai_info[Ships[docker->instance].ai_index];
3740
3741         // set the flags and dock_objnum for both objects
3742         aip->ai_flags &= ~(AIF_DOCKED | AIF_BEING_REPAIRED);
3743         aip->dock_objnum = -1;
3744         
3745         if ( dockee != NULL ) {
3746                 other_aip = &Ai_info[Ships[dockee->instance].ai_index];
3747                 other_aip->ai_flags &= ~(AIF_DOCKED | AIF_BEING_REPAIRED);
3748                 other_aip->dock_objnum = -1;
3749         }
3750
3751 }
3752
3753
3754 //      --------------------------------------------------------------------------
3755 //      Interface from goals code to AI.
3756 //      Cause *docker to dock with *dockee.
3757 //      priority is priority of goal from goals code.
3758 //      dock_type is:
3759 //              AIDO_DOCK               set goal of docking
3760 //              AIDO_DOCK_NOW   immediately dock, used for ships that need to be docked at mission start
3761 //              AIDO_UNDOCK             set goal of undocking
3762 void ai_dock_with_object(object *docker, object *dockee, int priority, int dock_type, int docker_index, int dockee_index)
3763 {
3764         ai_info         *aip;
3765         polymodel       *pm;
3766         ai_info         *dockee_aip;
3767
3768         SDL_assert(docker != NULL);
3769         SDL_assert(dockee != NULL);
3770         SDL_assert(docker->instance != -1);
3771         SDL_assert(Ships[docker->instance].ai_index != -1);
3772         SDL_assert(Ships[dockee->instance].ai_index != -1);
3773         SDL_assert( docker_index != -1 );
3774         SDL_assert( dockee_index != -1 );
3775
3776         aip = &Ai_info[Ships[docker->instance].ai_index];
3777
3778         if ((aip->ai_flags & AIF_DOCKED) && (dock_type == AIDO_DOCK)) {
3779         //      object  *dockee2;
3780         //      int             docker_index2, dockee_index2;
3781
3782                 SDL_assert(aip->dock_objnum > -1);
3783         //      dockee2 = &Objects[aip->dock_objnum];
3784         //      docker_index2 = aip->dock_index;
3785         //      dockee_index2 = aip->dockee_index;
3786                 // MWA -- 2/9/98.  use the goal code to undock the ships since goals might need to get removed
3787                 // and that code will do it properly.  I'd actually be surprised if we got into this code anymore
3788                 // since the outer layer goal code should deal with this issue....but who knows...
3789                 ai_add_goal_ship_internal( aip, AI_GOAL_UNDOCK, NULL, -1, -1, 0 );
3790
3791                 // old code below
3792                 //ai_dock_with_object(docker, dockee2, priority, AIDO_UNDOCK, docker_index2, dockee_index2);
3793                 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));
3794                 nprintf(("AI", "...so ship %s will now undock.\n", Ships[docker->instance].ship_name));
3795                 return;
3796         }
3797
3798         dockee_aip = &Ai_info[Ships[dockee->instance].ai_index];
3799
3800         aip->goal_objnum = dockee - Objects;
3801         aip->goal_signature = dockee->signature;
3802
3803         aip->mode = AIM_DOCK;
3804
3805         switch (dock_type) {
3806         case AIDO_DOCK:
3807                 aip->submode = AIS_DOCK_0;
3808                 break;
3809         case AIDO_DOCK_NOW:
3810                 aip->submode = AIS_DOCK_3A;
3811                 break;
3812         case AIDO_UNDOCK:
3813                 aip->submode = AIS_UNDOCK_0;
3814                 break;
3815         default:
3816                 Int3();         //      Bogus dock_type.
3817         }
3818
3819         aip->submode_start_time = Missiontime;
3820         aip->dock_index = docker_index;
3821         aip->dockee_index = dockee_index;
3822
3823         dockee_aip->dock_index = dockee_index;
3824         dockee_aip->dockee_index = docker_index;
3825
3826         // get the path number to the docking point on the dockee.  Each docking point contains a list
3827         // of paths that the point can be reached by.  Pick the first path in the path list for now.
3828         // We only want to do this stuff if we are docking!!!  Be sure to set the path index
3829         if ((dock_type == AIDO_DOCK) || (dock_type == AIDO_DOCK_NOW)) {
3830                 pm = model_get( Ships[dockee->instance].modelnum );
3831                 SDL_assert( pm->docking_bays[dockee_index].num_spline_paths > 0 );
3832
3833                 // only set the dock path index if we are docking.  undocking will assume that dock_path_index
3834                 // already set from some other docking command
3835                 aip->dock_path_index = dockee_index;
3836                 dockee_aip->dock_path_index = docker_index;
3837         }
3838
3839         if (dock_type != AIDO_DOCK_NOW) {
3840                 int path_num;
3841                 //      Note: Second parameter is dock path index.  This should be specified as an
3842                 //      _input_ to this function and passed through.  The path index should be already
3843                 // set for the undock function
3844                 path_num = ai_return_path_num_from_dockbay(dockee, dockee_index);
3845                 ai_find_path(docker, dockee-Objects, path_num, 0);
3846 //              ai_find_path(dockee-Objects, dockee_index, 0);
3847         } else {
3848                 dock_orient_and_approach(docker, dockee, DOA_DOCK_STAY);
3849                 //aip->dock_objnum = OBJ_INDEX(dockee);
3850                 ai_do_objects_docked_stuff( docker, dockee );
3851         }
3852
3853 }
3854
3855 //      Cause a ship to fly its waypoints.
3856 //      flags tells:
3857 //              WPF_REPEAT      Set -> repeat waypoints.
3858 void ai_start_waypoints(object *objp, int waypoint_list_index, int wp_flags)
3859 {
3860         ai_info *aip;
3861
3862         SDL_assert(waypoint_list_index < Num_waypoint_lists);
3863
3864         //nprintf(("AI", "Frame %i: Ship %s instructed to fly waypoint list #%i\n", AI_FrameCount, Ships[objp->instance].ship_name, waypoint_list_index));
3865         aip = &Ai_info[Ships[objp->instance].ai_index];
3866
3867         if ( (aip->mode == AIM_WAYPOINTS) && (aip->wp_index == waypoint_list_index) )
3868                 return;
3869
3870         aip->ai_flags |= AIF_FORMATION_WING;
3871         aip->ai_flags &= ~AIF_FORMATION_OBJECT;
3872         aip->wp_list = waypoint_list_index;
3873         aip->wp_index = 0;
3874         aip->wp_flags = wp_flags;
3875         aip->mode = AIM_WAYPOINTS;
3876
3877         SDL_assert(aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC);
3878 }
3879
3880 //      Make *objp stay within dist units of *other_objp
3881 void ai_do_stay_near(object *objp, object *other_objp, float dist)
3882 {
3883         ai_info *aip;
3884
3885         SDL_assert(objp != other_objp);         //      Bogus!  Told to stay near self.
3886         SDL_assert(objp->type == OBJ_SHIP);
3887         SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
3888
3889         aip = &Ai_info[Ships[objp->instance].ai_index];
3890
3891         aip->mode = AIM_STAY_NEAR;
3892         aip->submode = -1;
3893         aip->stay_near_distance = dist;
3894         aip->goal_objnum = other_objp-Objects;
3895         aip->goal_signature = other_objp->signature;
3896
3897 }
3898
3899 //      Make object *objp form on wing of object *goal_objp
3900 void ai_form_on_wing(object *objp, object *goal_objp)
3901 {
3902         ai_info *aip;
3903         ship                    *shipp;
3904         ship_info       *sip;
3905
3906         // objp == goal_objp sometimes in multiplayer when someone leaves a game -- make a simple
3907         // out for this case.
3908         if ( Game_mode & GM_MULTIPLAYER ) {
3909                 if ( objp == goal_objp ) {
3910                         return;
3911                 }
3912         }
3913
3914         SDL_assert(objp != goal_objp);          //      Bogus!  Told to form on own's wing!
3915
3916         shipp = &Ships[objp->instance];
3917         sip = &Ship_info[shipp->ship_info_index];
3918
3919         //      Only fighters or bombers allowed to form on wing.
3920         if (!(sip->flags & (SIF_FIGHTER | SIF_BOMBER))) {
3921                 nprintf(("AI", "Warning: Ship %s tried to form on player's wing, but not fighter or bomber.\n", shipp->ship_name));
3922                 return;
3923         }
3924
3925         aip = &Ai_info[Ships[objp->instance].ai_index];
3926
3927         aip->ai_flags &= ~AIF_FORMATION_WING;
3928         aip->ai_flags |= AIF_FORMATION_OBJECT;
3929
3930         aip->goal_objnum = goal_objp-Objects;
3931         ai_set_goal_maybe_abort_dock(objp, aip);
3932         aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME*4);           //      Super extra long time until can target another ship.
3933
3934 }
3935
3936 //      Given an object and an object on whose wing to form, return slot to use.
3937 //      Optimize:
3938 //              This function is called per object in formation per frame.  Should store slot in ai_info struct.
3939 int ai_formation_object_get_slotnum(int objnum, object *objp)
3940 {
3941         int     slotnum = 1;                    //      Note: Slot #0 means leader, which isn't someone who was told to form-on-wing.
3942         object *o;
3943
3944         for ( o = GET_FIRST(&obj_used_list); o != END_OF_LIST(&obj_used_list); o = GET_NEXT(o) ) {
3945                 if (objp == o)
3946                         break;
3947                 else if (o->type == OBJ_SHIP)
3948                         if (Ai_info[Ships[o->instance].ai_index].ai_flags & AIF_FORMATION_OBJECT)
3949                                 if (Ai_info[Ships[o->instance].ai_index].goal_objnum == objnum)
3950                                         slotnum++;
3951         }
3952
3953         SDL_assert(o != END_OF_LIST(&obj_used_list));   //      Didn't find objp in list of used ships.  Impossible!
3954
3955         return slotnum;
3956 }
3957
3958 #define BIGNUM  100000.0f
3959
3960 int Debug_k = 0;
3961
3962 //      Given an attacker's position and a target's position and velocity, compute the time of
3963 //      intersection of a weapon fired by the attacker with speed weapon_speed.
3964 //      Return this value.  Return value of 0.0f means no collision is possible.
3965 float compute_collision_time(vector *targpos, vector *targvel, vector *attackpos, float weapon_speed)
3966 {
3967         vector  vec_to_target;
3968         float           pos_dot_vel;
3969         float           vel_sqr;
3970         float           discrim;
3971
3972         vm_vec_sub(&vec_to_target, targpos, attackpos);
3973         pos_dot_vel = vm_vec_dot(&vec_to_target, targvel);
3974         vel_sqr = vm_vec_dot(targvel, targvel) - weapon_speed*weapon_speed;
3975         discrim = pos_dot_vel*pos_dot_vel - vel_sqr*vm_vec_dot(&vec_to_target, &vec_to_target);
3976
3977         if (discrim > 0.0f) {
3978                 float   t1, t2, t_solve;
3979
3980                 t1 = (-pos_dot_vel + fl_sqrt(discrim)) / vel_sqr;
3981                 t2 = (-pos_dot_vel - fl_sqrt(discrim)) / vel_sqr;
3982
3983                 t_solve = BIGNUM;
3984
3985                 if (t1 > 0.0f)
3986                         t_solve = t1;
3987                 if ((t2 > 0.0f) && (t2 < t_solve))
3988                         t_solve = t2;
3989
3990                 if (t_solve < BIGNUM-1.0f) {
3991                         return t_solve + Debug_k * flFrametime;
3992                 }
3993         }
3994
3995         return 0.0f;
3996 }
3997
3998
3999 //      --------------------------------------------------------------------------
4000 //      If far away, use player's speed.
4001 //      If in between, lerp between player and laser speed
4002 //      If close, use laser speed.
4003 // Want to know how much time it will take to get to the enemy.
4004 // This function doesn't account for the fact that by the time the player
4005 // (or his laser) gets to the current enemy position, the enemy will have moved.
4006 // This is dealt with in polish_predicted_enemy_pos.
4007 float compute_time_to_enemy(float dist_to_enemy, object *pobjp, object *eobjp)
4008 {
4009         float   time_to_enemy;
4010         float   pl_speed = pobjp->phys_info.speed;
4011         float   max_laser_distance, max_laser_speed;
4012         int     bank_num, weapon_num;
4013         ship    *shipp = &Ships[pobjp->instance];
4014
4015         bank_num = shipp->weapons.current_primary_bank;
4016         weapon_num = shipp->weapons.primary_bank_weapons[bank_num];
4017         max_laser_speed = Weapon_info[weapon_num].max_speed;
4018         max_laser_distance = max_laser_speed * Weapon_info[weapon_num].lifetime;
4019
4020         //      If pretty far away, use player's speed to predict position, else
4021         //      use laser's speed because when close, we care more about hitting
4022         //      with a laser than about causing ship:ship rendezvous.
4023         if (dist_to_enemy > 1.5 * max_laser_distance) {
4024                 if (pl_speed > 0.0f)
4025                         time_to_enemy = dist_to_enemy/pl_speed;
4026                 else
4027                         time_to_enemy = 1.0f;
4028         } else if (dist_to_enemy > 1.1*max_laser_distance) {
4029                 if (pl_speed > 0.1f) {
4030                         float   scale;
4031
4032                         scale = (float) ((dist_to_enemy - max_laser_distance) / max_laser_distance);
4033                 
4034                         time_to_enemy = (float) (dist_to_enemy/(pl_speed * scale + max_laser_speed * (1.0f - scale)));
4035                 } else
4036                         time_to_enemy = 2.0f;
4037         } else
4038                 time_to_enemy = (float) (dist_to_enemy/max_laser_speed);
4039
4040         // return time_to_enemy * (1.0f + Ai_info[Ships[pobjp->instance].ai_index].lead_scale);
4041         return time_to_enemy + flFrametime;
4042 }
4043
4044 //      Stuff *dot and *tts.
4045 //      *dot is always computed.  If dot is less than zero, the magnitude is
4046 //      incorrect, not having been divided by distance.
4047 //      If *dot is > 0.0f, then tts is computed.  This is the time it will take object
4048 //      *objp to get to *pos, assuming it moves right at it.
4049 void fds_aux(float *dot, float *tts, vector *pos, float dtime, object *objp)
4050 {
4051         vector  v2s;
4052
4053         vm_vec_sub(&v2s, pos, &objp->pos);
4054         *dot = vm_vec_dot(&v2s, &objp->orient.v.fvec);
4055
4056         if (*dot > 0.0f) {
4057                 float   dist;
4058
4059                 dist = vm_vec_dist(&objp->pos, pos);
4060
4061                 if (dist > 0.1f)
4062                         *dot /= dist;
4063                 else
4064                         *dot = 1.0f;
4065
4066                 if (objp->phys_info.speed > 0.1f)
4067                         *tts = dist / objp->phys_info.speed;
4068                 else
4069                         *tts = dist * 100.0f;
4070         }
4071 }
4072
4073 /*
4074 //      Return index of weapon that could hit object *sobjp within dtime seconds.
4075 //      Actual time until impact returned in *atime.
4076 int find_danger_weapon(object *sobjp, float dtime, float *atime, float dot_threshhold)
4077 {
4078         object  *objp, *best_objp = NULL;
4079         float           best_tts = 1000.0f;
4080
4081         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
4082                 if ((objp->type == OBJ_WEAPON) && (sobjp-Objects != objp->parent)) {
4083                         float           dot, tts;
4084                         // vector       psp;            //      Predicted ship position.
4085
4086                         //      Get dot and time to current ship position.
4087                         fds_aux(&dot, &tts, &sobjp->pos, dtime, objp);
4088
4089                         //      If dot and tts are in plausible range, do more expensive stuff.
4090                         if (dot > 0.98f) {
4091 //                              float   dot_from_sobjp;
4092                                 vector  v2e;
4093
4094                                 vm_vec_normalized_dir(&v2e, &objp->pos, &sobjp->pos);
4095 //                              dot_from_sobjp = vm_vec_dot(&sobjp->orient.v.fvec, &v2e);
4096 //                              if (dot_from_sobjp >= dot_threshhold)
4097                                         if (tts < dtime) {
4098                                                 if (tts < best_tts) {
4099                                                         best_tts = tts;
4100                                                         best_objp = objp;
4101                                                 }
4102                                         }
4103                         }
4104                 }
4105         }
4106
4107         *atime = best_tts;
4108
4109         if (best_objp != NULL)
4110                 return best_objp-Objects;
4111         else
4112                 return -1;
4113 }
4114 */
4115
4116 //      --------------------------------------------------------------------------
4117 void ai_set_positions(object *pl_objp, object *en_objp, ai_info *aip, vector *player_pos, vector *enemy_pos)
4118 {
4119         *player_pos = pl_objp->pos;
4120
4121         if (aip->next_predict_pos_time > Missiontime) {
4122                 *enemy_pos = aip->last_predicted_enemy_pos;
4123         } else {
4124                 *enemy_pos = en_objp->pos;
4125
4126                 aip->next_predict_pos_time = Missiontime + Skill_level_delay[Game_skill_level];
4127                 aip->last_predicted_enemy_pos = *enemy_pos;
4128         }
4129
4130
4131 }
4132
4133 //      --------------------------------------------------------------------------
4134 int find_nearest_waypoint(object *objp)
4135 {
4136         int     i;
4137         float   dist, min_dist, dot;
4138         int     min_ind;
4139         int     wp_listnum;
4140         waypoint_list   *wpl;
4141
4142         wp_listnum = Ai_info[Ships[objp->instance].ai_index].wp_list;
4143         SDL_assert(wp_listnum > 0);
4144         wpl = &Waypoint_lists[wp_listnum];
4145
4146         min_dist = 999999.0f;
4147         min_ind = -1;
4148
4149         for (i=0; i<wpl->count; i++) {
4150                 dist = vm_vec_dist_quick(&objp->pos, &wpl->waypoints[i]);
4151                 dot = vm_vec_dot_to_point(&objp->orient.v.fvec, &objp->pos, &wpl->waypoints[i]);
4152                 dist = (float) (dist * (1.25 - dot));
4153                 if (dist < min_dist) {
4154                         min_dist = dist;
4155                         min_ind = i;
4156                 }
4157         }
4158
4159         SDL_assert(min_ind != -1);
4160
4161         return min_ind;
4162 }
4163
4164 //      Given an ai_info struct, by reading current goal and path information,
4165 //      extract base path information and return in pmp and pmpv.
4166 //      Return true if found, else return false.
4167 //      false means the current point is not on the original path.
4168 int get_base_path_info(int path_cur, int goal_objnum, model_path **pmp, mp_vert **pmpv)
4169 {
4170         pnode                   *pn = &Path_points[path_cur];
4171         ship_info       *sip = &Ship_info[Ships[Objects[goal_objnum].instance].ship_info_index];
4172         polymodel       *pm = model_get(sip->modelnum);
4173         //static        int     debug_last_index = -1;  // no longer used
4174         *pmpv = NULL;
4175         *pmp = NULL;
4176
4177         if (pn->path_num != -1) {
4178                 *pmp = &pm->paths[pn->path_num];
4179                 if (pn->path_index != -1)
4180                         *pmpv = &(*pmp)->verts[pn->path_index];
4181                 else
4182                         return 0;
4183         } else
4184                 return 0;
4185
4186 /*      if (debug_last_index != *pmpv-(*pmp)->verts) {
4187                 debug_last_index = *pmpv-(*pmp)->verts;
4188                 nprintf(("AI", "Point %i has %i turrets: ", *pmpv-(*pmp)->verts, (*pmpv)->nturrets));
4189                 for (int i=0; i<(*pmpv)->nturrets; i++) {
4190                         nprintf(("AI", "%i ", (*pmpv)->turret_ids[i]));
4191                 }
4192                 nprintf(("AI", "\n"));
4193         }
4194 */
4195         return 1;
4196 }
4197
4198 //      Modify, in place, the points in a global model path.
4199 //      Only modify those points that are defined in the model path.  Don't modify the
4200 //      leadin points, such as those that are necessary to get the model on the path.
4201 void modify_model_path_points(object *objp)
4202 {       
4203         ai_info         *aip = &Ai_info[Ships[objp->instance].ai_index];
4204         object          *mobjp = &Objects[aip->path_objnum];
4205         ship_info       *osip = &Ship_info[Ships[mobjp->instance].ship_info_index];
4206         polymodel       *pm = model_get(osip->modelnum);
4207         pnode                   *pnp;
4208         int                     path_num, dir;
4209
4210         SDL_assert((aip->path_start >= 0) && (aip->path_start < MAX_PATH_POINTS));
4211
4212         pnp = &Path_points[aip->path_start];
4213         while ((pnp->path_index == -1) && (pnp-Path_points - aip->path_start < aip->path_length))
4214                 pnp++;
4215
4216         path_num = pnp->path_num;
4217         SDL_assert((path_num >= 0) && (path_num < pm->n_paths));
4218         
4219         SDL_assert(pnp->path_index != -1);      //      If this is -1, that means we never found the model path points
4220
4221         dir = 1;
4222         if ( aip->ai_flags & AIF_USE_EXIT_PATH ) {
4223                 dir = -1;
4224         }
4225
4226         copy_xlate_model_path_points(mobjp, &pm->paths[path_num], dir, pm->paths[path_num].nverts, path_num, pnp);
4227 }
4228
4229 //      Return an indication of the distance between two matrices.
4230 //      This is the sum of the distances of their dot products from 1.0f.
4231 float ai_matrix_dist(matrix *mat1, matrix *mat2)
4232 {
4233         float   t;
4234
4235         t =  1.0f - vm_vec_dot(&mat1->v.fvec, &mat2->v.fvec);
4236         t += 1.0f - vm_vec_dot(&mat1->v.uvec, &mat2->v.uvec);
4237         t += 1.0f - vm_vec_dot(&mat1->v.rvec, &mat2->v.rvec);
4238
4239         return t;
4240 }
4241
4242
4243 //      Paths are created in absolute space, so a moving object needs to have model paths within it recreated.
4244 //      This uses the hash functions which means the slightest movement will cause a recreate, though the timestamp
4245 //      prevents this from happening too often.
4246 //      force_recreate_flag TRUE means to recreate regardless of timestamp.
4247 //      Returns TRUE if path recreated.
4248 float maybe_recreate_path(object *objp, ai_info *aip, int force_recreate_flag)
4249 {
4250         int     hashval;
4251
4252         SDL_assert(&Ai_info[Ships[objp->instance].ai_index] == aip);
4253
4254         if ((aip->mode == AIM_BAY_EMERGE) || (aip->mode == AIM_BAY_DEPART))
4255                 if ((OBJ_INDEX(objp) % 4) == (Framecount % 4))
4256                         force_recreate_flag = 1;
4257
4258         //      If no path, that means we don't need one.
4259         if (aip->path_start == -1)
4260                 return 0.0f;
4261
4262         // AL 11-12-97: If AIF_USE_STATIC_PATH is set, don't try to recreate.  This is needed when ships
4263         //                                  emerge from fighter bays.  We don't need to recreate the path.. and in case the 
4264         //              parent ship dies, we still want to be able to continue on the path
4265         if ( aip->ai_flags & AIF_USE_STATIC_PATH ) 
4266                 return 0.0f;
4267
4268         if (force_recreate_flag || timestamp_elapsed(aip->path_next_create_time)) {
4269                 object  *path_objp;
4270
4271                 path_objp = &Objects[aip->path_objnum];
4272
4273                 if ((hashval = create_object_hash(path_objp)) != aip->path_goal_obj_hash) {
4274                         float dist;
4275                         
4276                         dist = vm_vec_dist_quick(&path_objp->pos, &aip->path_create_pos);
4277                         dist += ai_matrix_dist(&path_objp->orient, &aip->path_create_orient) * 25.0f;
4278
4279                         if (force_recreate_flag || (dist > 2.0f)) {
4280                                 aip->path_next_create_time = timestamp(1000);   //      Update again in as little as 1000 milliseconds, ie 1 second.
4281                                 aip->path_goal_obj_hash = hashval;
4282                                 modify_model_path_points(objp);
4283
4284                                 aip->path_create_pos = path_objp->pos;
4285                                 aip->path_create_orient = path_objp->orient;
4286                                 
4287                                 return dist;
4288                         }
4289                 }
4290         }
4291
4292         return 0.0f;
4293 }
4294
4295 //      Set acceleration for ai_dock().
4296 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)
4297 {
4298         float prev_dot_to_goal = aip->prev_dot_to_goal;
4299         
4300         aip->prev_dot_to_goal = dot;
4301
4302         if (objp->phys_info.speed < 0.0f) {
4303                 accelerate_ship(aip, 1.0f/32.0f);
4304         } else if ((prev_dot_to_goal-dot) > 0.01) {
4305                 if (prev_dot_to_goal > dot + 0.05f) {
4306                         accelerate_ship(aip, 0.0f);
4307                 } else {
4308                         change_acceleration(aip, -1.0f);        //      -1.0f means subtract off flFrametime from acceleration value in 0.0..1.0
4309                 }
4310         } else {
4311                 if ((aip->mode == AIM_DOCK) && (dist_to_next < 150.0f) && (aip->path_start + aip->path_length - 2 == aip->path_cur)) {
4312                         set_accel_for_target_speed(objp, sip->max_speed * max(dist_to_next/500.0f, 1.0f));
4313                         //mprintf(("dist = %7.3f, speed = %7.3f\n", dist_to_next, objp->phys_info.speed));
4314                 } else if ((dot_to_next >= dot * .9) || (dist_to_next > 100.0f)) {
4315                         if (dist_to_goal > 200.0f)
4316                                 set_accel_for_target_speed(objp, sip->max_speed * (dot + 1.0f) / 2.0f);
4317                         else {
4318                                 float   xdot;
4319
4320                                 xdot = (dot_to_next + dot)/2.0f;
4321                                 if (xdot < 0.0f)
4322                                         xdot = 0.0f;
4323
4324                                 // AL: if following a path not in dock mode, move full speed
4325                                 if (( aip->mode != AIM_DOCK ) && (dot > 0.9f)) {
4326                                         set_accel_for_target_speed(objp, sip->max_speed*dot*dot*dot);
4327                                 } else {
4328                                         if ((aip->path_cur - aip->path_start < aip->path_length-2) && (dist_to_goal < 2*objp->radius)) {
4329                                                 //nprintf(("AI", "Target speed = %7.3f\n", dist_to_goal/8.0f));
4330                                                 set_accel_for_target_speed(objp, dist_to_goal/8.0f + 2.0f);
4331                                         } else {
4332                                                 set_accel_for_target_speed(objp, sip->max_speed * (2*xdot + 0.25f)/4.0f);
4333                                         }
4334                                 }
4335                         }
4336                 } else {
4337                         float   xdot;
4338
4339                         xdot = max(dot_to_next, 0.1f);
4340                         if ( aip->mode != AIM_DOCK ) {
4341                                 set_accel_for_target_speed(objp, sip->max_speed);
4342                         } else {
4343                                 float   speed;
4344                                 if ((aip->path_cur - aip->path_start < aip->path_length-2) && (dist_to_goal < 2*objp->radius)) {
4345                                         speed = dist_to_goal/8.0f + 2.0f;
4346                                 } else if (dist_to_goal < 4*objp->radius + 50.0f) {
4347                                         speed = dist_to_goal/4.0f + 4.0f;
4348                                 } else {
4349                                         speed = sip->max_speed * (3*xdot + 1.0f)/4.0f;
4350                                 }
4351                                 if (aip->mode == AIM_DOCK) {
4352                                         speed = speed * 2.0f + 1.0f;
4353                                         if (aip->goal_objnum != -1) {
4354                                                 speed += Objects[aip->goal_objnum].phys_info.speed;
4355                                         }
4356                                 }
4357
4358                                 set_accel_for_target_speed(objp, speed);
4359                         }
4360                 }
4361         }
4362 }
4363
4364 //      --------------------------------------------------------------------------
4365 //      Follow a path associated with a large object, such as a capital ship.
4366 //      The points defined on the path are in the object's reference frame.
4367 //      The object of interest is goal_objnum.
4368 //      The paths are defined in the model.  The path of interest is wp_list.
4369 //      The next goal point in the path is wp_index.
4370 //      wp_flags contain special information specific to the path.
4371
4372 // The path vertices are defined by model_path structs:
4373 //              typedef struct model_path {
4374 //                      char            name[MAX_NAME_LEN];                                     // name of the subsystem.  Probably displayed on HUD
4375 //                      int             nverts;
4376 //                      vector  *verts;
4377 //              } model_path;
4378
4379 //      The polymodel struct for the object contains the following:
4380 //              int                     n_paths;
4381 //              model_path      *paths;
4382
4383 //      Returns distance to goal point.
4384 float ai_path()
4385 {
4386         polymodel       *pm;
4387         int             num_paths, num_points;
4388         float           dot, dist_to_goal, dist_to_next, dot_to_next;
4389         ship            *shipp = &Ships[Pl_objp->instance];
4390         ship_info       *sip = &Ship_info[shipp->ship_info_index];
4391         ai_info *aip;
4392         vector  nvel_vec;
4393         float           mag;//, prev_dot_to_goal;
4394         vector  temp_vec, *slop_vec;
4395         object  *gobjp;
4396         ship            *gshipp;
4397         vector  *cvp, *nvp, next_vec, gcvp, gnvp;               //      current and next vertices in global coordinates.
4398
4399         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
4400
4401         SDL_assert(aip->goal_objnum != -1);
4402         SDL_assert(Objects[aip->goal_objnum].type == OBJ_SHIP);
4403
4404         gobjp = &Objects[aip->goal_objnum];
4405         gshipp = &Ships[gobjp->instance];
4406
4407         pm = model_get( gshipp->modelnum );
4408         num_paths = pm->n_paths;
4409         SDL_assert(num_paths > 0);
4410
4411         if (aip->path_start == -1) {
4412                 int path_num;
4413                 path_num = ai_return_path_num_from_dockbay(&Objects[aip->goal_objnum], aip->dockee_index);
4414                 SDL_assert(aip->goal_objnum >= 0 && aip->goal_objnum < MAX_OBJECTS);
4415                 ai_find_path(Pl_objp, aip->goal_objnum, path_num, 0);
4416         }
4417
4418         // nprintf(("AI", "Frame: %i, Path index = %i/%i\n", AI_FrameCount, aip->path_cur-aip->path_start, aip->path_length));
4419
4420         maybe_recreate_path(Pl_objp, aip, 0);
4421
4422         num_points = aip->path_length;
4423
4424         //      Set cvp and nvp as pointers to current and next vertices of interest on path.
4425         cvp = &Path_points[aip->path_cur].pos;
4426         if ((aip->path_cur + aip->path_dir - aip->path_start < num_points) || (aip->path_cur + aip->path_dir < aip->path_start))
4427                 nvp = &Path_points[aip->path_cur + aip->path_dir].pos;
4428         else {
4429                 //      If this is 0, then path length must be 1 which means we have no direction!
4430                 SDL_assert((aip->path_cur - aip->path_dir >= aip->path_start) && (aip->path_cur - aip->path_dir - aip->path_start < num_points));
4431                 //      Cleanup for above SDL_assert() which we hit too near release. -- MK, 5/24/98.
4432                 if (aip->path_cur - aip->path_dir - aip->path_start >= num_points) {
4433                         if (aip->path_dir == 1)
4434                                 aip->path_cur = aip->path_start;
4435                         else
4436                                 aip->path_cur = aip->path_start + num_points - 1;
4437                 }
4438
4439                 vector  delvec;
4440                 vm_vec_sub(&delvec, cvp, &Path_points[aip->path_cur - aip->path_dir].pos);
4441                 vm_vec_normalize(&delvec);
4442                 vm_vec_scale_add(&next_vec, cvp, &delvec, 10.0f);
4443                 nvp = &next_vec;
4444         }
4445
4446         //      Interrupt if can't get to current goal point.  Debug only.
4447 /*      if (pp_collide(&Pl_objp->pos, cvp, gobjp, Pl_objp->radius)) {
4448                 Int3();
4449         }
4450 */
4451         //      See if can reach next point (as opposed to current point)
4452         //      However, don't do this if docking and next point is last point.
4453         //      That is, we don't want to pursue the last point under control of the
4454         //      path code.  In docking, this is a special hack.
4455         if ((aip->mode != AIM_DOCK) || ((aip->path_cur-aip->path_start) < num_points - 2)) {
4456                 if ((aip->path_cur + aip->path_dir > aip->path_start) && (aip->path_cur + aip->path_dir < aip->path_start + num_points-2)) {
4457                         if ( timestamp_elapsed(aip->path_next_check_time)) {
4458                                 aip->path_next_check_time = timestamp( 3000 );
4459                                 if (!pp_collide(&Pl_objp->pos, nvp, gobjp, 1.1f * Pl_objp->radius)) {
4460                                         cvp = nvp;
4461                                         aip->path_cur += aip->path_dir;
4462                                         nvp = &Path_points[aip->path_cur].pos;
4463                                         //nprintf(("AI", "Reach: Advancing from point %i to %i of %i points.\n", aip->path_cur-aip->path_dir, aip->path_cur, num_points));
4464                                 }
4465                         }
4466                 }
4467         }
4468
4469         gcvp = *cvp;
4470         gnvp = *nvp;
4471
4472         dist_to_goal = vm_vec_dist_quick(&Pl_objp->pos, &gcvp);
4473         dist_to_next = vm_vec_dist_quick(&Pl_objp->pos, &gnvp);
4474         //      Can't use fvec, need to use velocity vector because we aren't necessarily
4475         //      moving in the direction we're facing.
4476
4477 //      if (IS_VEC_NULL(&Pl_objp->phys_info.vel)) {
4478         if ( vm_vec_mag_quick(&Pl_objp->phys_info.vel) < AICODE_SMALL_MAGNITUDE ) {
4479                 mag = 0.0f;
4480                 vm_vec_zero(&nvel_vec);
4481         } else
4482                 mag = vm_vec_copy_normalize(&nvel_vec, &Pl_objp->phys_info.vel);
4483
4484         //      If moving not-very-slowly and sliding, then try to slide at goal, rather than
4485         //      point at goal.
4486         slop_vec = NULL;
4487         if (mag < 1.0f)
4488                 nvel_vec = Pl_objp->orient.v.fvec;
4489         else if (mag > 5.0f) {
4490                 float   nv_dot;
4491                 nv_dot = vm_vec_dot(&Pl_objp->orient.v.fvec, &nvel_vec);
4492                 if ((nv_dot > 0.5f) && (nv_dot < 0.97f)) {
4493                         slop_vec = &temp_vec;
4494                         vm_vec_sub(slop_vec, &nvel_vec, &Pl_objp->orient.v.fvec);
4495                 }
4496         }
4497
4498         if (dist_to_goal > 0.1f)
4499                 ai_turn_towards_vector(&gcvp, Pl_objp, flFrametime, sip->srotation_time, slop_vec, NULL, 0.0f, 0);
4500
4501         //      Code to control speed is MUCH less forgiving in path following than in waypoint
4502         //      following.  Must be very close to path or might hit objects.
4503 //      prev_dot_to_goal = aip->prev_dot_to_goal;
4504         dot = vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, &gcvp);
4505         dot_to_next = vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, &gnvp);
4506
4507         set_accel_for_docking(Pl_objp, aip, dot, dot_to_next, dist_to_next, dist_to_goal, sip);
4508         aip->prev_dot_to_goal = dot;
4509
4510 //mprintf(("Goal index = %i, dist = %7.3f, dot = %7.3f\n", wp_index, dist_to_goal, dot));
4511
4512         //      If moving at a non-tiny velocity, detect attaining path point by its being close to
4513         //      line between previous and current object location.
4514         if ((dist_to_goal < MIN_DIST_TO_WAYPOINT_GOAL) || (vm_vec_dist_quick(&Pl_objp->last_pos, &Pl_objp->pos) > 0.1f)) {
4515                 vector  nearest_point;
4516                 float           r, min_dist_to_goal;
4517
4518                 r = find_nearest_point_on_line(&nearest_point, &Pl_objp->last_pos, &Pl_objp->pos, &gcvp);
4519
4520                 //      Set min_dist_to_goal = how close must be to waypoint to pick next one.
4521                 //      If docking and this is the second last waypoint, must be very close.
4522                 if ((aip->mode == AIM_DOCK) && (aip->path_cur >= aip->path_length-2))
4523                         min_dist_to_goal = MIN_DIST_TO_WAYPOINT_GOAL;
4524                 else
4525                         min_dist_to_goal = MIN_DIST_TO_WAYPOINT_GOAL + Pl_objp->radius;
4526
4527                 if ( (vm_vec_dist_quick(&Pl_objp->pos, &gcvp) < min_dist_to_goal) ||
4528                         (((r >= 0.0f) && (r <= 1.0f)) && (vm_vec_dist_quick(&nearest_point, &gcvp) < (MIN_DIST_TO_WAYPOINT_GOAL + Pl_objp->radius)))) {
4529                         aip->path_cur += aip->path_dir;
4530                         //nprintf(("AI", " Near: Advancing from point %i to %i of %i points.\n", aip->path_cur-aip->path_dir, aip->path_cur, num_points));
4531                         if (((aip->path_cur - aip->path_start) > (num_points+1)) || (aip->path_cur < aip->path_start)) {
4532                                 SDL_assert(aip->mode != AIM_DOCK);              //      If docking, should never get this far, getting to last point handled outside ai_path()
4533                                 aip->path_dir = -aip->path_dir;
4534 //                              aip->path_cur += aip->path_dir;
4535                         }
4536                 }
4537         }
4538
4539         return dist_to_goal;
4540 }
4541
4542 void update_min_max(float val, float *min, float *max)
4543 {
4544         if (val < *min)
4545                 *min = val;
4546         else if (val > *max)
4547                 *max = val;
4548 }
4549
4550 //      Stuff bounding box of all enemy objects within "range" units of object *my_objp.
4551 //      Stuff ni min_vec and max_vec.
4552 //      Return value: Number of enemy objects in bounding box.
4553 int get_enemy_team_range(object *my_objp, float range, int enemy_team_mask, vector *min_vec, vector *max_vec)
4554 {
4555         object  *objp;
4556         ship_obj        *so;
4557         int             count = 0;
4558
4559         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
4560                 objp = &Objects[so->objnum];
4561                 if (Ships[objp->instance].team & enemy_team_mask) {
4562                         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))
4563                                 if (vm_vec_dist_quick(&my_objp->pos, &objp->pos) < range) {
4564                                         if (count == 0) {
4565                                                 *min_vec = objp->pos;
4566                                                 *max_vec = objp->pos;
4567                                                 count++;
4568                                         } else {
4569                                                 update_min_max(objp->pos.xyz.x, &min_vec->xyz.x, &max_vec->xyz.x);
4570                                                 update_min_max(objp->pos.xyz.y, &min_vec->xyz.y, &max_vec->xyz.y);
4571                                                 update_min_max(objp->pos.xyz.z, &min_vec->xyz.z, &max_vec->xyz.z);
4572                                         }
4573                                 }
4574
4575                 }
4576         }
4577
4578         return count;
4579 }
4580
4581 //      Pick a relatively safe spot for objp to fly to.
4582 //      Problem:
4583 //              Finds a spot away from any enemy within a bounding box.
4584 //              Doesn't verify that "safe spot" is not near some other enemy.
4585 void ai_safety_pick_spot(object *objp)
4586 {
4587         int             objnum;
4588         int             enemy_team_mask;
4589         vector  min_vec, max_vec;
4590         vector  vec_to_center, center;
4591         vector  goal_pos;
4592
4593         objnum = OBJ_INDEX(objp);
4594
4595         enemy_team_mask = get_enemy_team_mask(objnum);
4596
4597         if (get_enemy_team_range(objp, 1000.0f, enemy_team_mask, &min_vec, &max_vec)) {
4598                 vm_vec_avg(&center, &min_vec, &max_vec);
4599                 vm_vec_normalized_dir(&vec_to_center, &center, &objp->pos);
4600
4601                 vm_vec_scale_add(&goal_pos, &center, &vec_to_center, 2000.0f);
4602         } else
4603                 vm_vec_scale_add(&goal_pos, &objp->pos, &objp->orient.v.fvec, 100.0f);
4604
4605         Ai_info[Ships[objp->instance].ai_index].goal_point = goal_pos;
4606 }
4607
4608 //      Fly to desired safe point.
4609 // Returns distance to that point.
4610 float ai_safety_goto_spot(object *objp)
4611 {
4612         float   dot, dist;
4613         ai_info *aip;
4614         vector  vec_to_goal;
4615         ship_info       *sip;
4616         float   dot_val;
4617
4618         sip = &Ship_info[Ships[objp->instance].ship_info_index];
4619
4620         aip = &Ai_info[Ships[objp->instance].ai_index];
4621         dist = vm_vec_normalized_dir(&vec_to_goal, &aip->goal_point, &objp->pos);
4622         dot = vm_vec_dot(&vec_to_goal, &objp->orient.v.fvec);
4623
4624         dot_val = (1.1f + dot) / 2.0f;
4625         if (dist > 200.0f) {
4626                 set_accel_for_target_speed(objp, sip->max_speed * dot_val);
4627         } else
4628                 set_accel_for_target_speed(objp, sip->max_speed * dot_val * (dist/200.0f + 0.2f));
4629
4630         return dist;
4631 }
4632
4633 void ai_safety_circle_spot(object *objp)
4634 {
4635         vector  goal_point;
4636         ship_info       *sip;
4637         float           dot;
4638
4639         sip = &Ship_info[Ships[objp->instance].ship_info_index];
4640
4641         goal_point = Ai_info[Ships[objp->instance].ai_index].goal_point;
4642         dot = turn_towards_tangent(objp, &goal_point, 250.0f);  //      Increased from 50 to 250 to make circling not look so wacky.
4643
4644         set_accel_for_target_speed(objp, 0.5f * (1.0f + dot) * sip->max_speed/4.0f);
4645
4646 //      float dist = vm_vec_dist_quick(&goal_point, &Pl_objp->pos);
4647 //      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));
4648
4649 }
4650
4651 //      --------------------------------------------------------------------------
4652 void ai_safety()
4653 {
4654         ai_info *aip;
4655
4656         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
4657
4658         switch (aip->submode) {
4659         case AISS_1:
4660                 ai_safety_pick_spot(Pl_objp);
4661                 aip->submode = AISS_2;
4662                 aip->submode_start_time = Missiontime;
4663                 break;
4664         case AISS_1a:   //      Pick a safe point because we just got whacked!
4665                 Int3();
4666                 break;
4667         case AISS_2:
4668                 if (ai_safety_goto_spot(Pl_objp) < 25.0f) {
4669                         aip->submode = AISS_3;
4670                         aip->submode_start_time = Missiontime;
4671                 }
4672                 break;
4673         case AISS_3:
4674                 ai_safety_circle_spot(Pl_objp);
4675                 break;
4676         default:
4677                 Int3();         //      Illegal submode for ai_safety();
4678                 break;
4679         }
4680 }
4681
4682 //      --------------------------------------------------------------------------
4683 //      make Pl_objp fly waypoints.
4684 void ai_waypoints()
4685 {
4686         int             wp_index;
4687         vector  *wp_cur, *wp_next;
4688         float           dot, dist_to_goal;//, dot_to_next;
4689         ship            *shipp = &Ships[Pl_objp->instance];
4690         ship_info       *sip = &Ship_info[shipp->ship_info_index];
4691         waypoint_list   *wpl;
4692         ai_info *aip;
4693         vector  nvel_vec;
4694         float           mag;
4695         float           prev_dot_to_goal;
4696         vector  temp_vec;
4697         vector  *slop_vec;
4698
4699         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
4700
4701         wp_index = aip->wp_index;
4702
4703         if (wp_index == -1) {
4704                 ai_start_waypoints(Pl_objp, 0, WPF_REPEAT);
4705                 wp_index = aip->wp_index;
4706                 aip->wp_dir = 1;
4707         }
4708
4709         wpl = &Waypoint_lists[Ai_info[Ships[Pl_objp->instance].ai_index].wp_list];
4710
4711         SDL_assert(wpl->count); // What? Is this zero? Probably wp_index never got initialized!
4712
4713         wp_cur = &wpl->waypoints[wp_index];
4714         wp_next = &wpl->waypoints[(wp_index+1) % wpl->count];
4715
4716         dist_to_goal = vm_vec_dist_quick(&Pl_objp->pos, wp_cur);
4717
4718         //      Can't use fvec, need to use velocity vector because we aren't necessarily
4719         //      moving in the direction we're facing.
4720         // AL 23-3-98: Account for very small velocities by checking result of vm_vec_mag().
4721         //                                      If we don't vm_vec_copy_normalize() will think it is normalizing a null vector.
4722 //      if (IS_VEC_NULL(&Pl_objp->phys_info.vel)) {
4723         if ( vm_vec_mag_quick(&Pl_objp->phys_info.vel) < AICODE_SMALL_MAGNITUDE ) {
4724                 mag = 0.0f;
4725                 vm_vec_zero(&nvel_vec);
4726         } else {
4727                 mag = vm_vec_copy_normalize(&nvel_vec, &Pl_objp->phys_info.vel);
4728         }
4729
4730         //      If moving not-very-slowly and sliding, then try to slide at goal, rather than
4731         //      point at goal.
4732         slop_vec = NULL;
4733         if (mag < 1.0f) {
4734                 nvel_vec = Pl_objp->orient.v.fvec;
4735         } else if (mag > 5.0f) {
4736                 float   nv_dot;
4737                 nv_dot = vm_vec_dot(&Pl_objp->orient.v.fvec, &nvel_vec);
4738                 if ((nv_dot > 0.5f) && (nv_dot < 0.97f)) {
4739                         slop_vec = &temp_vec;
4740                         vm_vec_sub(slop_vec, &nvel_vec, &Pl_objp->orient.v.fvec);
4741                 }
4742         }
4743
4744         //      If a wing leader, take turns more slowly, based on size of wing.
4745         int     scale;
4746
4747         if (Ai_info[Ships[Pl_objp->instance].ai_index].wing >= 0) {
4748                 scale = Wings[Ai_info[Ships[Pl_objp->instance].ai_index].wing].current_count;
4749                 scale = (int) ((scale+1)/2);
4750         } else {
4751                 scale = 1;
4752         }
4753
4754         if (dist_to_goal > 0.1f) {
4755                 ai_turn_towards_vector(wp_cur, Pl_objp, flFrametime, sip->srotation_time*3.0f*scale, slop_vec, NULL, 0.0f, 0);
4756         }
4757
4758         prev_dot_to_goal = aip->prev_dot_to_goal;
4759         dot = vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, wp_cur);
4760         /*dot_to_next =*/ vm_vec_dot_to_point(&nvel_vec, &Pl_objp->pos, wp_next);
4761         aip->prev_dot_to_goal = dot;
4762
4763         //      If there is no next point on the path, don't care about dot to next.
4764 //      if (wp_index + 1 >= wpl->count) {
4765 //              dot_to_next = dot;
4766 //      }
4767
4768         // nprintf(("AI", "Wp #%i, dot = %6.3f, next dot = %6.3f, dist = %7.2f\n", wp_index, dot, dot_to_next, dist_to_goal));
4769
4770         if (Pl_objp->phys_info.speed < 0.0f) {
4771                 accelerate_ship(aip, 1.0f/32);
4772         } else if (prev_dot_to_goal > dot+0.01f) {
4773                 //      We are further from pointing at our goal this frame than last frame, so slow down.
4774                 set_accel_for_target_speed(Pl_objp, Pl_objp->phys_info.speed * 0.95f);
4775         } else if (dist_to_goal < 100.0f) {
4776                 float slew_dot = vm_vec_dot(&Pl_objp->orient.v.fvec, &nvel_vec);
4777                 if (fl_abs(slew_dot) < 0.9f) {
4778                         accelerate_ship(aip, 0.0f);
4779                 } else if (dot < 0.88f + 0.1f*(100.0f - dist_to_goal)/100.0f) {
4780                         accelerate_ship(aip, 0.0f);
4781                 } else {
4782                         accelerate_ship(aip, 0.5f * dot * dot);
4783                 }
4784         } else {
4785                 float   dot1;
4786                 if (dist_to_goal < 250.0f) {
4787                         dot1 = dot*dot*dot;                             //      Very important to be pointing towards goal when nearby.  Note, cubing preserves sign.
4788                 } else {
4789                         if (dot > 0.0f) {
4790                                 dot1 = dot*dot;
4791                         } else {
4792                                 dot1 = dot;
4793                         }
4794                 }
4795
4796                 if (dist_to_goal > 100.0f + Pl_objp->radius * 2) {
4797                         if (dot < 0.2f) {
4798                                 dot1 = 0.2f;
4799                         }
4800                 }
4801
4802                 if (sip->flags & SIF_SMALL_SHIP) {
4803                         set_accel_for_target_speed(Pl_objp, dot1 * dist_to_goal/5.0f);
4804                 } else {
4805                         set_accel_for_target_speed(Pl_objp, dot1 * dist_to_goal/10.0f);
4806                 }
4807         }
4808
4809         //      Make sure not travelling too fast for someone to keep up.
4810         float   max_allowed_speed = 9999.9f;
4811
4812         if (shipp->wingnum != -1) {
4813                 max_allowed_speed = 0.9f * get_wing_lowest_max_speed(Pl_objp);
4814         }
4815
4816         // check if waypoint speed cap is set and adjust max speed
4817         if (aip->waypoint_speed_cap > 0) {
4818                 max_allowed_speed = (float) aip->waypoint_speed_cap;
4819         }
4820
4821         if (aip->prev_accel * shipp->current_max_speed > max_allowed_speed) {
4822                 accelerate_ship(aip, max_allowed_speed / shipp->current_max_speed);
4823         }
4824
4825         if (vm_vec_dist_quick(&Pl_objp->last_pos, &Pl_objp->pos) > 0.1f) {
4826                 vector  nearest_point;
4827                 float           r;
4828
4829                 r = find_nearest_point_on_line(&nearest_point, &Pl_objp->last_pos, &Pl_objp->pos, wp_cur);
4830
4831                 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))) ||
4832                         (((r >= 0.0f) && (r <= 1.0f)) && (vm_vec_dist_quick(&nearest_point, wp_cur) < (MIN_DIST_TO_WAYPOINT_GOAL + fl_sqrt(Pl_objp->radius))))) {
4833                         wp_index++;
4834                         if (wp_index >= wpl->count) {
4835                                 if (aip->wp_flags & WPF_REPEAT) {
4836                                         wp_index = 0;
4837                                 } else {
4838                                         int treat_as_ship;
4839
4840                                         // when not repeating waypoints -- mark the goal as done and put and entry into the mission log
4841                                         // we must be careful when dealing with wings.  A ship in a wing might be completing
4842                                         // a waypoint for for the entire wing, or it might be completing a goal for itself.  If
4843                                         // for itself and in a wing, treat the completion as we would a ship
4844                                         treat_as_ship = 1;
4845                                         if ( Ships[Pl_objp->instance].wingnum != -1 ) {
4846                                                 int type;
4847
4848                                                 // I don't think that you can fly waypoints as dynamic goals!!!
4849                                                 // -- This is legal, just stupid. -- SDL_assert( (aip->active_goal != AI_GOAL_NONE) && (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC) );
4850                                                 
4851                                                 //      Clean up from above SDL_assert, just in case we ship without fixing it.  (Encountered by JimB on 2/9/98)
4852                                                 if ( (aip->active_goal == AI_GOAL_NONE) || (aip->active_goal == AI_ACTIVE_GOAL_DYNAMIC) ) {
4853                                                         aip->mode = AIM_NONE;
4854                                                         Int3(); //      Look at the ship, find out of it's supposed to be flying waypoints. -- MK.
4855                                                 }
4856
4857                                                 type = aip->goals[aip->active_goal].type;
4858                                                 if ( (type == AIG_TYPE_EVENT_WING) || (type == AIG_TYPE_PLAYER_WING) ) {
4859                                                         treat_as_ship = 0;
4860                                                 } else {
4861                                                         treat_as_ship = 1;
4862                                                 }
4863                                         }
4864
4865                                         // if the ship is not in a wing, remove the goal and continue on
4866                                         if ( treat_as_ship ) {
4867                                                 ai_mission_goal_complete( aip );                                        // this call should reset the AI mode
4868                                                 mission_log_add_entry(LOG_WAYPOINTS_DONE, Ships[Pl_objp->instance].ship_name, wpl->name, -1 );
4869                                         } else {
4870                                                 // this ship is in a wing.  We must mark the goal as being completed for all ships
4871                                                 // in the wing.  We will also mark an entry in the log that the wing completed the goal
4872                                                 // not the individual ship.
4873                                                 ai_mission_wing_goal_complete( Ships[Pl_objp->instance].wingnum, &(aip->goals[aip->active_goal]) );
4874                                                 mission_log_add_entry( LOG_WAYPOINTS_DONE, Wings[Ships[Pl_objp->instance].wingnum].name, wpl->name, -1 );
4875                                         }
4876                                         //wp_index = wpl->count-1;
4877                                 }
4878                         }
4879
4880                         aip->wp_index = wp_index;
4881                 }
4882         }
4883 }
4884
4885 //      Make Pl_objp avoid En_objp
4886 //      Not like evading.  This is for avoiding a collision!
4887 //      Note, use sliding if available.
4888 void avoid_ship()
4889 {
4890         //      To avoid an object, turn towards right or left vector until facing away from object.
4891         //      To choose right vs. left, pick one that is further from center of avoid object.
4892         //      Keep turning away from until pointing away from ship.
4893         //      Stay in avoid mode until at least 3 enemy ship radii away.
4894
4895         //      Speed setting:
4896         //      If inside sphere, zero speed and turn towards outside.
4897         //      If outside sphere, inside 2x sphere, set speed percent of max to:
4898         //              max(away_dot, (dist-rad)/rad)
4899         //      where away_dot is dot(Pl_objp->v.fvec, vec_En_objp_to_Pl_objp)
4900
4901         vector  vec_to_enemy;
4902         float           away_dot;
4903         float           dist;
4904         ship            *shipp = &Ships[Pl_objp->instance];
4905         ship_info       *sip = &Ship_info[shipp->ship_info_index];
4906         ai_info *aip = &Ai_info[shipp->ai_index];
4907         vector  player_pos, enemy_pos;
4908
4909         // if we're avoiding a stealth ship, then we know where he is, update with no error
4910         if ( is_object_stealth_ship(En_objp) ) {
4911                 update_ai_stealth_info_with_error(aip/*, 1*/);
4912         }
4913
4914         ai_set_positions(Pl_objp, En_objp, aip, &player_pos, &enemy_pos);
4915         vm_vec_sub(&vec_to_enemy, &enemy_pos, &Pl_objp->pos);
4916
4917         dist = vm_vec_normalize(&vec_to_enemy);
4918         away_dot = -vm_vec_dot(&Pl_objp->orient.v.fvec, &vec_to_enemy);
4919         
4920         if ((sip->max_vel.xyz.x > 0.0f) || (sip->max_vel.xyz.y > 0.0f)) {
4921                 if (vm_vec_dot(&Pl_objp->orient.v.rvec, &vec_to_enemy) > 0.0f) {
4922                         AI_ci.sideways = -1.0f;
4923                 } else {
4924                         AI_ci.sideways = 1.0f;
4925                 }
4926                 if (vm_vec_dot(&Pl_objp->orient.v.uvec, &vec_to_enemy) > 0.0f) {
4927                         AI_ci.vertical = -1.0f;
4928                 } else {
4929                         AI_ci.vertical = 1.0f;
4930                 }
4931         }               
4932
4933         //nprintf(("AI", "Frame %i: Sliding: %s %s\n", Framecount, AI_ci.sideways < 0 ? "left" : "right", AI_ci.vertical < 0 ? "down" : "up" ));
4934         // nprintf(("AI", "away_dot = %6.3f, dist = %7.2f, dist/radsum = %6.3f\n", away_dot, dist, dist/(Pl_objp->radius + En_objp->radius)));
4935
4936         //      If in front of enemy, turn away from it.
4937         //      If behind enemy, try to get fully behind it.
4938         if (away_dot < 0.0f) {
4939                 turn_away_from_point(Pl_objp, &enemy_pos, Pl_objp->phys_info.speed);
4940         } else {
4941                 vector  goal_pos;
4942
4943                 vm_vec_scale_add(&goal_pos, &En_objp->pos, &En_objp->orient.v.fvec, -100.0f);
4944                 turn_towards_point(Pl_objp, &goal_pos, NULL, Pl_objp->phys_info.speed);
4945         }
4946
4947         //      Set speed.
4948         float   radsum = Pl_objp->radius + En_objp->radius;
4949
4950         if (dist < radsum)
4951                 accelerate_ship(aip, max(away_dot, 0.2f));
4952         else if (dist < 2*radsum)
4953                 accelerate_ship(aip, max(away_dot, (dist - radsum) / radsum)+0.2f);
4954         else
4955                 accelerate_ship(aip, 1.0f);
4956
4957 }
4958
4959 //      Maybe it's time to resume the previous AI mode in aip->previous_mode.
4960 //      Each type of previous_mode has its own criteria on when to resume.
4961 //      Return true if previous mode was resumed.
4962 int maybe_resume_previous_mode(object *objp, ai_info *aip)
4963 {
4964         //      Only (maybe) resume previous goal if current goal is dynamic.
4965         if (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC)
4966                 return 0;
4967
4968         if (aip->mode == AIM_EVADE_WEAPON) {
4969                 if (timestamp_elapsed(aip->mode_time) || (((aip->nearest_locked_object == -1) || (Objects[aip->nearest_locked_object].type != OBJ_WEAPON)) && (aip->danger_weapon_objnum == -1))) {
4970                         SDL_assert(aip->previous_mode != AIM_EVADE_WEAPON);
4971                         aip->mode = aip->previous_mode;
4972                         aip->submode = aip->previous_submode;
4973                         aip->submode_start_time = Missiontime;
4974                         aip->active_goal = AI_GOAL_NONE;
4975                         aip->mode_time = -1;                    //      Means do forever.
4976                         return 1;
4977                 }
4978         } else if ( aip->previous_mode == AIM_GUARD) {
4979                 if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
4980                         object  *guard_objp;
4981                         float   dist;
4982
4983                         guard_objp = &Objects[aip->guard_objnum];
4984                         dist = vm_vec_dist_quick(&guard_objp->pos, &objp->pos);
4985
4986                         //      If guarding ship is far away from guardee and enemy is far away from guardee,
4987                         //      then stop chasing and resume guarding.
4988                         if (dist > (MAX_GUARD_DIST + guard_objp->radius) * 6) {
4989                                 if ((En_objp != NULL) && (En_objp->type == OBJ_SHIP)) {
4990                                         if (vm_vec_dist_quick(&guard_objp->pos, &En_objp->pos) > (MAX_GUARD_DIST + guard_objp->radius) * 6) {
4991                                                 SDL_assert(aip->previous_mode == AIM_GUARD);
4992                                                 aip->mode = aip->previous_mode;
4993                                                 aip->submode = AIS_GUARD_PATROL;
4994                                                 aip->active_goal = AI_GOAL_NONE;
4995                                                 return 1;
4996                                         }
4997                                 }
4998                         }
4999                 }
5000         }
5001
5002         return 0;
5003
5004 }
5005
5006 //      Call this function if you want something to happen on average every N quarters of a second.
5007 //      The truth value returned by this function will be the same for any given quarter second interval.
5008 //      The value "num" is only passed in to get asynchronous behavior for different objects.
5009 //      modulus == 1 will always return true.
5010 //      modulus == 2 will return true half the time.
5011 //      modulus == 16 will return true for one quarter second interval every four seconds.
5012 int static_rand_timed(int num, int modulus)
5013 {
5014         if (modulus < 2)
5015                 return 1;
5016         else {
5017                 int     t;
5018
5019                 t = Missiontime >> 18;          //      Get time in quarters of a second
5020                 t += num;
5021
5022                 return !(t % modulus);
5023         }
5024 }
5025
5026 //      Maybe fire afterburner based on AI class
5027 int ai_maybe_fire_afterburner(object *objp, ai_info *aip)
5028 {
5029         if (aip->ai_class == 0)
5030                 return 0;               //      Lowest level never aburners away
5031         else  {
5032                 //      Maybe don't afterburner because of a potential collision with the player.
5033                 //      If not multiplayer, near player and player in front, probably don't afterburner.
5034                 if (!(Game_mode & GM_MULTIPLAYER)) {
5035                         if (Ships[objp->instance].team == Player_ship->team) {
5036                                 float   dist;
5037
5038                                 dist = vm_vec_dist_quick(&objp->pos, &Player_obj->pos) - Player_obj->radius - objp->radius;
5039                                 if (dist < 150.0f) {
5040                                         vector  v2p;
5041                                         float           dot;
5042
5043                                         vm_vec_normalized_dir(&v2p, &Player_obj->pos, &objp->pos);
5044                                         dot = vm_vec_dot(&v2p, &objp->orient.v.fvec);
5045
5046                                         if (dot > 0.0f) {
5047                                                 if (dot * dist > 50.0f)
5048                                                         return 0;
5049                                         }
5050                                 }
5051                         }
5052                 }
5053
5054                 if (aip->ai_class >= Num_ai_classes-2)
5055                         return 1;               //      Highest two levels always aburner away.
5056                 else {
5057                         return static_rand_timed(objp-Objects, Num_ai_classes - aip->ai_class);
5058                 }
5059         }
5060 }
5061
5062 //      Maybe engage afterburner after being hit by an object.
5063 void maybe_afterburner_after_ship_hit(object *objp, ai_info *aip, object *en_objp)
5064 {
5065         //      Only do if facing a little away.
5066         if (en_objp != NULL) {
5067                 vector  v2e;
5068
5069                 vm_vec_normalized_dir(&v2e, &en_objp->pos, &objp->pos);
5070                 if (vm_vec_dot(&v2e, &objp->orient.v.fvec) > -0.5f)
5071                         return;
5072         }
5073
5074         if (!( objp->phys_info.flags & PF_AFTERBURNER_ON )) {
5075                 if (ai_maybe_fire_afterburner(objp, aip)) {
5076                         afterburners_start(objp);
5077                         aip->afterburner_stop_time = Missiontime + F1_0/2;
5078                 }
5079         }
5080 }
5081
5082 //      Return true if object *objp is an instructor.
5083 //      Is an instructor if name begins INSTRUCTOR_SHIP_NAME else not.
5084 int is_instructor(object *objp)
5085 {
5086         return !SDL_strncasecmp(Ships[objp->instance].ship_name, INSTRUCTOR_SHIP_NAME, strlen(INSTRUCTOR_SHIP_NAME));
5087 }
5088
5089 //      Evade the weapon aip->danger_weapon_objnum
5090 //      If it's not valid, do a quick out.
5091 //      Evade by accelerating hard.
5092 //      If necessary, turn hard left or hard right.
5093 void evade_weapon()
5094 {
5095         object  *weapon_objp = NULL;
5096         object  *unlocked_weapon_objp = NULL, *locked_weapon_objp = NULL;
5097         vector  weapon_pos, player_pos, goal_point;
5098         vector  vec_from_enemy;
5099         float           dot_from_enemy, dot_to_enemy;
5100         float           dist;
5101         ship            *shipp = &Ships[Pl_objp->instance];
5102         ai_info *aip = &Ai_info[shipp->ai_index];
5103
5104         if (is_instructor(Pl_objp))
5105                 return;
5106
5107         //      Make sure we're actually being attacked.
5108         //      Favor locked objects.
5109         if (aip->nearest_locked_object != -1) {
5110                 if (Objects[aip->nearest_locked_object].type == OBJ_WEAPON)
5111                         locked_weapon_objp = &Objects[aip->nearest_locked_object];
5112         }
5113         
5114         if (aip->danger_weapon_objnum != -1) {
5115                 if (Objects[aip->danger_weapon_objnum].signature == aip->danger_weapon_signature) {
5116                         unlocked_weapon_objp = &Objects[aip->danger_weapon_objnum];
5117                 } else {
5118                         aip->danger_weapon_objnum = -1;         //      Signatures don't match, so no longer endangered.
5119                 }
5120         }
5121
5122         if (locked_weapon_objp != NULL) {
5123                 if (unlocked_weapon_objp != NULL) {
5124                         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))
5125                                 weapon_objp = locked_weapon_objp;
5126                         else
5127                                 weapon_objp = unlocked_weapon_objp;
5128                 } else
5129                         weapon_objp = locked_weapon_objp;
5130         } else if (unlocked_weapon_objp != NULL)
5131                 weapon_objp = unlocked_weapon_objp;
5132         else {
5133                 if (aip->mode == AIM_EVADE_WEAPON)
5134                         maybe_resume_previous_mode(Pl_objp, aip);
5135                 return;
5136         }
5137
5138         SDL_assert(weapon_objp != NULL);
5139
5140         if (weapon_objp->type != OBJ_WEAPON) {
5141                 if (aip->mode == AIM_EVADE_WEAPON)
5142                         maybe_resume_previous_mode(Pl_objp, aip);
5143                 return;
5144         }
5145         
5146         weapon_pos = weapon_objp->pos;
5147         player_pos = Pl_objp->pos;
5148
5149         //      Make speed based on skill level, varying at highest skill level, which is harder to hit.
5150         accelerate_ship(aip, 1.0f);
5151
5152         dist = vm_vec_normalized_dir(&vec_from_enemy, &player_pos, &weapon_pos);
5153
5154         dot_to_enemy = -vm_vec_dot(&Pl_objp->orient.v.fvec, &vec_from_enemy);
5155         dot_from_enemy = vm_vec_dot(&weapon_objp->orient.v.fvec, &vec_from_enemy);
5156         //nprintf(("AI", "dot from enemy = %7.3f\n", dot_from_enemy));
5157
5158         //      If shot is incoming...
5159         if (dot_from_enemy < 0.3f) {
5160                 if (weapon_objp == unlocked_weapon_objp)
5161                         aip->danger_weapon_objnum = -1;
5162                 return;
5163         } else if (dot_from_enemy > 0.7f) {
5164                 if (dist < 200.0f) {
5165                         if (!( Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
5166                                 if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
5167                                         //nprintf(("AI", "Frame %i, turning on afterburner.\n", AI_FrameCount));
5168                                         afterburners_start(Pl_objp);
5169                                         aip->afterburner_stop_time = Missiontime + F1_0/2;
5170                                 }
5171                         }
5172                 }
5173
5174                 //      If we're sort of pointing towards it...
5175                 if ((dot_to_enemy < -0.5f) || (dot_to_enemy > 0.5f)) {
5176                         float   rdot;
5177
5178                         //      Turn hard left or right, depending on which gets out of way quicker.
5179                         rdot = vm_vec_dot(&Pl_objp->orient.v.rvec, &vec_from_enemy);
5180
5181                         if ((rdot < -0.5f) || (rdot > 0.5f))
5182                                 vm_vec_scale_add(&goal_point, &Pl_objp->pos, &Pl_objp->orient.v.rvec, -200.0f);
5183                         else
5184                                 vm_vec_scale_add(&goal_point, &Pl_objp->pos, &Pl_objp->orient.v.rvec, 200.0f);
5185
5186                         turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
5187                 }
5188         }
5189
5190 }
5191
5192 //      Use sliding and backwards moving to face enemy.
5193 //      (Coded 2/20/98.  Works fine, but it's hard to see how to integrate it into the AI system.
5194 //       Typically ships are moving so fast that a little sliding isn't enough to gain an advantage.
5195 //       It's currently used to avoid collisions and could be used to evade weapon fire, but the latter
5196 //       would be frustrating, I think.
5197 //       This function is currently not called.)
5198 void slide_face_ship()
5199 {
5200         ship_info       *sip;
5201
5202         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
5203
5204         //      If can't slide, return.
5205         if ((sip->max_vel.xyz.x == 0.0f) && (sip->max_vel.xyz.y == 0.0f))
5206                 return;
5207
5208         vector  goal_pos;
5209         float           dot_from_enemy;
5210         vector  vec_from_enemy, vec_to_goal;
5211         float           dist;
5212         float           up, right;
5213         ai_info         *aip;
5214
5215         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
5216
5217         dist = vm_vec_normalized_dir(&vec_from_enemy, &Pl_objp->pos, &En_objp->pos);
5218
5219         ai_turn_towards_vector(&En_objp->pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
5220
5221         dot_from_enemy = vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.fvec);
5222
5223         if (vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.rvec) > 0.0f)
5224                 right = 1.0f;
5225         else
5226                 right = -1.0f;
5227
5228         if (vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.uvec) > 0.0f)
5229                 up = 1.0f;
5230         else
5231                 up = -1.0f;
5232
5233         vm_vec_scale_add(&goal_pos, &En_objp->pos, &En_objp->orient.v.rvec, right * 200.0f);
5234         vm_vec_scale_add(&goal_pos, &En_objp->pos, &En_objp->orient.v.uvec, up * 200.0f);
5235
5236         vm_vec_normalized_dir(&vec_to_goal, &goal_pos, &Pl_objp->pos);
5237
5238         if (vm_vec_dot(&vec_to_goal, &Pl_objp->orient.v.rvec) > 0.0f)
5239                 AI_ci.sideways = 1.0f;
5240         else
5241                 AI_ci.sideways = -1.0f;
5242
5243         if (vm_vec_dot(&vec_to_goal, &Pl_objp->orient.v.uvec) > 0.0f)
5244                 AI_ci.vertical = 1.0f;
5245         else
5246                 AI_ci.vertical = -1.0f;
5247
5248         if (dist < 200.0f) {
5249                 if (dot_from_enemy < 0.7f)
5250                         accelerate_ship(aip, -1.0f);
5251                 else
5252                         accelerate_ship(aip, dot_from_enemy + 0.5f);
5253         } else {
5254                 if (dot_from_enemy < 0.7f) {
5255                         accelerate_ship(aip, 0.2f);
5256                 } else {
5257                         accelerate_ship(aip, 1.0f);
5258                 }
5259         }
5260 }
5261
5262 //      General code for handling one ship evading another.
5263 //      Problem: This code is also used for avoiding an impending collision.
5264 //      In such a case, it is not good to go to max speed, which is often good
5265 //      for a certain kind of evasion.
5266 void evade_ship()
5267 {
5268         vector  player_pos, enemy_pos, goal_point;
5269         vector  vec_from_enemy;
5270         float           dot_from_enemy;
5271         float           dist;
5272         ship            *shipp = &Ships[Pl_objp->instance];
5273         ship_info       *sip = &Ship_info[shipp->ship_info_index];
5274         ai_info *aip = &Ai_info[shipp->ai_index];
5275         float           bank_override = 0.0f;
5276
5277         ai_set_positions(Pl_objp, En_objp, aip, &player_pos, &enemy_pos);
5278
5279         //      Make speed based on skill level, varying at highest skill level, which is harder to hit.
5280         if (Game_skill_level == NUM_SKILL_LEVELS-1) {
5281                 int     rand_int;
5282                 float   accel_val;
5283
5284                 rand_int = static_rand(Pl_objp-Objects);
5285                 accel_val = (float) (((Missiontime^rand_int) >> 14) & 0x0f)/32.0f + 0.5f;
5286                 accelerate_ship(aip, accel_val);
5287                 //nprintf(("AI", "Accel value = %7.3f\n", accel_val));
5288         } else
5289                 accelerate_ship(aip, (float) (Game_skill_level+2) / (NUM_SKILL_LEVELS+1));
5290
5291         if ((Missiontime - aip->submode_start_time > F1_0/2) && (sip->afterburner_fuel_capacity > 0.0f)) {
5292                 float percent_left = 100.0f * shipp->afterburner_fuel / sip->afterburner_fuel_capacity;
5293                 if (percent_left > 30.0f + ((Pl_objp-Objects) & 0x0f)) {
5294                         afterburners_start(Pl_objp);
5295                         aip->afterburner_stop_time = Missiontime + F1_0 + static_rand(Pl_objp-Objects)/4;
5296                 }
5297         }
5298
5299         vm_vec_sub(&vec_from_enemy, &player_pos, &enemy_pos);
5300
5301         dist = vm_vec_normalize(&vec_from_enemy);
5302         dot_from_enemy = vm_vec_dot(&En_objp->orient.v.fvec, &vec_from_enemy);
5303
5304         if (dist > 250.0f) {
5305                 vector  gp1, gp2;
5306                 //      If far away from enemy, circle, going to nearer of point far off left or right wing
5307                 vm_vec_scale_add(&gp1, &enemy_pos, &En_objp->orient.v.rvec, 250.0f);
5308                 vm_vec_scale_add(&gp2, &enemy_pos, &En_objp->orient.v.rvec, -250.0f);
5309                 if (vm_vec_dist_quick(&gp1, &Pl_objp->pos) < vm_vec_dist_quick(&gp2, &Pl_objp->pos))
5310                         goal_point = gp1;
5311                 else
5312                         goal_point = gp2;
5313         } else if (dot_from_enemy < 0.1f) {
5314                 //      If already close to behind, goal is to get completely behind.
5315                 vm_vec_scale_add(&goal_point, &enemy_pos, &En_objp->orient.v.fvec, -1000.0f);
5316         } else if (dot_from_enemy > 0.9f) {
5317                 //      If enemy pointing almost right at self, and self pointing close to enemy, turn away from
5318                 vector  vec_to_enemy;
5319                 float           dot_to_enemy;
5320
5321                 vm_vec_sub(&vec_to_enemy, &enemy_pos, &player_pos);
5322
5323                 vm_vec_normalize(&vec_to_enemy);
5324                 dot_to_enemy = vm_vec_dot(&Pl_objp->orient.v.fvec, &vec_to_enemy);
5325                 if (dot_to_enemy > 0.75f) {
5326                         //      Used to go to En_objp's right vector, but due to banking while turning, that
5327                         //      caused flying in an odd spiral.
5328                         vm_vec_scale_add(&goal_point, &enemy_pos, &Pl_objp->orient.v.rvec, 1000.0f);
5329                         if (dist < 100.0f)
5330                                 bank_override = Pl_objp->phys_info.speed; 
5331                 } else {
5332                         bank_override = Pl_objp->phys_info.speed;                       //      In enemy's sights, not pointing at him, twirl away.
5333                         // nprintf(("Mike", " Do sumpin' else."));
5334                         goto evade_ship_l1;
5335                 }
5336         } else {
5337 evade_ship_l1: ;
5338                 if (aip->ai_evasion > myrand()*100.0f/32767.0f) {
5339                         int     temp;
5340                         float   scale;
5341                         float   psrandval;      //      some value close to zero to choose whether to turn right or left.
5342
5343                         psrandval = (float) (((Missiontime >> 14) & 0x0f) - 8); //      Value between -8 and 7
5344                         psrandval = psrandval/16.0f;                                                    //      Value between -1/2 and 1/2 (approx)
5345
5346                         //      If not close to behind, turn towards his right or left vector, whichever won't cross his path.
5347                         if (vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.rvec) > psrandval) {
5348                                 scale = 1000.0f;
5349                         } else {
5350                                 scale = -1000.0f;
5351                         }
5352
5353                         vm_vec_scale_add(&goal_point, &enemy_pos, &En_objp->orient.v.rvec, scale);
5354
5355                         temp = ((Missiontime >> 16) & 0x07);
5356                         temp = ((temp * (temp+1)) % 16)/2 - 4;
5357                         if ((psrandval == 0) && (temp == 0))
5358                                 temp = 3;
5359
5360                         scale = 200.0f * temp;
5361
5362                         vm_vec_scale_add2(&goal_point, &En_objp->orient.v.uvec, scale);
5363                 } else {
5364                         //      No evasion this frame, but continue with previous turn.
5365                         //      Reason: If you don't, you lose rotational momentum.  Turning every other frame,
5366                         //      and not in between results in a very slow turn because of loss of momentum.
5367                         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))
5368                                 goal_point = aip->prev_goal_point;
5369                         else
5370                                 vm_vec_scale_add(&goal_point, &enemy_pos, &En_objp->orient.v.rvec, 100.0f);
5371                 }
5372         }
5373
5374         // nprintf(("Mike", "Goal point = %7.1f %7.1f %7.1f\n", goal_point.xyz.x, goal_point.xyz.y, goal_point.xyz.z));
5375         turn_towards_point(Pl_objp, &goal_point, NULL, bank_override);
5376
5377         aip->prev_goal_point = goal_point;
5378 }
5379
5380 //      --------------------------------------------------------------------------
5381 //      Fly in a manner making it difficult for opponent to attack.
5382 void ai_evade()
5383 {
5384         evade_ship();
5385 }
5386
5387 /*
5388 // -------------------------------------------------------------------
5389 //      Refine predicted enemy position because enemy will move while we move
5390 //      towards predicted enemy position.
5391 //      last_delta_vec is stuffed with size of polishing in last step.  This small amount
5392 //      can be used to perturb the predicted position to make firing not be exact.
5393 //      This function will almost always undershoot actual position, assuming both ships
5394 //      are moving at constant speed.  But with even one polishing step, the error should
5395 //      be under 1%. The number of polishing steps is specified in the parameter num_polish_steps.
5396 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)
5397 {
5398         int     iteration;
5399         vector  player_pos = pobjp->pos;
5400         vector  enemy_pos = *predicted_enemy_pos;
5401         physics_info    *en_physp = &eobjp->phys_info;
5402         float           time_to_enemy;
5403         vector  last_predicted_enemy_pos = *predicted_enemy_pos;
5404         
5405         vm_vec_zero(last_delta_vec);
5406
5407         for (iteration=0; iteration < num_polish_steps; iteration++) {
5408                 dist_to_enemy = vm_vec_dist_quick(predicted_enemy_pos, &player_pos);
5409                 time_to_enemy = compute_time_to_enemy(dist_to_enemy, pobjp, eobjp);
5410                 vm_vec_scale_add(predicted_enemy_pos, &eobjp->pos, &eobjp->phys_info.vel, time_to_enemy);
5411                 vm_vec_sub(last_delta_vec, predicted_enemy_pos, &last_predicted_enemy_pos);
5412                 last_predicted_enemy_pos= *predicted_enemy_pos;
5413         }
5414 }
5415 */
5416
5417 /*
5418 Relevant variables are:
5419         best_dot_to_enemy               best dot product to enemy in last BEST_DOT_TIME seconds
5420         best_dot_to_time                time at which best dot occurred
5421         best_dot_from_enemy     best dot product for enemy to player in last BEST_DOT_TIME seconds
5422         best_dot_from_time      time at which best dot occurred
5423         submode_start_time      time at which we entered the current submode
5424         previous_submode                previous submode, get it?
5425 Legal submodes are:
5426         CONTINUOUS_TURN vector_id {0..3 = right, -right, up, -up}
5427         ATTACK
5428         EVADE_SQUIGGLE
5429         EVADE_BRAKE
5430 */
5431
5432 float   G_collision_time;
5433 vector  G_predicted_pos, G_fire_pos;
5434
5435 /*
5436 void show_firing_diag()
5437 {
5438         float           dot;
5439         vector  v2t;
5440         vector  pos1, pos2;
5441         float           dist;
5442
5443         if (G_collision_time == 0.0f)
5444                 return;
5445
5446         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",
5447                 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));
5448         vm_vec_normalized_dir(&v2t, &G_predicted_pos, &G_fire_pos);
5449         dot = vm_vec_dot(&v2t, &Pl_objp->orient.v.fvec);
5450         mprintf(("Dot of v.fvec and vector to predicted position = %10.7f (%7.3f degrees)\n", dot, acos(dot)*180.0f/3.141592654f));
5451
5452         vm_vec_scale_add(&pos1, &En_objp->pos, &En_objp->phys_info.vel, G_collision_time);
5453         vm_vec_scale_add(&pos2, &G_fire_pos, &Pl_objp->orient.v.fvec, G_collision_time*300.0f);
5454         dist = vm_vec_dist(&pos1, &pos2);
5455
5456         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));
5457 }
5458 */
5459
5460 //      If:
5461 //              flags & WIF_PUNCTURE
5462 //      Then Select a Puncture weapon.
5463 //      Else
5464 //              Select Any ol' weapon.
5465 //      Returns primary_bank index.
5466 int ai_select_primary_weapon(object *objp, object *other_objp, int flags)
5467 {
5468         ship    *shipp = &Ships[objp->instance];
5469         ship_weapon *swp = &shipp->weapons;
5470
5471         //SDL_assert( other_objp != NULL );
5472         SDL_assert( shipp->ship_info_index >= 0 && shipp->ship_info_index < MAX_SHIP_TYPES);
5473
5474         if (flags & WIF_PUNCTURE) {
5475                 if (swp->current_primary_bank >= 0) {
5476                         int     bank_index;
5477
5478                         bank_index = swp->current_primary_bank;
5479
5480                         if (Weapon_info[swp->primary_bank_weapons[bank_index]].wi_flags & WIF_PUNCTURE) {
5481                                 //nprintf(("AI", "%i: Ship %s selecting weapon %s\n", Framecount, Ships[objp->instance].ship_name, Weapon_info[swp->primary_bank_weapons[bank_index]].name));
5482                                 return swp->current_primary_bank;
5483                         }
5484                 }
5485                 for (int i=0; i<swp->num_primary_banks; i++) {
5486                         int     weapon_info_index;
5487
5488                         weapon_info_index = swp->primary_bank_weapons[i];
5489
5490                         if (weapon_info_index > -1){
5491                                 if (Weapon_info[weapon_info_index].wi_flags & WIF_PUNCTURE) {
5492                                         swp->current_primary_bank = i;
5493                                         //nprintf(("AI", "%i: Ship %s selecting weapon %s\n", Framecount, Ships[objp->instance].ship_name, Weapon_info[swp->primary_bank_weapons[i]].name));
5494                                         return i;
5495                                 }
5496                         }
5497                 }
5498                 
5499                 // AL 26-3-98: If we couldn't find a puncture weapon, pick first available weapon if one isn't active
5500                 if ( swp->current_primary_bank < 0 ) {
5501                         if ( swp->num_primary_banks > 0 ) {
5502                                 swp->current_primary_bank = 0;
5503                         }
5504                 }
5505
5506         } else {                //      Don't need to be using a puncture weapon.
5507                 if (swp->current_primary_bank >= 0) {
5508                         if (!(Weapon_info[swp->primary_bank_weapons[swp->current_primary_bank]].wi_flags & WIF_PUNCTURE)){
5509                                 return swp->current_primary_bank;
5510                         }
5511                 }
5512                 for (int i=0; i<swp->num_primary_banks; i++) {
5513                         if (swp->primary_bank_weapons[i] > -1) {
5514                                 if (!(Weapon_info[swp->primary_bank_weapons[i]].wi_flags & WIF_PUNCTURE)) {
5515                                         swp->current_primary_bank = i;
5516                                         nprintf(("AI", "%i: Ship %s selecting weapon %s\n", Framecount, Ships[objp->instance].ship_name, Weapon_info[swp->primary_bank_weapons[i]].name));
5517                                         return i;
5518                                 }
5519                         }
5520                 }
5521                 //      Wasn't able to find a non-puncture weapon.  Stick with what we have.
5522         }
5523
5524         SDL_assert( swp->current_primary_bank != -1 );          // get Alan or Allender
5525
5526         return swp->current_primary_bank;
5527 }
5528
5529 //      --------------------------------------------------------------------------
5530 //      Maybe link primary weapons.
5531 void set_primary_weapon_linkage(object *objp)
5532 {
5533         ship            *shipp;
5534         ai_info *aip;
5535
5536         shipp = &Ships[objp->instance];
5537         aip     = &Ai_info[shipp->ai_index];
5538
5539         shipp->flags &= ~SF_PRIMARY_LINKED;
5540
5541         if (Num_weapons > (int) (MAX_WEAPONS * 0.75f)) {
5542                 if (shipp->flags & SF_PRIMARY_LINKED)
5543                         nprintf(("AI", "Frame %i, ship %s: Unlinking primaries.\n", Framecount, shipp->ship_name));
5544                 shipp->flags &= ~SF_PRIMARY_LINKED;
5545                 return;         //      If low on slots, don't link.
5546         }
5547
5548         shipp->flags &= ~SF_PRIMARY_LINKED;
5549
5550         // AL: ensure target is a ship!
5551         if ( Objects[aip->target_objnum].type == OBJ_SHIP ) {
5552                 // If trying to destroy a big ship (i.e., not disable/disarm), always unleash all weapons
5553                 if ( ship_get_SIF(&Ships[Objects[aip->target_objnum].instance]) & SIF_BIG_SHIP) {
5554                         if ( aip->targeted_subsys == NULL ) {
5555                                 shipp->flags |= SF_PRIMARY_LINKED;
5556                                 shipp->flags |= SF_SECONDARY_DUAL_FIRE;
5557                                 return;
5558                         }
5559                 }
5560         }
5561
5562         // AL 2-11-98: If ship has a disarm or disable goal, don't link unless both weapons are
5563         //                                      puncture weapons
5564         if ( (aip->active_goal != AI_GOAL_NONE) && (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC) ) {
5565                 if ( aip->goals[aip->active_goal].ai_mode & (AI_GOAL_DISABLE_SHIP|AI_GOAL_DISARM_SHIP) ) {
5566                         ship_weapon     *swp;
5567                         swp = &shipp->weapons;
5568                         // only continue if both primaries are puncture weapons
5569                         if ( swp->num_primary_banks == 2 ) {
5570                                 if ( !(Weapon_info[swp->primary_bank_weapons[0]].wi_flags & WIF_PUNCTURE) ) 
5571                                         return;
5572                                 if ( !(Weapon_info[swp->primary_bank_weapons[1]].wi_flags & WIF_PUNCTURE) ) 
5573                                         return;
5574                         }
5575                 }
5576         }
5577
5578         //      Don't want all ships always linking weapons at start, so asynchronize.
5579         if (Missiontime < i2f(30))
5580                 return;
5581         else if (Missiontime < i2f(120)) {
5582                 int r = static_rand((Missiontime >> 17) ^ OBJ_INDEX(objp));
5583                 if ( (r&3) != 0)
5584                         return;
5585         }
5586
5587         if (shipp->weapon_energy > Link_energy_levels_always[Game_skill_level]) {
5588                 shipp->flags |= SF_PRIMARY_LINKED;
5589         } else if (shipp->weapon_energy > Link_energy_levels_maybe[Game_skill_level]) {
5590                 if (objp->hull_strength < Ship_info[shipp->ship_info_index].initial_hull_strength/3.0f)
5591                         shipp->flags |= SF_PRIMARY_LINKED;
5592         }
5593 }
5594
5595 //      --------------------------------------------------------------------------
5596 //      Fire the current primary weapon.
5597 //      *objp is the object to fire from.
5598 void ai_fire_primary_weapon(object *objp)
5599 {
5600         ship                    *shipp = &Ships[objp->instance];
5601         ship_weapon     *swp = &shipp->weapons;
5602         ai_info         *aip;
5603         object          *enemy_objp;
5604
5605         SDL_assert( shipp->ship_info_index >= 0 && shipp->ship_info_index < MAX_SHIP_TYPES);
5606
5607         aip = &Ai_info[shipp->ai_index];
5608
5609         //      If low on slots, fire a little less often.
5610         if (Num_weapons > (int) (0.9f * MAX_WEAPONS)) {
5611                 if (frand() > 0.5f) {
5612                         nprintf(("AI", "Frame %i, %s not fire.\n", Framecount, shipp->ship_name));
5613                         return;
5614                 }
5615         }
5616
5617         if (!Ai_firing_enabled){
5618                 return;
5619         }
5620
5621         if (aip->target_objnum != -1){
5622                 enemy_objp = &Objects[aip->target_objnum];
5623         } else {
5624                 enemy_objp = NULL;
5625         }
5626
5627         if ( (swp->current_primary_bank < 0) || (swp->current_primary_bank >= swp->num_primary_banks) || timestamp_elapsed(aip->primary_select_timestamp)) {
5628                 int     flags = 0;
5629                 // AL 2-11-98: If attacking any subsystem (not just engines), use disrupter weapon
5630 //              if ((aip->targeted_subsys != NULL) && (aip->targeted_subsys->system_info->type == SUBSYSTEM_ENGINE)) {
5631                 if ( aip->targeted_subsys != NULL ) {
5632                         flags = WIF_PUNCTURE;
5633                 }
5634                 ai_select_primary_weapon(objp, enemy_objp, flags);
5635                 ship_primary_changed(shipp);    // AL: maybe send multiplayer information when AI ship changes primaries
5636                 aip->primary_select_timestamp = timestamp(5 * 1000);    //      Maybe change primary weapon five seconds from now.
5637         }
5638
5639         //      If pointing nearly at predicted collision point of target, bash orientation to be perfectly pointing.
5640         float   dot;
5641         vector  v2t;
5642
5643 //      if (!IS_VEC_NULL(&G_predicted_pos)) {
5644         if (!( vm_vec_mag_quick(&G_predicted_pos) < AICODE_SMALL_MAGNITUDE )) {
5645                 if ( !vm_vec_cmp(&G_predicted_pos, &G_fire_pos) ) {
5646                         nprintf(("Warning", "Avoid NULL vector assert.. why are G_predicted_pos and G_fire_pos the same?\n"));
5647                 } else {
5648                         vm_vec_normalized_dir(&v2t, &G_predicted_pos, &G_fire_pos);
5649                         dot = vm_vec_dot(&v2t, &objp->orient.v.fvec);
5650                         if (dot > .998629534f){ //      if within 3.0 degrees of desired heading, bash
5651                                 vm_vector_2_matrix(&objp->orient, &v2t, &objp->orient.v.uvec, NULL);
5652                         }
5653                 }
5654         }
5655
5656         //      Make sure not firing at a protected ship unless firing at a live subsystem.
5657         //      Note: This happens every time the ship tries to fire, perhaps every frame.
5658         //      Should be wrapped in a timestamp, same one that enables it to fire, but that is complicated
5659         //      by multiple banks it can fire from.
5660         if (aip->target_objnum != -1) {
5661                 object  *tobjp = &Objects[aip->target_objnum];
5662                 if (tobjp->flags & OF_PROTECTED) {
5663                         if (aip->targeted_subsys != NULL) {
5664                                 int     type;
5665
5666                                 type = aip->targeted_subsys->system_info->type;
5667                                 if (ship_get_subsystem_strength(&Ships[tobjp->instance], type) == 0.0f) {
5668                                         aip->target_objnum = -1;
5669                                         return;
5670                                 }
5671                         } else {
5672                                 aip->target_objnum = -1;
5673                                 return;
5674                         }
5675                 }
5676         }
5677
5678         //      If enemy is protected, not firing a puncture weapon and enemy's hull is low, don't fire.
5679         if ((enemy_objp != NULL) && (enemy_objp->flags & OF_PROTECTED)) {
5680                 // AL: 3-6-98: Check if current_primary_bank is valid
5681                 if ((enemy_objp->hull_strength < 750.0f) && 
5682                         ((aip->targeted_subsys == NULL) || (enemy_objp->hull_strength < aip->targeted_subsys->current_hits + 50.0f)) &&
5683                         (swp->current_primary_bank >= 0) ) {
5684                         if (!(Weapon_info[swp->primary_bank_weapons[swp->current_primary_bank]].wi_flags & WIF_PUNCTURE)) {
5685                                 //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));
5686                                 swp->next_primary_fire_stamp[swp->current_primary_bank] = timestamp(1000);
5687                                 return;
5688                         }
5689
5690                         /*
5691                         int     num_attacking;
5692                         num_attacking = num_enemies_attacking(enemy_objp-Objects);
5693                         if (enemy_objp->hull_strength / num_attacking < 200.0f) {
5694                                 if (frand() < 0.75f) {
5695                                         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));
5696                                         swp->next_primary_fire_stamp[swp->current_primary_bank] = timestamp(500);
5697                                         return;
5698                                 }
5699                         }
5700                         */
5701                 }
5702         }
5703
5704         set_primary_weapon_linkage(objp);
5705         
5706         // I think this will properly solve the problem
5707         // fire non-streaming weapons
5708         ship_fire_primary(objp, 0);
5709         
5710         // fire streaming weapons
5711         shipp->flags |= SF_TRIGGER_DOWN;
5712         ship_fire_primary(objp, 1);
5713         shipp->flags &= ~SF_TRIGGER_DOWN;
5714 }
5715
5716 //      --------------------------------------------------------------------------
5717 //      Return number of nearby enemy fighters.
5718 //      threshold is the distance within which a ship is considered near.
5719 //
5720 // input:       enemy_team_mask =>      teams that are considered as an enemy
5721 //                              pos                                     =>      world position to measure ship distances from
5722 //                              threshold                       =>      max distance from pos to be considered "near"
5723 //
5724 // exit:                number of ships within threshold units of pos
5725 int num_nearby_fighters(int enemy_team_mask, vector *pos, float threshold)
5726 {
5727         ship_obj        *so;
5728         object  *ship_objp;
5729         int             count = 0;
5730
5731         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
5732
5733                 ship_objp = &Objects[so->objnum];
5734
5735                 if (Ships[ship_objp->instance].team & enemy_team_mask) {
5736                         if (Ship_info[Ships[ship_objp->instance].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER)) {
5737                                 if (vm_vec_dist_quick(pos, &ship_objp->pos) < threshold)
5738                                         count++;
5739                         }
5740                 }
5741         }
5742
5743         return count;
5744 }
5745
5746 //      --------------------------------------------------------------------------
5747 //      Select secondary weapon to fire.
5748 //      Currently, 1/16/98:
5749 //              If 0 secondary weapons available, return -1
5750 //              If 1 available, use it.
5751 //              If 2 or more, if the current weapon is one of them, stick with it, otherwise choose a random one.
5752 //      priority1 and priority2 are Weapon_info[] bitmasks such as WIF_HOMING_ASPECT.  If any weapon has any bit in priority1
5753 //      set, that weapon will be selected.  If not, apply to priority2.  If neither, return -1, meaning no weapon selected.
5754 //      Note, priorityX have default values of -1, meaning if not set, they will match any weapon.
5755 //      Return value:
5756 //              bank index
5757 //      Should do this:
5758 //              Favor aspect seekers when attacking small ships faraway.
5759 //              Favor rapid fire dumbfire when attacking a large ship.
5760 //              Ignore heat seekers because we're not sure how they'll work.
5761 void ai_select_secondary_weapon(object *objp, ship_weapon *swp, int priority1 = -1, int priority2 = -1)
5762 {
5763         int     num_weapon_types;
5764         int     weapon_id_list[MAX_WEAPON_TYPES], weapon_bank_list[MAX_WEAPON_TYPES];
5765         int     i;
5766         int     ignore_mask;
5767         int     initial_bank;
5768
5769         initial_bank = swp->current_secondary_bank;
5770
5771         //      Ignore bombs unless one of the priorities asks for them to be selected.
5772         if (WIF_HUGE & (priority1 | priority2))
5773                 ignore_mask = 0;
5774         else
5775                 ignore_mask = WIF_HUGE;
5776
5777         if (!(WIF_BOMBER_PLUS & (priority1 | priority2)))
5778                 ignore_mask |= WIF_BOMBER_PLUS;
5779
5780 #ifndef NDEBUG
5781         for (i=0; i<MAX_WEAPON_TYPES; i++) {
5782                 weapon_id_list[i] = -1;
5783                 weapon_bank_list[i] = -1;
5784         }
5785 #endif
5786
5787         //      Stuff weapon_bank_list with bank index of available weapons.
5788         num_weapon_types = get_available_secondary_weapons(objp, weapon_id_list, weapon_bank_list);
5789
5790         int     priority2_index = -1;
5791
5792         for (i=0; i<num_weapon_types; i++) {
5793                 int     wi_flags;
5794
5795                 wi_flags = Weapon_info[swp->secondary_bank_weapons[weapon_bank_list[i]]].wi_flags;
5796                 if (!(wi_flags & ignore_mask)) {                                        //      Maybe bombs are illegal.
5797                         if (wi_flags & priority1) {
5798                                 swp->current_secondary_bank = weapon_bank_list[i];                              //      Found first priority, return it.
5799                                 break;
5800                         } else if (wi_flags & priority2)
5801                                 priority2_index = weapon_bank_list[i];  //      Found second priority, but might still find first priority.
5802                 }
5803         }
5804
5805         //      If didn't find anything above, then pick any secondary weapon.
5806         if (i == num_weapon_types) {
5807                 swp->current_secondary_bank = priority2_index;  //      Assume we won't find anything.
5808                 if (priority2_index == -1) {
5809                         for (i=0; i<num_weapon_types; i++) {
5810                                 int     wi_flags;
5811
5812                                 wi_flags = Weapon_info[swp->secondary_bank_weapons[weapon_bank_list[i]]].wi_flags;
5813                                 if (!(wi_flags & ignore_mask)) {                                        //      Maybe bombs are illegal.
5814                                         if (swp->secondary_bank_ammo[i] > 0) {
5815                                                 swp->current_secondary_bank = i;
5816                                                 break;
5817                                         }
5818                                 }
5819                         }
5820                 }
5821         }
5822
5823         //      If switched banks, force reacquisition of aspect lock.
5824         if (swp->current_secondary_bank != initial_bank) {
5825                 ai_info *aip = &Ai_info[Ships[objp->instance].ai_index];
5826                 
5827                 aip->aspect_locked_time = 0.0f;
5828                 aip->current_target_is_locked = 0;
5829         }
5830
5831
5832         ship_secondary_changed(&Ships[objp->instance]); // AL: let multiplayer know if secondary bank has changed
5833         // nprintf(("AI", "Ship %s selected weapon %s\n", Ships[objp->instance].ship_name, Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]].name));
5834 }
5835
5836 //      Return number of objects homing on object *target_objp
5837 int compute_num_homing_objects(object *target_objp)
5838 {
5839         object  *objp;
5840         int             count = 0;
5841
5842         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
5843                 if (objp->type == OBJ_WEAPON) {
5844                         if (Weapon_info[Weapons[objp->instance].weapon_info_index].wi_flags & WIF_HOMING) {
5845                                 if (Weapons[objp->instance].homing_object == target_objp) {
5846                                         count++;
5847                                 }
5848                         }
5849                 }
5850         }
5851
5852         return count;
5853 }
5854
5855 //      Object *firing_objp just fired weapon weapon_index (index in Weapon_info).
5856 //      If it's a shockwave weapon, tell your team about it!
5857 void ai_maybe_announce_shockwave_weapon(object *firing_objp, int weapon_index)
5858 {
5859         if ((firing_objp->type == OBJ_SHIP) && (Weapon_info[weapon_index].shockwave_speed > 0.0f)) {
5860                 ship_obj        *so;
5861                 int             firing_ship_team;
5862
5863                 firing_ship_team = Ships[firing_objp->instance].team;
5864
5865                 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
5866                         object  *A = &Objects[so->objnum];
5867                         SDL_assert(A->type == OBJ_SHIP);
5868
5869                         if (Ships[A->instance].team == firing_ship_team) {
5870                                 ai_info *aip = &Ai_info[Ships[A->instance].ai_index];
5871                                 // AL 1-5-98: only avoid shockwave if not docked or repairing
5872                                 if ( !(aip->ai_flags & (AIF_DOCKED|AIF_BEING_REPAIRED)) ) {
5873                                         aip->ai_flags |= AIF_AVOID_SHOCKWAVE_WEAPON;
5874                                 }
5875                         }
5876                 }
5877         }
5878 }
5879
5880 //      Return total payload of all incoming missiles.
5881 float compute_incoming_payload(object *target_objp)
5882 {
5883         missile_obj     *mo;
5884         float                   payload = 0.0f;
5885
5886         for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
5887                 object  *objp;
5888
5889                 objp = &Objects[mo->objnum];
5890                 SDL_assert(objp->type == OBJ_WEAPON);
5891                 if (Weapons[objp->instance].homing_object == target_objp) {
5892                         payload += Weapon_info[Weapons[objp->instance].weapon_info_index].damage;
5893                 }
5894         }
5895
5896         return payload;
5897 }
5898
5899 //      --------------------------------------------------------------------------
5900 //      Return true if OK for *aip to fire its current weapon at its current target.
5901 //      Only reason this function returns false is:
5902 //              weapon is a homer
5903 //              targeted at player
5904 //                      OR:     player has too many homers targeted at him
5905 //                                      Missiontime in that dead zone in which can't fire at this player
5906 //      Note: If player is attacking a ship, that ship is allowed to fire at player.  Otherwise, we get in a situation in which
5907 //      player is attacking a large ship, but that large ship is not defending itself with missiles.
5908 int check_ok_to_fire(int objnum, int target_objnum, weapon_info *wip)
5909 {
5910         int     num_homers = 0;
5911         object  *tobjp = &Objects[target_objnum];
5912
5913         if (target_objnum > -1) {
5914                 // AL 3-4-98: Ensure objp target is a ship first 
5915                 if ( tobjp->type == OBJ_SHIP ) {
5916
5917                         // should not get this far. check if ship is protected from beam and weapon is type beam
5918                         if ( (wip->wi_flags & WIF_BEAM) && (tobjp->flags & OF_BEAM_PROTECTED) ) {
5919                                 Int3();
5920                                 return 0;
5921                         }
5922                         if (Ship_info[Ships[tobjp->instance].ship_info_index].flags & SIF_SMALL_SHIP) {
5923                                 num_homers = compute_num_homing_objects(&Objects[target_objnum]);
5924                         }
5925                 }
5926
5927                 //      If player, maybe fire based on Skill_level and number of incoming weapons.
5928                 //      If non-player, maybe fire based on payload of incoming weapons.
5929                 if (wip->wi_flags & WIF_HOMING) {
5930                         if ((target_objnum > -1) && (tobjp->flags & OF_PLAYER_SHIP)) {
5931                                 if (Ai_info[Ships[tobjp->instance].ai_index].target_objnum != objnum) {
5932                                         //      Don't allow AI ships to fire at player for fixed periods of time based on skill level.
5933                                         //      With 5 skill levels, at Very Easy, they fire in 1/7 of every 10 second interval.
5934                                         //      At Easy, 2/7...at Expert, 5/7
5935                                         int t = ((Missiontime /(65536*10)) ^ target_objnum ^ 0x01) % (NUM_SKILL_LEVELS+2);
5936                                         if (t > Game_skill_level) {
5937                                                 //nprintf(("AI", "Not OK to fire homer at time thing %i\n", t));
5938                                                 return 0;
5939                                         }
5940                                 }
5941                                 //nprintf(("AI", " IS OK to fire homer at time thing %i ***\n", t));
5942                                 int     swarmers = 0;
5943                                 if (wip->wi_flags & WIF_SWARM)
5944                                         swarmers = 2;   //      Note, always want to be able to fire swarmers if no currently incident homers.
5945                                 if (Max_allowed_player_homers[Game_skill_level] < num_homers + swarmers) {
5946                                         return 0;
5947                                 }
5948                         } else if (num_homers > 3) {
5949                                 float   incoming_payload;
5950
5951                                 incoming_payload = compute_incoming_payload(&Objects[target_objnum]);
5952
5953                                 if (incoming_payload > tobjp->hull_strength) {
5954                                         return 0;
5955                                 }
5956                         }
5957                 }
5958         }
5959
5960         return 1;
5961 }
5962
5963 //      --------------------------------------------------------------------------
5964 //      Fire a secondary weapon.
5965 //      Maybe choose to fire a different one.
5966 //      priority1 and priority2 are optional parameters with defaults = -1
5967 int ai_fire_secondary_weapon(object *objp, int priority1, int priority2)
5968 {
5969         ship_weapon *swp;
5970         ship    *shipp;
5971         int             current_bank;
5972         int             rval = 0;
5973
5974 #ifndef NDEBUG
5975         if (!Ai_firing_enabled)
5976                 return rval;
5977 #endif
5978
5979         SDL_assert( objp != NULL );
5980         SDL_assert(objp->type == OBJ_SHIP);
5981         shipp = &Ships[objp->instance];
5982         swp = &shipp->weapons;
5983
5984         //      Select secondary weapon.
5985         current_bank = swp->current_secondary_bank; //ai_select_secondary_weapon(objp, swp, priority1, priority2);
5986
5987         //nprintf(("AI", "Frame %i: Current bank = %i, ammo remaining = %i\n", Framecount, current_bank, swp->secondary_bank_ammo[current_bank]));
5988         if (current_bank == -1) {
5989                 swp->next_secondary_fire_stamp[current_bank] = timestamp(500);
5990                 return rval;
5991         }
5992
5993         SDL_assert(current_bank < shipp->weapons.num_secondary_banks);
5994
5995         weapon_info     *wip = &Weapon_info[shipp->weapons.secondary_bank_weapons[current_bank]];
5996
5997         if ((wip->wi_flags & WIF_HOMING_ASPECT) && (!Ai_info[shipp->ai_index].current_target_is_locked)) {
5998                 //nprintf(("AI", "Not firing secondary weapon because not aspect locked.\n"));
5999                 swp->next_secondary_fire_stamp[current_bank] = timestamp(250);
6000         } else if ((wip->wi_flags & WIF_BOMB) || (vm_vec_dist_quick(&objp->pos, &En_objp->pos) > 50.0f)) {
6001                 //      This might look dumb, firing a bomb even if closer than 50 meters, but the reason is, if you're carrying
6002                 //      bombs, delivering them is probably more important than surviving.
6003                 ai_info *aip;
6004
6005                 aip = &Ai_info[shipp->ai_index];
6006                 
6007                 //      Note, maybe don't fire if firing at player and any homers yet fired.
6008                 //      Decreasing chance to fire the more homers are incoming on player.
6009                 if (check_ok_to_fire(OBJ_INDEX(objp), aip->target_objnum, wip)) {
6010                         if (ship_fire_secondary(objp)) {
6011                                 rval = 1;
6012                                 swp->next_secondary_fire_stamp[current_bank] = timestamp(500);
6013                                 //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));
6014                         }
6015
6016                 } else {
6017                         swp->next_secondary_fire_stamp[current_bank] = timestamp(500);
6018                 }
6019         }
6020
6021         return rval;
6022 }
6023
6024 //      Return true if it looks like obj1, if continuing to move along current vector, will
6025 //      collide with obj2.
6026 int might_collide_with_ship(object *obj1, object *obj2, float dot_to_enemy, float dist_to_enemy, float duration)
6027 {
6028         if (obj1->phys_info.speed * duration + 2*(obj1->radius + obj2->radius) > dist_to_enemy)
6029                 if (dot_to_enemy > 0.8f - 2*(obj1->radius + obj2->radius)/dist_to_enemy)
6030                         return objects_will_collide(obj1, obj2, duration, 2.0f);
6031
6032 //              BABY - 
6033 //              CONDITION 1, dist_to_enemy < o1_rad + o2_rad + (obj1.speed + obj2.speed) * time + 50
6034         
6035         return 0;
6036
6037 }
6038
6039 //      --------------------------------------------------------------------------
6040 //      Return true if ship *objp firing a laser believes it will hit a teammate.
6041 int might_hit_teammate(object *firing_objp)
6042 {
6043         int             team;
6044         object  *objp;
6045         ship_obj        *so;
6046
6047         team = Ships[firing_objp->instance].team;
6048
6049         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
6050                 objp = &Objects[so->objnum];
6051                 if (Ships[objp->instance].team == team) {
6052                         float           dist, dot;
6053                         vector  vec_to_objp;
6054
6055                         vm_vec_sub(&vec_to_objp, &firing_objp->pos, &objp->pos);
6056                         dist = vm_vec_mag_quick(&vec_to_objp);
6057                         dot = vm_vec_dot(&firing_objp->orient.v.fvec, &vec_to_objp)/dist;
6058                         if (might_collide_with_ship(firing_objp, objp, dot, dist, 2.0f))
6059                                 return 1;
6060                 }
6061         }
6062
6063         return 0;
6064
6065 }
6066
6067 //int   Team_not_fire_count=0, Team_hit_count = 0;
6068
6069 void render_all_ship_bay_paths(object *objp)
6070 {
6071         int             i,j,color;
6072         ship            *sp = &Ships[objp->instance];
6073         polymodel       *pm;
6074         model_path      *mp;
6075
6076         pm = model_get(sp->modelnum);
6077         vector  global_path_point;
6078         vertex  v, prev_vertex;
6079
6080         if ( pm->ship_bay == NULL )
6081                 return;
6082
6083         for ( i = 0; i < pm->ship_bay->num_paths; i++ ) {
6084                 mp = &pm->paths[pm->ship_bay->paths[i]];
6085
6086                 for ( j = 0; j < mp->nverts; j++ ) {
6087                         vm_vec_unrotate(&global_path_point, &mp->verts[j].pos, &objp->orient);
6088                         vm_vec_add2(&global_path_point, &objp->pos);
6089                         g3_rotate_vertex(&v, &global_path_point);
6090                         color = 255 - j*50;
6091                         if ( color < 50 ) 
6092                                 color = 100;
6093                         gr_set_color(0, color, 0);
6094
6095                         if ( j == mp->nverts-1 ) {
6096                                 gr_set_color(255, 0, 0);
6097                         }
6098
6099                         g3_draw_sphere( &v, 1.5f);
6100
6101                         if ( j > 0 )
6102                                 g3_draw_line(&v, &prev_vertex);
6103
6104                         prev_vertex = v;
6105         
6106                 }
6107         }
6108 }
6109
6110 // debug function to show all path points associated with an object
6111 void render_all_subsys_paths(object *objp)
6112 {
6113         int             i,j,color;
6114         ship            *sp = &Ships[objp->instance];
6115         polymodel       *pm;
6116         model_path      *mp;
6117
6118         pm = model_get(sp->modelnum);
6119         vector  global_path_point;
6120         vertex  v, prev_vertex;
6121
6122         if ( pm->ship_bay == NULL )
6123                 return;
6124
6125         for ( i = 0; i < pm->n_paths; i++ ) {
6126                 mp = &pm->paths[i];
6127                 for ( j = 0; j < mp->nverts; j++ ) {
6128                         vm_vec_unrotate(&global_path_point, &mp->verts[j].pos, &objp->orient);
6129                         vm_vec_add2(&global_path_point, &objp->pos);
6130                         g3_rotate_vertex(&v, &global_path_point);
6131                         color = 255 - j*50;
6132                         if ( color < 50 ) 
6133                                 color = 100;
6134                         gr_set_color(0, color, 0);
6135
6136                         if ( j == mp->nverts-1 ) {
6137                                 gr_set_color(255, 0, 0);
6138                         }
6139
6140                         g3_draw_sphere( &v, 1.5f);
6141
6142                         if ( j > 0 )
6143                                 g3_draw_line(&v, &prev_vertex);
6144
6145                         prev_vertex = v;
6146                 }
6147         }
6148 }
6149
6150 void render_path_points(object *objp)
6151 {
6152         ship            *shipp = &Ships[objp->instance];
6153         ai_info *aip = &Ai_info[shipp->ai_index];
6154         object  *dobjp;
6155         polymodel       *pm;
6156
6157         render_all_subsys_paths(objp);
6158         render_all_ship_bay_paths(objp);
6159
6160         if (aip->goal_objnum < 0)
6161                 return;
6162
6163         dobjp = &Objects[aip->goal_objnum];
6164         pm = model_get(Ships[dobjp->instance].modelnum);
6165         vector  dock_point, global_dock_point;
6166         vertex  v;
6167
6168         ship_model_start(&Objects[aip->goal_objnum]);
6169         if (pm->n_docks) {
6170                 dock_point = pm->docking_bays[0].pnt[0];
6171                 model_find_world_point(&global_dock_point, &dock_point, Ships[dobjp->instance].modelnum, 0, &dobjp->orient, &dobjp->pos );
6172                 g3_rotate_vertex(&v, &global_dock_point);
6173                 gr_set_color(255, 255, 255);
6174                 g3_draw_sphere( &v, 1.5f);
6175         }
6176
6177         if (aip->path_start != -1) {
6178                 vertex          prev_vertex;
6179                 pnode                   *pp = &Path_points[aip->path_start];
6180                 int                     num_points = aip->path_length;
6181                 int                     i;
6182
6183                 for (i=0; i<num_points; i++) {
6184                         vertex  v0;
6185
6186                         g3_rotate_vertex( &v0, &pp->pos );
6187
6188                         gr_set_color(0, 128, 96);
6189                         if (i != 0)
6190                                 g3_draw_line(&v0, &prev_vertex);
6191
6192                         if (pp-Path_points == aip->path_cur)
6193                                 gr_set_color(255,255,0);
6194                         
6195                         g3_draw_sphere( &v0, 4.5f);
6196
6197                         //      Connect all the turrets that can fire upon this point to this point.
6198 /*                      if (0) { //pp->path_index != -1) {
6199                                 model_path      *pmp;
6200                                 mp_vert         *pmpv;
6201
6202                                 get_base_path_info(pp->path_index, aip->goal_objnum, &pmp, &pmpv);
6203
6204                                 if (pmpv->nturrets) {
6205                                         for (int j = 0; j<pmpv->nturrets; j++) {
6206                                                 vertex  v1;
6207                                                 vector  turret_pos;
6208                                                 ship_subsys     *ssp;
6209
6210                                                 ssp = ship_get_indexed_subsys(&Ships[Objects[aip->goal_objnum].instance], pmpv->turret_ids[j]);
6211
6212 model_find_world_point(&turret_pos, &ssp->system_info->pnt, Ships[dobjp->instance].modelnum, 0, &dobjp->orient, &dobjp->pos );
6213         
6214                                                 g3_rotate_vertex(&v1, &turret_pos);
6215                                                 gr_set_color(255, 255, 0);
6216                                                 g3_draw_line(&v0, &v1);
6217                                                 g3_draw_sphere( &v1, 1.5f);
6218                                         }
6219                                 }
6220                         } */
6221
6222                         prev_vertex = v0;
6223
6224                         pp++;
6225                 }
6226         }
6227
6228         ship_model_stop(&Objects[aip->goal_objnum]);
6229 }
6230
6231 // Return the distance that the current AI weapon will travel
6232 float ai_get_weapon_dist(ship_weapon *swp)
6233 {
6234         int     bank_num, weapon_num;
6235
6236         bank_num = swp->current_primary_bank;
6237         weapon_num = swp->primary_bank_weapons[bank_num];
6238
6239         //      If weapon_num is illegal, return a reasonable value.  A valid weapon
6240         //      will get selected when this ship tries to fire.
6241         if (weapon_num == -1) {
6242                 // Int3();
6243                 return 1000.0f;
6244         }
6245
6246         return Weapon_info[weapon_num].max_speed * Weapon_info[weapon_num].lifetime;
6247 }
6248
6249 float ai_get_weapon_speed(ship_weapon *swp)
6250 {
6251         int     bank_num, weapon_num;
6252
6253         bank_num = swp->current_primary_bank;
6254         if (bank_num < 0)
6255                 return 100.0f;
6256
6257         weapon_num = swp->primary_bank_weapons[bank_num];
6258
6259         if (weapon_num == -1) {
6260                 //Int3();
6261                 return 100.0f;
6262         }
6263
6264         return Weapon_info[weapon_num].max_speed;
6265 }
6266
6267 //      Compute the predicted position of a ship to be fired upon from a turret.
6268 //      This is based on position of firing gun, enemy object, weapon speed and skill level constraints.
6269 //      Return value in *predicted_enemy_pos.
6270 //      Also, stuff globals G_predicted_pos, G_collision_time and G_fire_pos.
6271 //      *pobjp          object firing the weapon
6272 //      *eobjp          object being fired upon
6273 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)
6274 {
6275         ship    *shipp = &Ships[pobjp->instance];
6276         float   range_time;
6277
6278         //weapon_speed = ai_get_weapon_speed(&shipp->weapons);
6279
6280         if (weapon_speed < 1.0f)
6281                 weapon_speed = 1.0f;
6282
6283         range_time = 2.0f;
6284
6285         //      Make it take longer for enemies to get player's allies in range based on skill level.
6286         if (Ships[pobjp->instance].team != Ships[Player_obj->instance].team)
6287                 range_time += In_range_time[Game_skill_level];
6288
6289         //nprintf(("AI", "time enemy in range = %7.3f\n", aip->time_enemy_in_range));
6290
6291         if (time_enemy_in_range < range_time) {
6292                 float   dist;
6293
6294                 dist = vm_vec_dist_quick(&pobjp->pos, enemy_pos);
6295                 vm_vec_scale_add(predicted_enemy_pos, enemy_pos, enemy_vel, time_enemy_in_range * dist/weapon_speed);
6296         } else {
6297                 float   collision_time, scale;
6298                 vector  rand_vec;
6299                 ai_info *aip = &Ai_info[shipp->ai_index];
6300
6301                 collision_time = compute_collision_time(enemy_pos, enemy_vel, gun_pos, weapon_speed);
6302
6303                 if (collision_time == 0.0f){
6304                         collision_time = 100.0f;
6305                 }
6306
6307                 vm_vec_scale_add(predicted_enemy_pos, enemy_pos, enemy_vel, collision_time);
6308                 if (time_enemy_in_range > 2*range_time){
6309                         scale = (1.0f - aip->ai_accuracy) * 4.0f;
6310                 } else {
6311                         scale = (1.0f - aip->ai_accuracy) * 4.0f * (1.0f + 4.0f * (1.0f - time_enemy_in_range/(2*range_time)));
6312                 }               
6313
6314                 static_randvec(((pobjp-Objects) ^ (Missiontime >> 16)) & 7, &rand_vec);
6315
6316                 vm_vec_scale_add2(predicted_enemy_pos, &rand_vec, scale);
6317                 G_collision_time = collision_time;
6318                 G_fire_pos = *gun_pos;
6319         }
6320
6321         G_predicted_pos = *predicted_enemy_pos;
6322 }
6323
6324 //      Compute the predicted position of a ship to be fired upon.
6325 //      This is based on current position of firing object, enemy object, relative position of gun on firing object,
6326 //      weapon speed and skill level constraints.
6327 //      Return value in *predicted_enemy_pos.
6328 //      Also, stuff globals G_predicted_pos, G_collision_time and G_fire_pos.
6329 void set_predicted_enemy_pos(vector *predicted_enemy_pos, object *pobjp, object *eobjp, ai_info *aip)
6330 {
6331         float   weapon_speed, range_time;
6332         ship    *shipp = &Ships[pobjp->instance];
6333
6334         weapon_speed = ai_get_weapon_speed(&shipp->weapons);
6335         weapon_speed = max(weapon_speed, 1.0f);         // set not less than 1
6336
6337         range_time = 2.0f;
6338
6339         //      Make it take longer for enemies to get player's allies in range based on skill level.
6340         // but don't bias team v. team missions
6341         if ( !((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_TEAM)) ) {
6342                 if (Ships[pobjp->instance].team != Ships[Player_obj->instance].team) {
6343                         range_time += In_range_time[Game_skill_level];
6344                 }
6345         }
6346         //nprintf(("AI", "time enemy in range = %7.3f\n", aip->time_enemy_in_range));
6347
6348         if (aip->time_enemy_in_range < range_time) {
6349                 float   dist;
6350
6351                 dist = vm_vec_dist_quick(&pobjp->pos, &eobjp->pos);
6352                 vm_vec_scale_add(predicted_enemy_pos, &eobjp->pos, &eobjp->phys_info.vel, aip->time_enemy_in_range * dist/weapon_speed);
6353         } else {
6354                 float   collision_time;
6355                 vector  gun_pos, pnt;
6356                 polymodel *po = model_get( Ship_info[shipp->ship_info_index].modelnum );
6357
6358                 //      Compute position of gun in absolute space and use that as fire position.
6359                 if(po->gun_banks != NULL){
6360                         pnt = po->gun_banks[0].pnt[0];
6361                 } else {
6362                         pnt = Objects[shipp->objnum].pos;
6363                 }
6364                 vm_vec_unrotate(&gun_pos, &pnt, &pobjp->orient);
6365                 vm_vec_add2(&gun_pos, &pobjp->pos);
6366
6367                 collision_time = compute_collision_time(&eobjp->pos, &eobjp->phys_info.vel, &gun_pos, weapon_speed);
6368
6369                 if (collision_time == 0.0f) {
6370                         collision_time = 100.0f;
6371                 }
6372
6373                 vm_vec_scale_add(predicted_enemy_pos, &eobjp->pos, &eobjp->phys_info.vel, collision_time);
6374
6375                 // set globals
6376                 G_collision_time = collision_time;
6377                 G_fire_pos = gun_pos;
6378         }
6379
6380         // Now add error terms (1) regular aim (2) EMP (3) stealth
6381         float scale = 0.0f;
6382         vector rand_vec;
6383
6384         // regular skill level error in aim
6385         if (aip->time_enemy_in_range > 2*range_time) {
6386                 scale = (1.0f - aip->ai_accuracy) * 4.0f;
6387         } else {
6388                 scale = (1.0f - aip->ai_accuracy) * 4.0f * (1.0f + 4.0f * (1.0f - aip->time_enemy_in_range/(2*range_time)));
6389         }
6390
6391         // if this ship is under the effect of an EMP blast, throw his aim off a bit
6392         if (shipp->emp_intensity > 0.0f) {
6393                 // never go lower than 1/2 of the EMP effect max, otherwise things aren't noticeable
6394                 scale += (MAX_EMP_INACCURACY * (shipp->emp_intensity < 0.5f ? 0.5f : shipp->emp_intensity));
6395                 mprintf(("AI miss scale factor (EMP) %f\n",scale));
6396         }
6397
6398         // if stealthy ship, throw his aim off, more when farther away and when dot is small
6399         if ( aip->ai_flags & AIF_STEALTH_PURSIUT ) {
6400                 float dist = vm_vec_dist_quick(&pobjp->pos, &eobjp->pos);
6401                 vector temp;
6402                 vm_vec_sub(&temp, &eobjp->pos, &pobjp->pos);
6403                 vm_vec_normalize_quick(&temp);
6404                 float dot = vm_vec_dotprod(&temp, &pobjp->orient.v.fvec);
6405                 float st_err = 3.0f * (1.4f - dot) * (1.0f + dist / (get_skill_stealth_dist_scaler() * STEALTH_MAX_VIEW_DIST)) * (1 - aip->ai_accuracy);
6406                 scale += st_err;
6407                 // mprintf(("error term: %.1f, total %.1f, dot %.3f\n", st_err, scale, dot));
6408         }
6409
6410         // get a random vector that changes slowly over time (1x / sec)
6411         static_randvec(((pobjp-Objects) ^ (Missiontime >> 16)) & 7, &rand_vec);
6412
6413         vm_vec_scale_add2(predicted_enemy_pos, &rand_vec, scale);
6414
6415         // set global
6416         G_predicted_pos = *predicted_enemy_pos;
6417 }
6418
6419 //      Handler of submode for Chase.  Go into a continuous turn for awhile.
6420 void ai_chase_ct()
6421 {
6422         vector          tvec;
6423         ship_info       *sip;
6424         ai_info         *aip;
6425
6426         SDL_assert(Ships[Pl_objp->instance].ship_info_index >= 0);
6427         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6428         SDL_assert(Ships[Pl_objp->instance].ai_index >= 0);
6429         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
6430
6431         //      Make a continuous turn towards any combination of possibly negated
6432         // up and right vectors.
6433         tvec = Pl_objp->pos;
6434
6435         if (aip->submode_parm0 & 0x01)
6436                 vm_vec_add2(&tvec, &Pl_objp->orient.v.rvec);
6437         if (aip->submode_parm0 & 0x02)
6438                 vm_vec_sub2(&tvec, &Pl_objp->orient.v.rvec);
6439         if (aip->submode_parm0 & 0x04)
6440                 vm_vec_add2(&tvec, &Pl_objp->orient.v.uvec);
6441         if (aip->submode_parm0 & 0x08)
6442                 vm_vec_sub2(&tvec, &Pl_objp->orient.v.uvec);
6443
6444         //      Detect degenerate cases that cause tvec to be same as player pos.
6445         if (vm_vec_dist_quick(&tvec, &Pl_objp->pos) < 0.1f) {
6446                 aip->submode_parm0 &= 0x05;
6447                 if (aip->submode_parm0 == 0)
6448                         aip->submode_parm0 = 1;
6449                 vm_vec_add2(&tvec, &Pl_objp->orient.v.rvec);
6450         }
6451
6452         ai_turn_towards_vector(&tvec, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6453         accelerate_ship(aip, 1.0f);
6454 }
6455
6456 //      ATTACK submode handler for chase mode.
6457 void ai_chase_eb(ai_info *aip, ship_info *sip, vector *predicted_enemy_pos, float dist_to_enemy)
6458 {
6459         vector  _pep;
6460         float           dot_to_enemy, dot_from_enemy;
6461
6462         compute_dots(Pl_objp, En_objp, &dot_to_enemy, &dot_from_enemy);
6463
6464         //      If we're trying to slow down to get behind, then point to turn towards is different.
6465         _pep = *predicted_enemy_pos;
6466         if ((dot_to_enemy > dot_from_enemy + 0.1f) || (dot_to_enemy > 0.9f))
6467                 vm_vec_scale_add(&_pep, &Pl_objp->pos, &En_objp->orient.v.fvec, 100.0f);
6468
6469         ai_turn_towards_vector(&_pep, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6470
6471         accelerate_ship(aip, 0.0f);
6472 }
6473
6474 //      Return time until weapon_objp might hit ship_objp.
6475 //      Assumes ship_objp is not moving.
6476 //      Returns negative time if not going to hit.
6477 //      This is a very approximate function, but is pretty fast.
6478 float ai_endangered_time(object *ship_objp, object *weapon_objp)
6479 {
6480         float           to_dot, from_dot, dist;
6481
6482         dist = compute_dots(ship_objp, weapon_objp, &to_dot, &from_dot);
6483
6484         //      Note, this is bogus.  It assumes only the weapon is moving.
6485         //      Only proceed if weapon sort of pointing at object and object pointing towards or away from weapon
6486         //      (Ie, if object moving at right angle to weapon, just continue for now...)
6487         if (weapon_objp->phys_info.speed < 1.0f)
6488                 return dist + 1.0f;
6489         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))
6490                 return dist / weapon_objp->phys_info.speed;
6491         else
6492                 return -1.0f;
6493 }
6494
6495 //      Return time until danger weapon could hit this ai object.
6496 //      Return negative time if not endangered.
6497 float ai_endangered_by_weapon(ai_info *aip)
6498 {
6499         object  *weapon_objp;
6500
6501         if (aip->danger_weapon_objnum == -1) {
6502                 return -1.0f;
6503         }
6504
6505         weapon_objp = &Objects[aip->danger_weapon_objnum];
6506
6507         if (weapon_objp->signature != aip->danger_weapon_signature) {
6508                 aip->danger_weapon_objnum = -1;
6509                 return -1.0f;
6510         }
6511
6512         return ai_endangered_time(&Objects[Ships[aip->shipnum].objnum], weapon_objp);
6513 }
6514
6515 //      Return true if this ship is near full strength.
6516 int ai_near_full_strength(object *objp, ship_info *sip)
6517 {
6518         return (objp->hull_strength/sip->initial_hull_strength > 0.9f) || (get_shield_strength(objp)/sip->shields > 0.8f);
6519 }
6520                                 
6521 //      Set acceleration while in attack mode.
6522 void attack_set_accel(ai_info *aip, float dist_to_enemy, float dot_to_enemy, float dot_from_enemy)
6523 {
6524         float   speed_ratio;
6525
6526         if (En_objp->phys_info.speed > 1.0f)
6527                 speed_ratio = Pl_objp->phys_info.speed/En_objp->phys_info.speed;
6528         else
6529                 speed_ratio = 5.0f;
6530
6531         //      Sometimes, told to attack slowly.  Allows to get in more hits.
6532         if (aip->ai_flags & AIF_ATTACK_SLOWLY) {
6533                 if ((dist_to_enemy > 200.0f) && (dist_to_enemy < 800.0f)) {
6534                         if ((dot_from_enemy < 0.9f) || ai_near_full_strength(Pl_objp, &Ship_info[Ships[Pl_objp->instance].ship_info_index])) {
6535                                 //nprintf(("AI", " slowly "));
6536                                 accelerate_ship(aip, max(1.0f - (dist_to_enemy-200.0f)/600.0f, 0.1f));
6537                                 return;
6538                         }
6539                 } else
6540                         aip->ai_flags &= ~AIF_ATTACK_SLOWLY;
6541         }
6542
6543         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) {
6544                 //nprintf(("AI", "1"));
6545                 if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
6546                         if (dist_to_enemy > 800.0f) {
6547                                 if (!( Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
6548                                         float percent_left;
6549                                         ship    *shipp;
6550                                         ship_info *sip;
6551
6552                                         shipp = &Ships[Pl_objp->instance];
6553                                         sip = &Ship_info[shipp->ship_info_index];
6554
6555                                         if (sip->afterburner_fuel_capacity > 0.0f) {
6556                                                 percent_left = 100.0f * shipp->afterburner_fuel / sip->afterburner_fuel_capacity;
6557                                                 if (percent_left > 30.0f + ((Pl_objp-Objects) & 0x0f)) {
6558                                                         afterburners_start(Pl_objp);
6559                                                         aip->afterburner_stop_time = Missiontime + F1_0 + static_rand(Pl_objp-Objects)/4;
6560                                                 }
6561                                         }
6562                                 }
6563                         }
6564                 }
6565
6566                 accelerate_ship(aip, 1.0f);
6567         } else if ((Missiontime - aip->last_hit_time > F1_0*7)
6568                 && (En_objp->phys_info.speed < 10.0f) 
6569                 && (dist_to_enemy > 25.0f) 
6570                 && (dot_to_enemy > 0.8f)
6571                 && (dot_from_enemy < 0.8f)) {
6572                 accelerate_ship(aip, 0.0f);             //      No one attacking us, so don't need to move.
6573         } else if ((dot_from_enemy < 0.25f) && (dot_to_enemy > 0.5f)) {
6574                 set_accel_for_target_speed(Pl_objp, En_objp->phys_info.speed);
6575         } else if (Pl_objp->phys_info.speed < 15.0f) {
6576                 accelerate_ship(aip, 1.0f);
6577         } else if (Pl_objp->phys_info.speed > En_objp->phys_info.speed - 1.0f) {
6578                 if (dot_from_enemy > 0.75f)
6579                         accelerate_ship(aip, 1.0f);
6580                 else
6581                         set_accel_for_target_speed(Pl_objp, En_objp->phys_info.speed*0.75f + 3.0f);
6582         } else {
6583                 change_acceleration(aip, 0.5f);
6584         }
6585 }
6586
6587 //      Pl_objp (aip) tries to get behind En_objp.
6588 //      New on 2/21/98: If this ship can move backwards and slide, maybe do that to get behind.
6589 void get_behind_ship(ai_info *aip, ship_info *sip, float dist_to_enemy)
6590 {
6591         vector  new_pos;
6592         float           dot;
6593         vector  vec_from_enemy;
6594
6595         vm_vec_normalized_dir(&vec_from_enemy, &Pl_objp->pos, &En_objp->pos);
6596
6597         vm_vec_scale_add(&new_pos, &En_objp->pos, &En_objp->orient.v.fvec, -100.0f);            //      Pick point 100 units behind.
6598         ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6599
6600         dot = vm_vec_dot(&vec_from_enemy, &En_objp->orient.v.fvec);
6601
6602         if (dot > 0.25f) {
6603                 accelerate_ship(aip, 1.0f);
6604         } else {
6605                 accelerate_ship(aip, (dot + 1.0f)/2.0f);
6606         }
6607 }
6608
6609 int avoid_player(object *objp, vector *goal_pos)
6610 {
6611         maybe_avoid_player(Pl_objp, goal_pos);
6612         ai_info *aip = &Ai_info[Ships[objp->instance].ai_index];
6613
6614         if (aip->ai_flags & AIF_AVOIDING_SMALL_SHIP) {
6615                 ship_info *sip = &Ship_info[Ships[objp->instance].ship_info_index];
6616
6617                 if (aip->ai_flags & AIF_AVOIDING_SMALL_SHIP) {
6618                         ai_turn_towards_vector(&aip->avoid_goal_point, objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6619                         accelerate_ship(aip, 0.5f);
6620                         return 1;
6621                 }
6622         }
6623
6624         return 0;
6625 }
6626
6627 //      Determine if a cylinder of width radius from p0 to p1 will collide with big_objp.
6628 //      If so, stuff *collision_point.
6629 int will_collide_pp(vector *p0, vector *p1, float radius, object *big_objp, vector *collision_point)
6630 {
6631         mc_info mc;
6632
6633         mc.model_num = Ships[big_objp->instance].modelnum;              // Fill in the model to check
6634         mc.orient = &big_objp->orient;                  // The object's orient
6635         mc.pos = &big_objp->pos;                                        // The object's position
6636         mc.p0 = p0;                                                                             // Point 1 of ray to check
6637         mc.p1 = p1;
6638         mc.flags = MC_CHECK_MODEL | MC_CHECK_SPHERELINE | MC_SUBMODEL;                                  // flags
6639
6640         mc.radius = radius;
6641
6642         // Only check the 2nd lowest hull object
6643         polymodel *pm = model_get(Ships[big_objp->instance].modelnum);
6644         mc.submodel_num = pm->detail[0]; //pm->submodel->num_details-2];
6645         model_collide(&mc);
6646
6647         if (mc.num_hits)
6648                 *collision_point = mc.hit_point_world;
6649
6650         return mc.num_hits;
6651 }
6652
6653 //      Return true/false if *objp will collide with *big_objp
6654 //      Stuff distance in *distance to collision point if *objp will collide with *big_objp within delta_time seconds.
6655 //      Global collision point stuffed in *collision_point
6656 int will_collide_with_big_ship(object *objp, vector *goal_point, object *big_objp, vector *collision_point, float delta_time)
6657 {
6658         float           radius;
6659         vector  end_pos;
6660
6661         radius = big_objp->radius + delta_time * objp->phys_info.speed;
6662
6663         if (vm_vec_dist_quick(&big_objp->pos, &objp->pos) > radius) {
6664                 return 0;
6665         }
6666
6667         if (goal_point == NULL) {
6668                 vm_vec_scale_add(&end_pos, &objp->pos, &objp->phys_info.vel, delta_time);                                       // Point 2 of ray to check
6669         } else {
6670                 end_pos = *goal_point;
6671         }
6672
6673         return will_collide_pp(&objp->pos, &end_pos, objp->radius, big_objp, collision_point);
6674 }
6675
6676 //      Return true if *objp is expected to collide with a large ship.
6677 //      Stuff global collision point in *collision_point.
6678 //      If *goal_point is not NULL, use that as the point towards which *objp will be flying.  Don't use *objp velocity
6679 //      *ignore_objp will typically be the target this ship is pursuing, either to attack or guard.  We don't want to avoid it.
6680 int will_collide_with_big_ship_all(object *objp, object *ignore_objp, vector *goal_point, vector *collision_point, float *distance, float delta_time)
6681 {
6682         ship_obj        *so;
6683         object  *big_objp;
6684         int             collision_obj_index = -1;
6685         float           min_dist = 999999.9f;
6686
6687         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
6688                 big_objp = &Objects[so->objnum];
6689
6690                 if (big_objp == ignore_objp)
6691                         continue;
6692
6693                 if (Ship_info[Ships[big_objp->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
6694                         vector  cur_collision_point;
6695                         float           cur_dist;
6696
6697                         if (will_collide_with_big_ship(objp, goal_point, big_objp, &cur_collision_point, delta_time)) {
6698
6699                                 cur_dist = vm_vec_dist(&cur_collision_point, &objp->pos);
6700
6701                                 if (cur_dist < min_dist) {
6702                                         min_dist = cur_dist;
6703                                         *collision_point = cur_collision_point;
6704                                         collision_obj_index = OBJ_INDEX(big_objp);
6705                                 }
6706                         }
6707                 }
6708         }
6709
6710         *distance = min_dist;
6711         return collision_obj_index;
6712
6713 }
6714
6715 typedef struct {
6716         float           dist;
6717         int             collide;
6718         vector  pos;
6719 } sgoal;
6720
6721 //int will_collide_pp(vector *p0, vector *p1, float radius, object *big_objp, vector *collision_point)
6722 //      Pick a point for *objp to fly towards to avoid a collision with *big_objp at *collision_point
6723 //      Return result in *avoid_pos
6724 void mabs_pick_goal_point(object *objp, object *big_objp, vector *collision_point, vector *avoid_pos)
6725 {
6726         matrix  mat1;
6727         sgoal           goals[4];
6728         vector  v2b;
6729
6730         vm_vec_normalized_dir(&v2b, collision_point, &objp->pos);
6731         vm_vector_2_matrix(&mat1, &v2b, NULL, NULL);
6732
6733         int     found = 0;
6734
6735         //      Try various scales, in 0.5f, 0.75f, 1.0f, 1.25f.
6736         //      First try 0.5f to see if we can find a point that near the center of the target ship, which presumably
6737         //      means less of a turn.
6738         //      Try going as far as 1.25f * radius.
6739         float   s;
6740         for (s=0.5f; s<1.3f; s += 0.25f) {
6741                 int     i;
6742                 for (i=0; i<4; i++) {
6743                         vector p = big_objp->pos;
6744                         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
6745                         float kr = big_objp->radius*s + objp->radius * ((OBJ_INDEX(objp) % 4) ^ 2)/4;
6746                         if (i&1)
6747                                 ku = -ku;
6748                         if (i&2)
6749                                 kr = -kr;
6750                         vm_vec_scale_add2(&p, &mat1.v.uvec, ku);
6751                         vm_vec_scale_add2(&p, &mat1.v.rvec, kr);
6752                         goals[i].pos = p;
6753                         goals[i].dist = vm_vec_dist_quick(&objp->pos, &p);
6754                         goals[i].collide = will_collide_pp(&objp->pos, &p, objp->radius, big_objp, collision_point);
6755                         if (!goals[i].collide)
6756                                 found = 1;
6757                 }
6758
6759                 //      If we found a point that doesn't collide, find the nearest one and make that the *avoid_pos.
6760                 if (found) {
6761                         float   min_dist = 9999999.9f;
6762                         int     min_index = -1;
6763
6764                         for (i=0; i<4; i++) {
6765                                 if (!goals[i].collide && (goals[i].dist < min_dist)) {
6766                                         min_dist = goals[i].dist;
6767                                         min_index = i;
6768                                 }
6769                         }
6770
6771                         SDL_assert(i != -1);
6772                         if (i != -1) {
6773                                 *avoid_pos = goals[min_index].pos;
6774                                 return;
6775                         }
6776                 }
6777         }
6778
6779         //      Drat.  We tried and tried and could not find a point that did not cause a collision.
6780         //      Get this dump pilot far away from the problem ship.
6781         vector  away_vec;
6782         vm_vec_normalized_dir(&away_vec, &objp->pos, collision_point);
6783         vm_vec_scale_add(avoid_pos, &objp->pos, &away_vec, big_objp->radius*1.5f);
6784
6785 }
6786
6787 //      Return true if a large ship is being ignored.
6788 int maybe_avoid_big_ship(object *objp, object *ignore_objp, ai_info *aip, vector *goal_point, float delta_time)
6789 {
6790         if (timestamp_elapsed(aip->avoid_check_timestamp)) {
6791                 float           distance;
6792                 vector  collision_point;
6793                 int             ship_num;
6794                 if ((ship_num = will_collide_with_big_ship_all(Pl_objp, ignore_objp, goal_point, &collision_point, &distance, delta_time)) != -1) {
6795                         aip->ai_flags |= AIF_AVOIDING_BIG_SHIP;
6796                         mabs_pick_goal_point(objp, &Objects[ship_num], &collision_point, &aip->avoid_goal_point);
6797                         float dist = vm_vec_dist_quick(&aip->avoid_goal_point, &objp->pos);
6798                         aip->avoid_check_timestamp = timestamp(2000 + min(1000, (int) (dist * 2.0f)));  //      Delay until check again is based on distance to avoid point.
6799                         aip->avoid_ship_num = ship_num;
6800                 } else {
6801                         aip->ai_flags &= ~AIF_AVOIDING_BIG_SHIP;
6802                         aip->ai_flags &= ~AIF_AVOIDING_SMALL_SHIP;
6803                         aip->avoid_ship_num = -1;
6804                         aip->avoid_check_timestamp = timestamp(1500);
6805                 }
6806         }
6807         
6808         if (aip->ai_flags & AIF_AVOIDING_BIG_SHIP) {
6809                 ship_info *sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6810
6811                 vector  v2g;
6812
6813                 ai_turn_towards_vector(&aip->avoid_goal_point, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6814                 vm_vec_normalized_dir(&v2g, &aip->avoid_goal_point, &Pl_objp->pos);
6815                 float dot = vm_vec_dot(&objp->orient.v.fvec, &v2g);
6816                 float d2 = (1.0f + dot) * (1.0f + dot);
6817                 accelerate_ship(aip, d2/4.0f);
6818                 return 1;
6819         }
6820
6821         return 0;
6822 }
6823
6824 //      Set desired right vector for ships flying towards another ship.
6825 //      Since this is governed only by vector to target, it causes ships to align bank and look less chaotic.
6826 void compute_desired_rvec(vector *rvec, vector *goal_pos, vector *cur_pos)
6827 {
6828         vector  v2e;
6829
6830         vm_vec_normalized_dir(&v2e, goal_pos, cur_pos);
6831         rvec->xyz.x = v2e.xyz.z;
6832         rvec->xyz.y = 0.0f;
6833         rvec->xyz.z = -v2e.xyz.x;
6834         if (vm_vec_mag_squared(rvec) < 0.001f)
6835                 rvec->xyz.y = 1.0f;
6836 }
6837
6838 // Handler for stealth find submode of Chase.
6839 void ai_stealth_find()
6840 {
6841         ai_info         *aip;
6842         ship_info       *sip;
6843
6844         vector new_pos, vec_to_enemy;
6845         float dist_to_enemy, dot_to_enemy, dot_from_enemy;
6846
6847         SDL_assert(Ships[Pl_objp->instance].ship_info_index >= 0);
6848         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6849         SDL_assert(Ships[Pl_objp->instance].ai_index >= 0);
6850         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
6851
6852         // get time since last seen
6853         int delta_time = (timestamp() - aip->stealth_last_visible_stamp);
6854
6855         // if delta_time is really big, i'm real confused, start sweep
6856         if (delta_time > 10000) {
6857                 aip->submode_parm0 = SM_SF_BAIL;
6858         }
6859
6860         // guestimate new position
6861         vm_vec_scale_add(&new_pos, &aip->stealth_last_pos, &aip->stealth_velocity, (delta_time * 0.001f));
6862
6863         // if I think he's behind me, go to the goal point
6864         if ( aip->submode_parm0 == SM_SF_BEHIND ) {
6865                 new_pos = aip->goal_point;
6866         }
6867
6868         // check for collision with big ships
6869         if (maybe_avoid_big_ship(Pl_objp, En_objp, aip, &new_pos, 10.0f)) {
6870                 // reset ai submode to chase
6871                 return;
6872         }
6873
6874         // if dist is near max and dot is close to 1, accel, afterburn
6875         vm_vec_sub(&vec_to_enemy, &new_pos, &Pl_objp->pos);
6876         dist_to_enemy = vm_vec_normalize_quick(&vec_to_enemy);
6877         dot_to_enemy = vm_vec_dotprod(&vec_to_enemy, &Pl_objp->orient.v.fvec);
6878
6879         // 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
6880         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) ) {
6881                 // do turn around)
6882                 vm_vec_scale_add(&aip->goal_point, &Pl_objp->pos, &Pl_objp->orient.v.fvec, -300.0f);
6883                 aip->submode_parm0 = SM_SF_BEHIND;
6884                 vm_vec_sub(&vec_to_enemy, &new_pos, &Pl_objp->pos);
6885                 dist_to_enemy = vm_vec_normalize_quick(&vec_to_enemy);
6886                 dot_to_enemy = vm_vec_dotprod(&vec_to_enemy, &Pl_objp->orient.v.fvec);
6887         }
6888
6889         if ( (dist_to_enemy > get_skill_stealth_dist_scaler()*STEALTH_MAX_VIEW_DIST) && (dot_to_enemy > 0.94f) ) {              // 20 degree half angle
6890                 // accelerate ship
6891                 accelerate_ship(aip, 1.0f);
6892
6893                 // engage afterburner
6894                 if (!( Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
6895                         if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
6896                                 afterburners_start(Pl_objp);
6897                                 aip->afterburner_stop_time = Missiontime + 3*F1_0/2;
6898                         }
6899                 }
6900
6901                 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6902                 return;
6903         }
6904
6905         //      If enemy more than 500 meters away, all ships flying there will tend to match bank.
6906         //      They do this by using their vector to their target to compute their right vector and causing ai_turn_towards_vector
6907         //      to interpolate a matrix rather than just a vector.
6908         if (dist_to_enemy > 500.0f) {
6909                 vector  rvec;
6910                 compute_desired_rvec(&rvec, &new_pos, &Pl_objp->pos);
6911                 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0, &rvec);
6912         } else {
6913                 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
6914         }
6915
6916         dot_from_enemy = -vm_vec_dotprod(&vec_to_enemy, &En_objp->orient.v.fvec);
6917
6918         attack_set_accel(aip, dist_to_enemy, dot_to_enemy, dot_from_enemy);
6919 }
6920
6921 // -----------------------------------------------------------------------------
6922 // try to find stealth ship by sweeping an area
6923 void ai_stealth_sweep()
6924 {
6925         ai_info         *aip;
6926         ship_info       *sip;
6927
6928         SDL_assert(Ships[Pl_objp->instance].ship_info_index >= 0);
6929         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
6930         SDL_assert(Ships[Pl_objp->instance].ai_index >= 0);
6931         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
6932
6933         vector goal_pt;
6934         vector forward, right, up;
6935         int lost_time;
6936
6937         // time since stealth last seen
6938         lost_time = (timestamp() - aip->stealth_last_visible_stamp);
6939
6940         // determine which pt to fly to in sweep by keeping track of parm0
6941         if (aip->submode_parm0 == SM_SS_SET_GOAL) {
6942
6943                 // don't make goal pt more than 2k from current pos
6944                 vm_vec_scale_add(&goal_pt, &aip->stealth_last_pos, &aip->stealth_velocity, (0.001f * lost_time));
6945
6946                 // make box size based on speed of stealth and expected time to intercept (keep box in range 200-500)
6947                 float box_size = vm_vec_mag_quick(&aip->stealth_velocity) * (0.001f * lost_time);
6948                 box_size = min(200.0f, box_size);
6949                 box_size = max(500.0f, box_size);
6950                 aip->stealth_sweep_box_size = box_size;
6951
6952                 aip->goal_point = goal_pt;
6953                 aip->submode_parm0 = SM_SS_BOX0;
6954         }
6955
6956         // GET UP, RIGHT, FORWARD FOR BOX based on stealth ship's velocity
6957         // if velocity changes in stealth mode, then ship is *seen*, and falls out of sweep mode
6958         // if stealth has no velocity make a velocity
6959         if ( vm_vec_mag_quick(&aip->stealth_velocity) < 1 ) {
6960                 vm_vec_rand_vec_quick(&aip->stealth_velocity);
6961         }
6962
6963         // get "right" vector for box
6964         vm_vec_crossprod(&right, &aip->stealth_velocity, &vmd_y_vector);
6965
6966         if ( vm_vec_mag_quick(&right) < 0.01 ) {
6967                 vm_vec_crossprod(&right, &aip->stealth_velocity, &vmd_z_vector);
6968         }
6969
6970         vm_vec_normalize_quick(&right);
6971
6972         // get forward for box
6973         vm_vec_copy_normalize_quick(&forward, &aip->stealth_velocity);
6974
6975         // get "up" for box
6976         vm_vec_crossprod(&up, &forward, &right);
6977         
6978         // lost far away ahead (do box)
6979         switch(aip->submode_parm0) {
6980         case SM_SS_BOX0:
6981                 goal_pt = aip->goal_point;
6982                 break;
6983
6984         // pt1 -U +R
6985         case SM_SS_LR:
6986                 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, -aip->stealth_sweep_box_size);
6987                 vm_vec_scale_add2(&goal_pt, &right, aip->stealth_sweep_box_size);
6988                 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
6989                 break;
6990
6991         // pt2 +U -R
6992         case SM_SS_UL:
6993                 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, aip->stealth_sweep_box_size);
6994                 vm_vec_scale_add2(&goal_pt, &right, -aip->stealth_sweep_box_size);
6995                 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
6996                 break;
6997
6998         // pt3 back
6999         case SM_SS_BOX1:
7000                 goal_pt = aip->goal_point;
7001                 break;
7002
7003         // pt4 +U +R
7004         case SM_SS_UR:
7005                 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, aip->stealth_sweep_box_size);
7006                 vm_vec_scale_add2(&goal_pt, &right, aip->stealth_sweep_box_size);
7007                 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
7008                 break;
7009
7010         // pt5 -U -R
7011         case SM_SS_LL:
7012                 vm_vec_scale_add(&goal_pt, &aip->goal_point, &up, -aip->stealth_sweep_box_size);
7013                 vm_vec_scale_add2(&goal_pt, &right, -aip->stealth_sweep_box_size);
7014                 vm_vec_scale_add2(&goal_pt, &forward, 0.5f*aip->stealth_sweep_box_size);
7015                 break;
7016
7017         // pt6 back
7018         case SM_SS_BOX2:
7019                 goal_pt = aip->goal_point;
7020                 break;
7021
7022         default:
7023                 Int3();
7024
7025         }
7026
7027         // when close to goal_pt, update next goal pt
7028         float dist_to_goal = vm_vec_dist(&goal_pt, &Pl_objp->pos);
7029         if (dist_to_goal < 15) {
7030                 aip->submode_parm0++;
7031         }
7032
7033         // check for collision with big ship
7034         if (maybe_avoid_big_ship(Pl_objp, En_objp, aip, &goal_pt, 10.0f)) {
7035                 // skip to the next pt on box
7036                 aip->submode_parm0++;
7037                 return;
7038         }
7039
7040         ai_turn_towards_vector(&goal_pt, Pl_objp, flFrametime, sip->srotation_time, NULL, NULL, 0.0f, 0);
7041
7042         float dot = 1.0f;
7043         if (dist_to_goal < 100) {
7044                 vector vec_to_goal;
7045                 vm_vec_normalized_dir(&vec_to_goal, &goal_pt, &Pl_objp->pos);
7046                 dot = vm_vec_dotprod(&vec_to_goal, &Pl_objp->orient.v.fvec);
7047         }
7048
7049         accelerate_ship(aip, 0.8f*dot);
7050 }
7051
7052 //      ATTACK submode handler for chase mode.
7053 void ai_chase_attack(ai_info *aip, ship_info *sip, vector *predicted_enemy_pos, float dist_to_enemy)
7054 {
7055         int             start_bank;
7056         float           dot_to_enemy, dot_from_enemy; //, time_to_hit;
7057         float           bank_override = 0.0f;
7058
7059         if (avoid_player(Pl_objp, predicted_enemy_pos))
7060                 return;
7061
7062         compute_dots(Pl_objp, En_objp, &dot_to_enemy, &dot_from_enemy);
7063
7064         polymodel *po = model_get( sip->modelnum );
7065
7066         vector  *rel_pos;
7067         float           scale;
7068         vector  randvec;
7069         vector  new_pos;
7070
7071         start_bank = Ships[aip->shipnum].weapons.current_primary_bank;
7072         if (po->n_guns && start_bank != -1 ) {
7073                 rel_pos = &po->gun_banks[start_bank].pnt[0];
7074         } else
7075                 rel_pos = NULL;
7076
7077         //      If ship moving slowly relative to its size, then don't attack its center point.
7078         //      How far from center we attack is based on speed, size and distance to enemy
7079         if (En_objp->radius > En_objp->phys_info.speed) {
7080                 static_randvec(Pl_objp-Objects, &randvec);
7081                 scale = dist_to_enemy/(dist_to_enemy + En_objp->radius) * En_objp->radius;
7082                 scale *= 0.5f * En_objp->radius/(En_objp->phys_info.speed + En_objp->radius);   // scale downward by 1/2 to 1/4
7083                 vm_vec_scale_add(&new_pos, predicted_enemy_pos, &randvec, scale);
7084         } else
7085                 new_pos = *predicted_enemy_pos;
7086
7087         if (dist_to_enemy < 250.0f) {
7088                 if (dot_from_enemy > 0.7f) {
7089                         bank_override = Pl_objp->phys_info.speed;
7090                 }
7091         }
7092
7093         //      If enemy more than 500 meters away, all ships flying there will tend to match bank.
7094         //      They do this by using their vector to their target to compute their right vector and causing ai_turn_towards_vector
7095         //      to interpolate a matrix rather than just a vector.
7096         if (dist_to_enemy > 500.0f) {
7097                 vector  rvec;
7098                 compute_desired_rvec(&rvec, predicted_enemy_pos, &Pl_objp->pos);
7099                 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, rel_pos, bank_override, 0, &rvec);
7100         } else {
7101                 ai_turn_towards_vector(&new_pos, Pl_objp, flFrametime, sip->srotation_time, NULL, rel_pos, bank_override, 0);
7102         }
7103
7104         attack_set_accel(aip, dist_to_enemy, dot_to_enemy, dot_from_enemy);
7105 }
7106
7107 //      EVADE_SQUIGGLE submode handler for chase mode.
7108 //      Changed by MK on 5/5/97.
7109 //      Used to evade towards a point off the right or up vector.
7110 //      Now, evade straight away to try to get far away.
7111 //      The squiggling should protect against laser fire.
7112 void ai_chase_es(ai_info *aip, ship_info *sip)
7113 {
7114         vector  tvec;
7115         fix             timeslice;
7116         fix             scale;
7117         float           bank_override = 0.0f;
7118
7119         tvec = Pl_objp->pos;
7120
7121         timeslice = (Missiontime >> 16) & 0x0f;
7122         scale = ((Missiontime >> 16) & 0x0f) << 14;
7123
7124         if (timeslice & 0x01)
7125                 vm_vec_scale_add2(&tvec, &Pl_objp->orient.v.rvec, f2fl(scale ^ 0x10000));
7126         if (timeslice & 0x02)
7127                 vm_vec_scale_sub2(&tvec, &Pl_objp->orient.v.rvec, f2fl(scale));
7128         if (timeslice & 0x04)
7129                 vm_vec_scale_add2(&tvec, &Pl_objp->orient.v.uvec, f2fl(scale ^ 0x10000));
7130         if (timeslice & 0x08)
7131                 vm_vec_scale_sub2(&tvec, &Pl_objp->orient.v.uvec, f2fl(scale));
7132
7133         while (vm_vec_dist_quick(&tvec, &Pl_objp->pos) < 0.1f) {
7134                 tvec.xyz.x += frand();
7135                 tvec.xyz.y += frand();
7136         }
7137
7138         bank_override = Pl_objp->phys_info.speed;
7139
7140         ai_turn_towards_vector(&tvec, Pl_objp, flFrametime/2, sip->srotation_time, NULL, NULL, bank_override, 0);
7141         accelerate_ship(aip, 1.0f);
7142 }
7143
7144 //      Trying to get away from opponent.
7145 void ai_chase_ga(ai_info *aip, ship_info *sip)
7146 {
7147         //      If not near end of this submode, evade squiggly.  If near end, just fly straight for a bit
7148         vector  tvec;
7149         float           bank_override;
7150         vector  vec_from_enemy;
7151
7152         if (En_objp != NULL) {
7153                 vm_vec_normalized_dir(&vec_from_enemy, &Pl_objp->pos, &En_objp->pos);
7154         } else
7155                 vec_from_enemy = Pl_objp->orient.v.fvec;
7156
7157         static_randvec(Missiontime >> 15, &tvec);
7158         vm_vec_scale(&tvec, 100.0f);
7159         vm_vec_scale_add2(&tvec, &vec_from_enemy, 300.0f);
7160         vm_vec_add2(&tvec, &Pl_objp->pos);
7161
7162         bank_override = Pl_objp->phys_info.speed;
7163
7164         ai_turn_towards_vector(&tvec, Pl_objp, flFrametime/2, sip->srotation_time, NULL, NULL, bank_override, 0);
7165
7166         accelerate_ship(aip, 2.0f);
7167
7168         if (ai_maybe_fire_afterburner(Pl_objp, aip)) {
7169                 if (!(Pl_objp->phys_info.flags & PF_AFTERBURNER_ON )) {
7170                         float percent_left = 100.0f * Ships[Pl_objp->instance].afterburner_fuel / sip->afterburner_fuel_capacity;
7171                         if (percent_left > 30.0f + ((Pl_objp-Objects) & 0x0f)) {
7172                                 afterburners_start(Pl_objp);
7173                                 aip->afterburner_stop_time = Missiontime + 3*F1_0/2;
7174                         }
7175                         afterburners_start(Pl_objp);
7176                         aip->afterburner_stop_time = Missiontime + 3*F1_0/2;
7177                 }
7178         }
7179
7180 }
7181
7182 //      Make object *objp attack subsystem with ID = subnum.
7183 //      Return true if found a subsystem to attack, else return false.
7184 //      Note, can fail if subsystem exists, but has no hits.
7185 int ai_set_attack_subsystem(object *objp, int subnum)
7186 {
7187         ship                    *shipp, *attacker_shipp;
7188         ai_info         *aip;
7189         ship_subsys     *ssp;
7190         object          *attacked_objp;
7191
7192         SDL_assert(objp->type == OBJ_SHIP);
7193         SDL_assert(objp->instance >= 0);
7194
7195         attacker_shipp = &Ships[objp->instance];
7196         SDL_assert(attacker_shipp->ai_index >= 0);
7197
7198         aip = &Ai_info[attacker_shipp->ai_index];
7199
7200         // MWA -- 2/27/98.  Due to AL's changes, target_objnum is now not always valid (at least sometimes
7201         // in terms of goals).  So, bail if we don't have a valid target.
7202         if ( aip->target_objnum == -1 )
7203                 return 0;
7204
7205         attacked_objp = &Objects[aip->target_objnum];
7206         shipp = &Ships[attacked_objp->instance];                //  need to get our target's ship pointer!!!
7207
7208         ssp = ship_get_indexed_subsys(shipp, subnum, &objp->pos);
7209         if (ssp == NULL)
7210                 return 0;
7211
7212         set_targeted_subsys(aip, ssp, aip->target_objnum);
7213         
7214         if (aip->ignore_objnum == aip->target_objnum)
7215                 aip->ignore_objnum = UNUSED_OBJNUM;
7216
7217         // -- Done at caller in ai_process_mission_orders -- attacked_objp->flags |= OF_PROTECTED;
7218
7219         ai_set_goal_maybe_abort_dock(objp, aip);
7220         aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);
7221
7222         return 1;
7223 }
7224
7225 void ai_set_guard_vec(object *objp, object *guard_objp)
7226 {
7227         ai_info *aip;
7228         float   radius;
7229
7230         aip = &Ai_info[Ships[objp->instance].ai_index];
7231
7232         //      Handle case of bogus call in which ship is told to guard self.
7233         SDL_assert(objp != guard_objp);
7234         if (objp == guard_objp) {
7235                 vm_vec_rand_vec_quick(&aip->guard_vec);
7236                 vm_vec_scale(&aip->guard_vec, 100.0f);
7237                 return;
7238         }
7239
7240         // check if guard_objp is BIG
7241         radius = 5.0f * (objp->radius + guard_objp->radius) + 50.0f;
7242         if (radius > 300.0f) {
7243                 radius = guard_objp->radius * 1.25f;
7244         }
7245
7246         vm_vec_sub(&aip->guard_vec, &objp->pos, &guard_objp->pos);
7247
7248         if (vm_vec_mag(&aip->guard_vec) > 3.0f*radius) {
7249                 //      Far away, don't just use vector to object, causes clustering of guard ships.
7250                 vector  tvec, rvec;
7251                 float   mag;
7252                 mag = vm_vec_copy_normalize(&tvec, &aip->guard_vec);
7253                 vm_vec_rand_vec_quick(&rvec);                   
7254                 vm_vec_scale_add2(&tvec, &rvec, 0.5f);
7255                 vm_vec_copy_scale(&aip->guard_vec, &tvec, mag);
7256         }
7257
7258         vm_vec_normalize_quick(&aip->guard_vec);
7259         vm_vec_scale(&aip->guard_vec, radius);
7260 }
7261
7262 //      Make object *objp guard object *other_objp.
7263 //      To be called from the goals code.
7264 void ai_set_guard_wing(object *objp, int wingnum)
7265 {
7266         ship            *shipp;
7267         ai_info *aip;
7268         int             leader_objnum, leader_shipnum;
7269
7270         SDL_assert(wingnum >= 0);
7271
7272         SDL_assert(objp->type == OBJ_SHIP);
7273         SDL_assert(objp->instance >= 0);
7274
7275         // shouldn't set the ai mode for the player
7276         if ( objp == Player_obj ) {
7277                 return;
7278         }
7279
7280         shipp = &Ships[objp->instance];
7281
7282         SDL_assert(shipp->ai_index >= 0);
7283
7284         aip = &Ai_info[shipp->ai_index];
7285         force_avoid_player_check(objp, aip);
7286
7287         ai_set_goal_maybe_abort_dock(objp, aip);
7288         aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);
7289
7290         //      This function is called whenever a guarded ship is destroyed, so this code
7291         //      prevents a ship from trying to guard a non-existent wing.
7292         if (Wings[wingnum].current_count < 1) {
7293                 aip->guard_objnum = -1;
7294                 aip->guard_wingnum = -1;
7295                 aip->mode = AIM_NONE;
7296         } else {
7297                 leader_shipnum = Wings[wingnum].ship_index[0];
7298                 leader_objnum = Ships[leader_shipnum].objnum;
7299
7300                 SDL_assert((leader_objnum >= 0) && (leader_objnum < MAX_OBJECTS));
7301                 //SDL_assert(leader_objnum != objp-Objects);    //      Don't allow ships to guard themselves.
7302                 if (leader_objnum == OBJ_INDEX(objp)) {
7303                         //Int3();       //      Seems illegal, but let's clean up.  Get MikeK.
7304                         return;
7305                 }
7306
7307                 aip->guard_wingnum = wingnum;
7308                 aip->guard_objnum = leader_objnum;
7309                 aip->guard_signature = Objects[leader_objnum].signature;
7310                 aip->mode = AIM_GUARD;
7311                 aip->submode = AIS_GUARD_STATIC;
7312
7313                 ai_set_guard_vec(objp, &Objects[leader_objnum]);
7314         }
7315 }
7316
7317 //      Make object *objp guard object *other_objp.
7318 //      To be called from the goals code.
7319 void ai_set_evade_object(object *objp, object *other_objp)
7320 {
7321         ship            *shipp;
7322         ai_info *aip;
7323         int             other_objnum;
7324
7325         SDL_assert(objp->type == OBJ_SHIP);
7326         SDL_assert(objp->instance >= 0);
7327
7328         shipp = &Ships[objp->instance];
7329
7330         SDL_assert(shipp->ai_index >= 0);
7331
7332         aip = &Ai_info[shipp->ai_index];
7333
7334         other_objnum = OBJ_INDEX(other_objp);
7335         SDL_assert(other_objnum >= 0);
7336
7337         SDL_assert(other_objnum != Ships[aip->shipnum].objnum); //      make sure not targeting self
7338         aip->target_objnum = other_objnum;
7339
7340         aip->mode = AIM_EVADE;
7341 }
7342
7343 //      Make objp guard other_objp
7344 //      If other_objp is a member of a wing, objp will guard that whole wing
7345 //      UNLESS objp is also a member of the wing!
7346 void ai_set_guard_object(object *objp, object *other_objp)
7347 {
7348         ship            *shipp;
7349         ai_info *aip;
7350         int             other_objnum;
7351
7352         SDL_assert(objp->type == OBJ_SHIP);
7353         SDL_assert(objp->instance >= 0);
7354         SDL_assert(objp != other_objp);
7355
7356         shipp = &Ships[objp->instance];
7357
7358         SDL_assert(shipp->ai_index >= 0);
7359
7360         aip = &Ai_info[shipp->ai_index];
7361         aip->avoid_check_timestamp = timestamp(1);
7362
7363         //      If ship to guard is in a wing, guard that whole wing.
7364         ai_info *other_aip = &Ai_info[Ships[other_objp->instance].ai_index];
7365         if ((other_aip->wing != -1) && (other_aip->wing != aip->wing)) {
7366                 ai_set_guard_wing(objp, Ai_info[Ships[other_objp->instance].ai_index].wing);
7367         } else {
7368
7369                 other_objnum = other_objp-Objects;
7370
7371                 aip->guard_objnum = other_objnum;
7372                 aip->guard_signature = other_objp->signature;
7373                 aip->guard_wingnum = -1;
7374
7375                 aip->mode = AIM_GUARD;
7376                 aip->submode = AIS_GUARD_STATIC;
7377
7378                 SDL_assert(other_objnum >= 0);  //      Hmm, bogus object and we need its position for guard_vec.
7379
7380                 // vm_vec_sub(&aip->guard_vec, &objp->pos, &Objects[other_objnum].pos);
7381                 ai_set_guard_vec(objp, &Objects[other_objnum]);
7382
7383                 ai_set_goal_maybe_abort_dock(objp, aip);
7384                 aip->ok_to_target_timestamp = timestamp(DELAY_TARGET_TIME);
7385         }
7386 }
7387
7388 //      Update the aspect_locked_time field based on whether enemy is in view cone.
7389 //      Also set/clear AIF_SEEK_LOCK.
7390 void update_aspect_lock_information(ai_info *aip, vector *vec_to_enemy, float dist_to_enemy, float enemy_radius)
7391 {
7392         float   dot_to_enemy;
7393         int     num_weapon_types;
7394         int     weapon_id_list[MAX_WEAPON_TYPES], weapon_bank_list[MAX_WEAPON_TYPES];
7395         ship    *shipp;
7396         ship_weapon     *swp;
7397         weapon_info     *wip;
7398
7399         shipp = &Ships[aip->shipnum];
7400         swp = &shipp->weapons;
7401
7402         // AL 3-7-98: This probably should never happen, but check to ensure that current_secondary_bank is valid
7403         if ( (swp->current_secondary_bank < 0) || (swp->current_secondary_bank > swp->num_secondary_banks) ) {
7404                 return;
7405         }
7406
7407         num_weapon_types = get_available_secondary_weapons(Pl_objp, weapon_id_list, weapon_bank_list);
7408
7409         wip = &Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]];
7410
7411         if (num_weapon_types && (wip->wi_flags & WIF_HOMING_ASPECT)) {
7412                 if (dist_to_enemy > 300.0f - min(enemy_radius, 100.0f))
7413                         aip->ai_flags |= AIF_SEEK_LOCK;
7414                 else
7415                         aip->ai_flags &= ~AIF_SEEK_LOCK;
7416
7417                 //      Update locking information for aspect seeking missiles.
7418                 aip->current_target_is_locked = 0;
7419                 dot_to_enemy = vm_vec_dot(vec_to_enemy, &Pl_objp->orient.v.fvec);
7420
7421                 float   needed_dot = 0.9f - 0.5f * enemy_radius/(dist_to_enemy + enemy_radius); //      Replaced MIN_TRACKABLE_DOT with 0.9f
7422                 if (dot_to_enemy > needed_dot) {
7423                         aip->aspect_locked_time += flFrametime;
7424                         // nprintf(("AI", "+ Lock time = %7.3f\n", aip->aspect_locked_time));
7425                         if (aip->aspect_locked_time >= wip->min_lock_time) {
7426                                 aip->aspect_locked_time = wip->min_lock_time;
7427                                 aip->current_target_is_locked = 1;
7428                         }
7429                 } else {
7430                         aip->aspect_locked_time -= flFrametime*2;
7431                         // nprintf(("AI", "- Lock time = %7.3f\n", aip->aspect_locked_time));
7432                         if (aip->aspect_locked_time < 0.0f)
7433                                 aip->aspect_locked_time = 0.0f;
7434                 }
7435                 //nprintf(("AI", "dot = %7.3f, time = %7.3f\n", dot_to_enemy, aip->aspect_locked_time));
7436         
7437         } else {
7438                 aip->current_target_is_locked = 0;
7439                 aip->aspect_locked_time = 0.0f; // Used to be this, why?: wip->min_lock_time;
7440                 aip->ai_flags &= ~AIF_SEEK_LOCK;
7441         }
7442
7443 }
7444
7445 //      We're in chase mode and we've recently collided with our target.
7446 //      Fly away from it!
7447 void ai_chase_fly_away(object *objp, ai_info *aip)
7448 {
7449         int     abort_flag = 0;
7450
7451         if (aip->ai_flags & AIF_TARGET_COLLISION) {
7452                 aip->ai_flags &= ~AIF_TARGET_COLLISION; //      Don't process this hit again next frame.
7453                 aip->submode = SM_FLY_AWAY;                                     //      Focus on avoiding target
7454                 aip->submode_start_time = Missiontime;
7455         }
7456
7457         if ((aip->target_objnum == -1) || (Objects[aip->target_objnum].signature != aip->target_signature)) {
7458                 abort_flag = 1;
7459         }
7460
7461         if (abort_flag || (Missiontime > aip->submode_start_time + F1_0)) {
7462                 aip->last_attack_time = Missiontime;
7463                 aip->submode = SM_ATTACK;
7464                 aip->submode_start_time = Missiontime;
7465         } else {
7466                 vector  v2e;
7467                 float           dot;
7468
7469                 vm_vec_normalized_dir(&v2e, &Objects[aip->target_objnum].pos, &objp->pos);
7470
7471                 dot = vm_vec_dot(&objp->orient.v.fvec, &v2e);
7472                 if (dot < 0.0f)
7473                         accelerate_ship(aip, 1.0f);
7474                 else
7475                         accelerate_ship(aip, 1.0f - dot);
7476                 turn_away_from_point(objp, &Objects[aip->target_objnum].pos, 0.0f);
7477         }
7478 }
7479
7480 //      Return bank index of favored secondary weapon.
7481 //      Return -1 if nothing favored.
7482 //      "favored" means SEXPs have specified the weapon as being good to fire at en_objp.
7483 int has_preferred_secondary(object *objp, object *en_objp, ship_weapon *swp)
7484 {
7485 // int is_preferred_weapon(int weapon_num, object *firer_objp, object *target_objp)
7486         int     i;
7487
7488         for (i=0; i<swp->num_secondary_banks; i++) {
7489                 if (swp->secondary_bank_capacity[i] > 0) {
7490                         if (swp->secondary_bank_ammo[i] > 0) {
7491                                 if (is_preferred_weapon(swp->secondary_bank_weapons[i], objp, en_objp) != -1){
7492                                         return i;
7493                                 }
7494                         }
7495                 }
7496         }
7497
7498         return -1;
7499 }
7500
7501 //      Choose which secondary weapon to fire.
7502 //      Note, this is not like ai_select_secondary_weapon().  "choose" means make a choice.
7503 //      "select" means execute an order.  Get it?
7504 //      This function calls ai_select_secondary_weapon() with the characteristics it should search for.
7505 void ai_choose_secondary_weapon(object *objp, ai_info *aip, object *en_objp)
7506 {
7507         float                   subsystem_strength = 0.0f;
7508         int                     is_big_ship, priority1, priority2;
7509         ship_weapon     *swp;
7510         ship_info       *esip;
7511
7512         if ( en_objp->type == OBJ_SHIP ) {
7513                 esip = &Ship_info[Ships[en_objp->instance].ship_info_index];
7514         } else {
7515                 esip = NULL;
7516         }
7517
7518         swp = &Ships[objp->instance].weapons;
7519
7520         // AL 3-5-98: do a quick out if the ship has no secondaries
7521         if ( swp->num_secondary_banks <= 0 ) {
7522                 swp->current_secondary_bank = -1;
7523                 return;
7524         }
7525
7526         int preferred_secondary = has_preferred_secondary(objp, en_objp, swp);
7527
7528         if (preferred_secondary != -1) {
7529                 if (swp->current_secondary_bank != preferred_secondary) {
7530                         aip->current_target_is_locked = 0;
7531                         aip->aspect_locked_time = 0.0f;
7532                         swp->current_secondary_bank = preferred_secondary;
7533                 }
7534                 //nprintf(("AI", "Favored secondary = %s\n", Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]].name));
7535                 aip->ai_flags |= AIF_UNLOAD_SECONDARIES;
7536         } else {
7537                 aip->ai_flags &= ~AIF_UNLOAD_SECONDARIES;
7538                 if (aip->targeted_subsys) {
7539                         subsystem_strength = aip->targeted_subsys->current_hits;
7540                 }
7541
7542                 if ( esip ) {
7543                         is_big_ship = esip->flags & (SIF_HUGE_SHIP | SIF_BIG_SHIP);
7544                 } else {
7545                         is_big_ship=0;
7546                 }
7547
7548                 if (is_big_ship) {
7549                         priority1 = WIF_HUGE;
7550                         priority2 = WIF_HOMING;
7551                 } else if ( (esip != NULL) && (esip->flags & SIF_BOMBER) ) {
7552                         priority1 = WIF_BOMBER_PLUS;
7553                         priority2 = WIF_HOMING;
7554                 } else if (subsystem_strength > 100.0f) {
7555                         priority1 = WIF_PUNCTURE;
7556                         priority2 = WIF_HOMING;
7557                 } else {
7558                         priority1 = WIF_HOMING;
7559                         priority2 = 0;
7560                 }
7561                 
7562                 ai_select_secondary_weapon(objp, swp, priority1, priority2);
7563         }
7564
7565         // nprintf(("AI", "Frame %i: Chose secondary %s\n", Framecount, Weapon_info[swp->secondary_bank_weapons[swp->current_secondary_bank]].name));
7566 }
7567
7568 //      Return time, in seconds, at which this ship can next fire its current secondary weapon.
7569 float set_secondary_fire_delay(ai_info *aip, ship *shipp, weapon_info *swip)
7570 {
7571         float t = swip->fire_wait;              //      Base delay for this weapon.
7572         if (shipp->team == Player_ship->team) {
7573                 //      On player's team, _lower_ skill level = faster firing
7574                 t = t * (Game_skill_level+2) / (NUM_SKILL_LEVELS);
7575         } else {                //      Not on player's team, higher skill level = faster firing
7576                 t = t * (NUM_SKILL_LEVELS - Game_skill_level+2) / (NUM_SKILL_LEVELS);
7577         }
7578
7579         t += (Num_ai_classes - aip->ai_class + 1) * 0.5f;
7580         t *= frand_range(0.8f, 1.2f);
7581
7582         //      For the missiles that fire fairly quickly, occasionally add an additional substantial delay.
7583         if (t < 5.0f)
7584                 if (frand() < 0.5f)
7585                         t = t * 2.0f + 2.0f;
7586
7587         return t;
7588 }
7589
7590
7591 void ai_chase_big_approach_set_goal(vector *goal_pos, object *attack_objp, object *target_objp, float *accel)
7592 {
7593         float dist_to_goal;
7594
7595         // head straight toward him and maybe circle later
7596         vm_vec_avg(goal_pos, &attack_objp->pos, &target_objp->pos);
7597
7598         // get distance to goal
7599         dist_to_goal = vm_vec_dist(goal_pos, &attack_objp->pos);
7600         
7601         // set accel
7602         if (dist_to_goal > 400.0f) {
7603                 *accel = 1.0f;
7604         } else {
7605                 *accel = dist_to_goal/400.0f;
7606         }
7607 }
7608
7609 void ai_chase_big_circle_set_goal(vector *goal_pos, object *attack_objp, object *target_objp, float *accel)
7610 {
7611         get_tangent_point(goal_pos, attack_objp, &target_objp->pos, attack_objp->radius + target_objp->radius + 100.0f);
7612
7613         *accel = 1.0f;
7614 }
7615
7616 // get the current and desired horizontal separations between target
7617 void ai_chase_big_get_separations(object *attack_objp, object *target_objp, vector *horz_vec_to_target, float *desired_separation, float *cur_separation)
7618 {
7619         float temp, r_target, r_attacker;
7620         float perp_dist;
7621         vector vec_to_target;
7622         polymodel *pm;
7623
7624         // get parameters of ships (as cylinders - radius and height)
7625         // get radius of attacker (for rotations about forward)
7626         pm = model_get(Ships[attack_objp->instance].modelnum);
7627         temp = max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7628         r_attacker = max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7629         r_attacker = max(temp, r_attacker);
7630
7631         // get radius of target (for rotations about forward)
7632         pm = model_get(Ships[attack_objp->instance].modelnum);
7633         temp = max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7634         r_target = max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7635         r_target = max(temp, r_target);
7636
7637         // find separation between cylinders [if parallel]
7638         vm_vec_sub(&vec_to_target, &attack_objp->pos, &target_objp->pos);
7639
7640         // find the distance between centers along forward direction of ships
7641         perp_dist = vm_vec_dotprod(&vec_to_target, &target_objp->orient.v.fvec);
7642
7643         // subtract off perp component to get "horizontal" separation vector between cylinders [ASSUMING parallel]
7644         vm_vec_scale_add(horz_vec_to_target, &vec_to_target, &target_objp->orient.v.fvec, -perp_dist);
7645         *cur_separation = vm_vec_mag_quick(horz_vec_to_target);
7646
7647         // choose "optimal" separation of 1000 + r_target + r_attacker
7648         *desired_separation = 1000 + r_target + r_attacker;
7649 }
7650
7651 void ai_chase_big_parallel_set_goal(vector *goal_pos, object *attack_objp, object *target_objp, float *accel)
7652 {
7653         int opposing;
7654         float temp, r_target, r_attacker;
7655         float separation, optimal_separation;
7656         vector  horz_vec_to_target;
7657         polymodel *pm;
7658
7659         // get parameters of ships (as cylinders - radius and height)
7660         // get radius of attacker (for rotations about forward)
7661         pm = model_get(Ships[attack_objp->instance].modelnum);
7662         temp = max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7663         r_attacker = max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7664         r_attacker = max(temp, r_attacker);
7665
7666         // get radius of target (for rotations about forward)
7667         pm = model_get(Ships[attack_objp->instance].modelnum);
7668         temp = max(pm->maxs.xyz.x, pm->maxs.xyz.y);
7669         r_target = max(-pm->mins.xyz.x, -pm->mins.xyz.y);
7670         r_target = max(temp, r_target);
7671
7672         // are we opposing (only when other ship is not moving)
7673         opposing = ( vm_vec_dotprod(&attack_objp->orient.v.fvec, &target_objp->orient.v.fvec) < 0 );
7674
7675         ai_chase_big_get_separations(attack_objp, target_objp, &horz_vec_to_target, &optimal_separation, &separation);
7676
7677         // choose dist (2000) so that we don't bash
7678         float dist = 2000;
7679         if (opposing) {
7680                 dist = - dist;
7681         }
7682
7683         // set the goal pos as dist forward from target along target forward
7684         vm_vec_scale_add(goal_pos, &target_objp->pos, &target_objp->orient.v.fvec, dist);
7685         // then add horizontal separation
7686         vm_vec_scale_add2(goal_pos, &horz_vec_to_target, optimal_separation/separation);
7687
7688         // find the distance between centers along forward direction of ships
7689         vector vec_to_target;
7690         vm_vec_sub(&vec_to_target, &target_objp->pos, &attack_objp->pos);
7691         float perp_dist = vm_vec_dotprod(&vec_to_target, &target_objp->orient.v.fvec);
7692
7693         float match_accel = target_objp->phys_info.vel.xyz.z / Ship_info[Ships[attack_objp->instance].ship_info_index].max_vel.xyz.z;
7694         float length_scale = attack_objp->radius;
7695
7696         // if we're heading toward enemy ship, we want to keep going if we're ahead
7697         if (opposing) {
7698                 perp_dist = -perp_dist;
7699         }
7700
7701         if (perp_dist > 0) {
7702                 // falling behind, so speed up
7703                 *accel = match_accel + (1.0f - match_accel) / length_scale * (perp_dist);
7704         } else {
7705                 // up in front, so slow down
7706                 *accel = match_accel  - match_accel / length_scale * -perp_dist;
7707                 *accel = max(0.0f, *accel);
7708         }
7709
7710 }
7711
7712
7713 //      Return *goal_pos for one cruiser to attack another (big ship).
7714 //      Choose point fairly nearby that is not occupied by another cruiser.
7715 void ai_cruiser_chase_set_goal_pos(vector *goal_pos, object *pl_objp, object *en_objp)
7716 {
7717         ai_info *aip;
7718
7719         aip = &Ai_info[Ships[pl_objp->instance].ai_index];
7720         float accel;
7721
7722         switch (aip->submode) {
7723         case SM_BIG_APPROACH:
7724                 // do approach stuff;
7725                 ai_chase_big_approach_set_goal(goal_pos, pl_objp, en_objp, &accel);
7726                 break;
7727
7728         case SM_BIG_CIRCLE:
7729                 // do circle stuff
7730                 ai_chase_big_circle_set_goal(goal_pos, pl_objp, en_objp, &accel);
7731                 break;
7732
7733         case SM_BIG_PARALLEL:
7734                 // do parallel stuff
7735                 ai_chase_big_parallel_set_goal(goal_pos, pl_objp, en_objp, &accel);
7736                 break;
7737         }
7738 }
7739
7740 int maybe_hack_cruiser_chase_abort()
7741 {
7742         ship                    *shipp = &Ships[Pl_objp->instance];     
7743         ship                    *eshipp = &Ships[En_objp->instance];
7744         ai_info         *aip = &Ai_info[shipp->ai_index];
7745
7746         // mission sm3-08, sathanos chasing collosus
7747         if ( SDL_strcasecmp(Mission_filename, "sm3-08.fs2") == 0 ) {
7748                 if (( SDL_strcasecmp(eshipp->ship_name, "colossus") == 0 ) || ( SDL_strcasecmp(shipp->ship_name, "colossus") == 0 )) {
7749                         // Changed so all big ships attacking the Colossus will not do the chase code.
7750                         // Did this so Beast wouldn't swerve away from Colossus. -- MK, 9/14/99
7751                         //if ( SDL_strcasecmp(shipp->ship_name, "Sathanas") == 0 ) {
7752                                 // do cool hack stuff here
7753                                 ai_clear_ship_goals( aip );
7754                                 aip->mode = AIM_NONE;
7755                                 return 1;
7756                         //}
7757                 }
7758         }
7759
7760         return 0;
7761 }
7762
7763 //      Make a big ship pursue another big ship.
7764 //      (Note, called "ai_cruiser_chase" because we already have ai_chase_big() which means fighter chases big ship.
7765 void ai_cruiser_chase()
7766 {
7767         ship_info       *sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
7768         ship                    *shipp = &Ships[Pl_objp->instance];     
7769         ai_info         *aip = &Ai_info[shipp->ai_index];
7770
7771         if (!(sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
7772                 Int3(); //      Hmm, not a very big ship, how did we get in this function?
7773                 aip->mode = AIM_NONE;
7774                 return;
7775         }
7776
7777         if (En_objp->type != OBJ_SHIP) {
7778                 Int3();
7779                 return;
7780         }
7781
7782         if (En_objp->instance < 0) {
7783                 Int3();
7784                 return;
7785         }
7786
7787         ship                    *eshipp;
7788         ship_info       *esip;
7789
7790         eshipp = &Ships[En_objp->instance];
7791         esip = &Ship_info[eshipp->ship_info_index];
7792
7793         if (!(esip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
7794                 // Int3();      //      Hmm, we're big and we're pursuing something other than a big ship?
7795                 aip->mode = AIM_NONE;
7796                 return;
7797         }
7798
7799         vector  goal_pos;
7800         float turn_time = Ship_info[Ships[Pl_objp->instance].ship_info_index].srotation_time;
7801
7802         // kamikaze - ram and explode
7803         if (aip->ai_flags & AIF_KAMIKAZE) {
7804                 ai_turn_towards_vector(&En_objp->pos, Pl_objp, flFrametime, turn_time, NULL, NULL, 0.0f, 0);
7805                 accelerate_ship(aip, 1.0f);
7806         } 
7807         
7808         // really track down and chase
7809         else {
7810                 // check valid submode
7811                 SDL_assert( (aip->submode == SM_ATTACK) || (aip->submode == SM_BIG_APPROACH) || (aip->submode == SM_BIG_CIRCLE) || (aip->submode == SM_BIG_PARALLEL) );
7812
7813                 // just entering, approach enemy ship
7814                 if (aip->submode == SM_ATTACK) {
7815                         aip->submode = SM_BIG_APPROACH;
7816                 }
7817
7818                 // desired accel
7819                 float accel = 0.0f;
7820                 vector *rvecp = NULL;
7821
7822                 switch (aip->submode) {
7823                 case SM_BIG_APPROACH:
7824                         // do approach stuff;
7825                         ai_chase_big_approach_set_goal(&goal_pos, Pl_objp, En_objp, &accel);
7826                         // maybe set rvec
7827                         break;
7828
7829                 case SM_BIG_CIRCLE:
7830                         // do circle stuff
7831                         ai_chase_big_circle_set_goal(&goal_pos, Pl_objp, En_objp, &accel);
7832                         // maybe set rvec
7833                         break;
7834
7835                 case SM_BIG_PARALLEL:
7836                         // do parallel stuff
7837                         ai_chase_big_parallel_set_goal(&goal_pos, Pl_objp, En_objp, &accel);
7838                         //maybe set rvec
7839                         break;
7840                 }
7841
7842
7843                 // now move as desired
7844                 ai_turn_towards_vector(&goal_pos, Pl_objp, flFrametime, turn_time, NULL, NULL, 0.0f, 0, rvecp);
7845                 accelerate_ship(aip, accel);
7846
7847
7848                 // maybe switch to new mode
7849                 vector vec_to_enemy;
7850                 float dist_to_enemy;
7851                 int moving = (En_objp->phys_info.vel.xyz.z > 0.5f);
7852                 vm_vec_sub(&vec_to_enemy, &En_objp->pos, &Pl_objp->pos);
7853                 dist_to_enemy = vm_vec_mag_quick(&vec_to_enemy);
7854
7855                 switch (aip->submode) {
7856                 case SM_BIG_APPROACH:
7857                         if ( dist_to_enemy < (Pl_objp->radius + En_objp->radius)*1.25f + 200.0f ) {
7858                                 // moving
7859                                 if (moving) {
7860                                         // if within 90 degrees of en forward, go into parallel, otherwise circle
7861                                         if ( vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) > 0 ) {
7862                                                 aip->submode = SM_BIG_PARALLEL;
7863                                         }
7864                                 }
7865
7866                                 // otherwise cirle
7867                                 if ( !maybe_hack_cruiser_chase_abort() ) {
7868                                         aip->submode = SM_BIG_CIRCLE;
7869                                 }
7870                         }
7871                         break;
7872
7873                 case SM_BIG_CIRCLE:
7874                         // moving
7875                         if (moving) {
7876                                 vector temp;
7877                                 float desired_sep, cur_sep;
7878                                 // we're behind the enemy ship
7879                                 if (vm_vec_dotprod(&vec_to_enemy, &En_objp->orient.v.fvec) > 0) {
7880                                         // and we're turning toward the enemy
7881                                         if (vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) > 0) {
7882                                                 // get separation
7883                                                 ai_chase_big_get_separations(Pl_objp, En_objp, &temp, &desired_sep, &cur_sep);
7884                                                 // and the separation is > 0.9 desired
7885                                                 if (cur_sep > 0.9 * desired_sep) {
7886                                                         aip->submode = SM_BIG_PARALLEL;
7887                                                 }
7888                                         }
7889                                 }
7890                         } else {
7891                                 // still
7892                                 vector temp;
7893                                 float desired_sep, cur_sep;
7894                                 // we're behind the enemy ship
7895                                 if (vm_vec_dotprod(&vec_to_enemy, &En_objp->orient.v.fvec) > 0) {
7896                                         // and we're turning toward the enemy
7897                                         if (vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) > 0) {
7898                                                 // get separation
7899                                                 ai_chase_big_get_separations(Pl_objp, En_objp, &temp, &desired_sep, &cur_sep);
7900                                                 //and the separation is [0.9 to 1.1] desired
7901                                                 if ( (cur_sep > 0.9f * desired_sep) ) {
7902                                                         aip->submode = SM_BIG_PARALLEL;
7903                                                 }
7904                                         }
7905                                 }
7906                                 // in front of ship
7907                                 else {
7908                                         // and we're turning toward the enemy
7909                                         if (vm_vec_dotprod(&En_objp->orient.v.fvec, &Pl_objp->orient.v.fvec) < 0) {
7910                                                 // get separation
7911                                                 ai_chase_big_get_separations(Pl_objp, En_objp, &temp, &desired_sep, &cur_sep);
7912                                                 //and the separation is [0.9 to 1.1] desired
7913                                                 if ( (cur_sep > 0.9f * desired_sep) ) {
7914                                                         aip->submode = SM_BIG_PARALLEL;
7915                                                 }
7916                                         }
7917                                 }
7918                         }
7919                         break;
7920
7921                 case SM_BIG_PARALLEL:
7922                         // we're opposing
7923                         if ( vm_vec_dotprod(&Pl_objp->orient.v.fvec, &En_objp->orient.v.fvec) < 0 ) {
7924                                 // and the other ship is moving
7925                                 if (moving) {
7926                                         // and we no longer overlap
7927                                         if ( dist_to_enemy > (0.75 * (En_objp->radius + Pl_objp->radius)) ) {
7928                                                 aip->submode = SM_BIG_APPROACH;
7929                                         }
7930                                 }
7931                         }
7932                         break;
7933                 }
7934         }
7935 }
7936
7937 // --------------------------------------------------------------------------
7938 // Make object Pl_objp chase object En_objp
7939 void ai_chase()
7940 {
7941         float                   dist_to_enemy;
7942         float                   dot_to_enemy, dot_from_enemy, real_dot_to_enemy;
7943         vector          player_pos, enemy_pos, predicted_enemy_pos, real_vec_to_enemy, predicted_vec_to_enemy;
7944         ship_info       *sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
7945         ship                    *shipp = &Ships[Pl_objp->instance];
7946         ship_weapon     *swp = &shipp->weapons;
7947         ai_info         *aip = &Ai_info[shipp->ai_index];
7948         int                     enemy_sip_flags;
7949
7950         if (aip->mode != AIM_CHASE) {
7951                 Int3();
7952         }
7953
7954         if (sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
7955                 ai_cruiser_chase();
7956                 return;
7957         }
7958
7959         if (!(sip->flags & (SIF_FIGHTER | SIF_BOMBER | SIF_ESCAPEPOD))) {
7960                 Warning(LOCATION, "Ship %s is not 'small', but is in chase mode.\nSwitching to AI=none.\n", shipp->ship_name);
7961                 aip->mode = AIM_NONE;
7962                 return;
7963         }
7964
7965         //nprintf(("AI", "%7s ", Submode_text[aip->submode]));
7966
7967         if ( En_objp->type == OBJ_SHIP ) {
7968                 enemy_sip_flags = Ship_info[Ships[En_objp->instance].ship_info_index].flags;
7969         } else {
7970                 enemy_sip_flags = 0;
7971         }
7972
7973         if ( enemy_sip_flags > 0 ) {
7974                 if (enemy_sip_flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
7975                         ai_big_chase();
7976                         return;
7977                 }
7978         }
7979
7980         //      If collided with target_objnum last frame, avoid that ship.
7981         //      This should prevent the embarrassing behavior of ships getting stuck on each other
7982         //      as if they were magnetically attracted. -- MK, 11/13/97.
7983         if ((aip->ai_flags & AIF_TARGET_COLLISION) || (aip->submode == SM_FLY_AWAY)) {
7984                 ai_chase_fly_away(Pl_objp, aip);
7985                 return;
7986         }
7987
7988         ai_set_positions(Pl_objp, En_objp, aip, &player_pos, &enemy_pos);
7989         dist_to_enemy = vm_vec_dist_quick(&player_pos, &enemy_pos);
7990         vm_vec_sub(&real_vec_to_enemy, &enemy_pos, &player_pos);
7991
7992         vm_vec_normalize(&real_vec_to_enemy);
7993
7994         real_dot_to_enemy = vm_vec_dot(&real_vec_to_enemy, &Pl_objp->orient.v.fvec);
7995
7996         int is_stealthy_ship = 0;
7997         if ( (enemy_sip_flags > 0) && (enemy_sip_flags & SIF_STEALTH) ) {
7998                 if ( ai_is_stealth_visible(Pl_objp, En_objp) != STEALTH_FULLY_TARGETABLE ) {
7999                         is_stealthy_ship = 1;
8000                 }
8001         }
8002
8003         // Can only acquire lock on a target that isn't hidden from sensors
8004         if ( !(Ships[En_objp->instance].flags & SF_HIDDEN_FROM_SENSORS) && !is_stealthy_ship ) {
8005                 update_aspect_lock_information(aip, &real_vec_to_enemy, dist_to_enemy, En_objp->radius);
8006         } else {
8007                 aip->current_target_is_locked = 0;
8008                 aip->ai_flags &= ~AIF_SEEK_LOCK;
8009         }
8010
8011         //      If seeking lock, try to point directly at ship, else predict position so lasers can hit it.
8012         //      If just acquired target, or target is not in reasonable cone, don't refine believed enemy position.
8013         if ((real_dot_to_enemy < 0.25f) || (aip->target_time < 1.0f) || (aip->ai_flags & AIF_SEEK_LOCK)) {
8014                 predicted_enemy_pos = enemy_pos;
8015         } else {
8016                 //      Set predicted_enemy_pos.
8017                 //      See if attacking a subsystem.
8018                 if (aip->targeted_subsys != NULL) {
8019                         SDL_assert(En_objp->type == OBJ_SHIP);
8020                         ship_info       *esip = &Ship_info[Ships[En_objp->instance].ship_info_index];
8021                         if (get_shield_strength(En_objp)/esip->shields < HULL_DAMAGE_THRESHOLD_PERCENT) {
8022                                 //int   rval;
8023
8024                                 if (aip->targeted_subsys != NULL) {
8025                                         get_subsystem_pos(&enemy_pos, En_objp, aip->targeted_subsys);
8026                                         predicted_enemy_pos = enemy_pos;
8027                                         predicted_vec_to_enemy = real_vec_to_enemy;
8028                                 } else {
8029                                         set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, En_objp, aip);
8030                                         set_target_objnum(aip, -1);
8031                                 }
8032                                 // nprintf(("AI", "Attacking subsystem: rval = %i, pos = %7.3f %7.3f %7.3f\n", rval, predicted_enemy_pos.xyz.x, predicted_enemy_pos.xyz.y, predicted_enemy_pos.xyz.z));
8033
8034                         } else {
8035                                 set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, En_objp, aip);
8036                                 // nprintf(("AI", "Attacking subsystem: pos = %7.3f %7.3f %7.3f\n", predicted_enemy_pos.xyz.x, predicted_enemy_pos.xyz.y, predicted_enemy_pos.xyz.z));
8037                         }
8038                 } else {
8039                         set_predicted_enemy_pos(&predicted_enemy_pos, Pl_objp, En_objp, aip);
8040                 }
8041         }
8042
8043         vm_vec_sub(&predicted_vec_to_enemy, &predicted_enemy_pos, &player_pos);
8044
8045         vm_vec_normalize(&predicted_vec_to_enemy);
8046
8047         dot_to_enemy = vm_vec_dot(&Pl_objp->orient.v.fvec, &predicted_vec_to_enemy);
8048         dot_from_enemy= - vm_vec_dot(&En_objp->orient.v.fvec, &real_vec_to_enemy);
8049
8050         //
8051         //      Set turn and acceleration based on submode.
8052         //
8053         switch (aip->submode) {
8054         case SM_CONTINUOUS_TURN:
8055                 ai_chase_ct();
8056                 break;
8057
8058         case SM_STEALTH_FIND:
8059                 ai_stealth_find();
8060                 break;
8061
8062         case SM_STEALTH_SWEEP:
8063                 ai_stealth_sweep();
8064                 break;
8065
8066         case SM_ATTACK:
8067         case SM_SUPER_ATTACK:
8068         case SM_ATTACK_FOREVER:
8069                 if (vm_vec_dist_quick(&Pl_objp->pos, &predicted_enemy_pos) > 100.0f + En_objp->radius * 2.0f) {
8070                         if (maybe_avoid_big_ship(Pl_objp, En_objp, aip, &predicted_enemy_pos, 10.0f))
8071                                 return;
8072                 }
8073
8074                 ai_chase_attack(aip, sip, &predicted_enemy_pos, dist_to_enemy);
8075                 break;
8076
8077         case SM_EVADE_SQUIGGLE:
8078                 ai_chase_es(aip, sip);
8079                 break;
8080
8081         case SM_EVADE_BRAKE:
8082                 ai_chase_eb(aip, sip, &predicted_enemy_pos, dist_to_enemy);
8083                 break;
8084
8085         case SM_EVADE:
8086                 evade_ship();
8087                 break;
8088
8089         case SM_AVOID:
8090                 avoid_ship();
8091                 break;
8092
8093         case SM_GET_BEHIND:
8094                 get_behind_ship(aip, sip, dist_to_enemy);
8095                 break;
8096
8097         case SM_GET_AWAY:               //      Used to get away from opponent to prevent endless circling.
8098                 ai_chase_ga(aip, sip);
8099                 break;
8100
8101         case SM_EVADE_WEAPON:
8102                 evade_weapon();
8103                 break;
8104
8105         default:
8106                 // Int3();
8107                 aip->last_attack_time = Missiontime;
8108                 aip->submode = SM_ATTACK;
8109                 aip->submode_start_time = Missiontime;
8110         }
8111
8112         //
8113         //      Maybe choose a new submode.
8114         //
8115         if ( (aip->submode != SM_AVOID) && (aip->submode != SM_ATTACK_FOREVER) ) {
8116                 //      If a very long time since attacked, attack no matter what!
8117                 if ( (aip->submode != SM_SUPER_ATTACK) && (aip->submode != SM_GET_AWAY) && !(aip->ai_flags & AIF_STEALTH_PURSIUT) ) {
8118                         if (Missiontime - aip->last_attack_time > i2f(6)) {
8119                                 aip->submode = SM_SUPER_ATTACK;
8120                                 aip->submode_start_time = Missiontime;
8121                                 aip->last_attack_time = Missiontime;
8122                         }
8123                 }
8124
8125                 //      If a collision is expected, pull out!
8126                 //      If enemy is pointing away and moving a bit, don't worry about collision detection.
8127                 if ((dot_from_enemy > 0.5f) || (En_objp->phys_info.speed < 10.0f)) {
8128                         if (might_collide_with_ship(Pl_objp, En_objp, dot_to_enemy, dist_to_enemy, 4.0f)) {
8129                                 if ((Missiontime - aip->last_hit_time > F1_0*4) && (dist_to_enemy < Pl_objp->radius*2 + En_objp->radius*2)) {
8130                                         accelerate_ship(aip, -1.0f);
8131                                 } else {
8132                                         aip->submode = SM_AVOID;
8133                                         aip->submode_start_time = Missiontime;
8134                                 }
8135                         }
8136                 }
8137         }
8138
8139         switch (aip->submode) {
8140         case SM_CONTINUOUS_TURN:
8141                 if (Missiontime - aip->submode_start_time > i2f(3)) {
8142                         aip->last_attack_time = Missiontime;
8143                         aip->submode = SM_ATTACK;
8144                         aip->submode_start_time = Missiontime;
8145                 }
8146                 break;
8147
8148         case SM_ATTACK:
8149                 // if taraget is stealth and stealth not visible, then enter stealth find mode
8150                 if ( (aip->ai_flags & AIF_STEALTH_PURSIUT) && (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_INVISIBLE) ) {
8151                         aip->submode = SM_STEALTH_FIND;
8152                         aip->submode_start_time = Missiontime;
8153                         aip->submode_parm0 = SM_SF_AHEAD;
8154                 } else if (ai_near_full_strength(Pl_objp, sip) && (Missiontime - aip->last_hit_target_time > i2f(3)) && (dist_to_enemy < 500.0f) && (dot_to_enemy < 0.5f)) {
8155                         aip->submode = SM_SUPER_ATTACK;
8156                         aip->submode_start_time = Missiontime;
8157                         aip->last_attack_time = Missiontime;
8158                 } else if ((Missiontime - aip->last_hit_target_time > i2f(6)) &&
8159                         (dist_to_enemy < 500.0f) && (dot_to_enemy < 0.2f) &&
8160                         (frand() < (float) Game_skill_level/NUM_SKILL_LEVELS)) {
8161                         aip->submode = SM_GET_AWAY;
8162                         aip->submode_start_time = Missiontime;
8163                         aip->last_hit_target_time = Missiontime;
8164                 } else if ((enemy_sip_flags & SIF_SMALL_SHIP)
8165                         && (dot_to_enemy < dot_from_enemy)
8166                         && (En_objp->phys_info.speed > 15.0f) 
8167                         && (dist_to_enemy < 200.0f) 
8168                         && (dist_to_enemy > 50.0f)
8169                         && (dot_to_enemy < 0.1f)
8170                         && (Missiontime - aip->submode_start_time > i2f(2))) {
8171                         aip->submode = SM_EVADE_BRAKE;
8172                         aip->submode_start_time = Missiontime;
8173                 } else if ((dot_to_enemy > 0.2f) && (dot_from_enemy > -0.2f) && (dot_from_enemy < 0.1f)) {
8174                         aip->submode = SM_GET_BEHIND;
8175                         aip->submode_start_time = Missiontime;
8176                 } else if ((enemy_sip_flags & SIF_SMALL_SHIP) && (dist_to_enemy < 150.0f) && (dot_from_enemy > dot_to_enemy + 0.5f + aip->ai_courage*.002)) {
8177                         if ((Missiontime - aip->last_hit_target_time > i2f(5)) && (frand() < (float) (aip->ai_class + Game_skill_level)/(Num_ai_classes + NUM_SKILL_LEVELS))) {                         aip->submode = SM_GET_AWAY;
8178                                 aip->submode_start_time = Missiontime;
8179                                 aip->last_hit_target_time = Missiontime;
8180                         } else {
8181                                 aip->submode = SM_EVADE_SQUIGGLE;
8182                                 aip->submode_start_time = Missiontime;
8183                         }
8184                 } else if ((enemy_sip_flags & SIF_SMALL_SHIP) && (Missiontime - aip->submode_start_time > F1_0*2)) {
8185                         if ((dot_to_enemy < 0.8f) && (dot_from_enemy > dot_to_enemy)) {
8186                                 if (frand() > 0.5f) {
8187                                         aip->submode = SM_CONTINUOUS_TURN;
8188                                         aip->submode_parm0 = myrand() & 0x0f;
8189                                         aip->submode_start_time = Missiontime;
8190                                 } else {
8191                                         aip->submode = SM_EVADE;
8192                                         aip->submode_start_time = Missiontime;
8193                                 }
8194                         } else {
8195                                 aip->submode_start_time = Missiontime;
8196                         }
8197                 }
8198
8199                 aip->last_attack_time = Missiontime;
8200
8201                 break;
8202                 
8203         case SM_EVADE_SQUIGGLE:
8204                 if ((Missiontime - aip->submode_start_time > i2f(5)) || (dist_to_enemy > 300.0f)) {
8205                         if ((dist_to_enemy < 100.0f) && (dot_to_enemy < 0.0f) && (dot_from_enemy > 0.5f)) {
8206                                 aip->submode = SM_EVADE_BRAKE;
8207                                 aip->submode_start_time = Missiontime;
8208                         } else {
8209                                 aip->last_attack_time = Missiontime;
8210                                 aip->submode = SM_ATTACK;
8211                                 aip->submode_start_time = Missiontime;
8212                         }
8213                 }
8214                 break;
8215         
8216         case SM_EVADE_BRAKE:
8217                 if ((dist_to_enemy < 15.0f) || (En_objp->phys_info.speed < 10.0f)) {
8218                         aip->submode = SM_AVOID;
8219                         aip->submode_start_time = Missiontime;
8220                 } else if ((dot_to_enemy > 0.9f) || ((dot_from_enemy > 0.9f) && (Missiontime - aip->submode_start_time > i2f(1)))) {
8221                         aip->last_attack_time = Missiontime;
8222                         aip->submode = SM_ATTACK;
8223                         aip->submode_start_time = Missiontime;
8224                 } else if (Missiontime - aip->submode_start_time > i2f(4)) {
8225                         aip->last_attack_time = Missiontime;
8226                         aip->submode = SM_ATTACK;
8227                         aip->submode_start_time = Missiontime;
8228                 }
8229                 break;
8230
8231         case SM_EVADE:
8232                 //      Modified by MK on 5/5/97 to keep trying to regain attack mode.  It's what a human would do.
8233                 if ((dot_to_enemy < 0.2f) && (dot_from_enemy < 0.8f) && (dist_to_enemy < 100.0f) && (En_objp->phys_info.speed > 15.0f)) {
8234                         aip->last_attack_time = Missiontime;
8235                         aip->submode = SM_EVADE_BRAKE;
8236                         aip->submode_start_time = Missiontime;
8237                 } else if (((dot_to_enemy > dot_from_enemy - 0.1f)
8238                         && (Missiontime > aip->submode_start_time + i2f(1)))
8239                         || (dist_to_enemy > 150.0f + 2*(Pl_objp->radius + En_objp->radius))) {
8240                         aip->last_attack_time = Missiontime;
8241                         aip->submode = SM_ATTACK;
8242                         aip->submode_start_time = Missiontime;
8243                 } else if (Missiontime - aip->submode_start_time > i2f(2))
8244                         if (dot_from_enemy > 0.8f) {
8245                                 aip->submode = SM_EVADE_SQUIGGLE;
8246                                 aip->submode_start_time = Missiontime;
8247                         }
8248
8249                 break;
8250
8251         case SM_SUPER_ATTACK:
8252                 // if stealth and invisible, enter stealth find mode
8253                 if ( (aip->ai_flags & AIF_STEALTH_PURSIUT) && (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_INVISIBLE) ) {
8254                         aip->submode = SM_STEALTH_FIND;
8255                         aip->submode_start_time = Missiontime;
8256                         aip->submode_parm0 = SM_SF_AHEAD;
8257                 } else if ((dist_to_enemy < 100.0f) && (dot_to_enemy < 0.8f) && (enemy_sip_flags & SIF_SMALL_SHIP) && (Missiontime - aip->submode_start_time > i2f(5) )) {
8258                         aip->ai_flags &= ~AIF_ATTACK_SLOWLY;    //      Just in case, clear here.
8259
8260                         switch (myrand() % 5) {
8261                         case 0:
8262                                 aip->submode = SM_CONTINUOUS_TURN;
8263                                 aip->submode_start_time = Missiontime;
8264                                 break;
8265                         case 1:
8266                                 aip->submode_start_time = Missiontime;  //      Stay in super attack mode
8267                                 break;
8268                         case 2:
8269                         case 3:
8270                                 if (frand() < (float) 0.5f * (aip->ai_class + Game_skill_level)/(Num_ai_classes + NUM_SKILL_LEVELS)) {
8271                                         aip->submode = SM_GET_AWAY;
8272                                         aip->submode_start_time = Missiontime;
8273                                 } else {
8274                                         aip->submode = SM_EVADE;
8275                                         aip->submode_start_time = Missiontime;
8276                                 }
8277                                 break;
8278                         case 4:
8279                                 if (dot_from_enemy + (NUM_SKILL_LEVELS - Game_skill_level) * 0.1f > dot_to_enemy) {     //      Less likely to GET_AWAY at lower skill levels.
8280                                         aip->submode = SM_EVADE;
8281                                         aip->submode_start_time = Missiontime;
8282                                 } else {
8283                                         aip->submode = SM_GET_AWAY;
8284                                         aip->submode_start_time = Missiontime;
8285                                 }
8286                                 break;
8287                         default:
8288                                 Int3(); //      Impossible!
8289                         }
8290                 }
8291
8292                 aip->last_attack_time = Missiontime;
8293
8294                 break;
8295
8296         case SM_AVOID:
8297                 if ((dot_to_enemy > -0.2f) && (dist_to_enemy / (dot_to_enemy + 0.3f) < 100.0f)) {
8298                         aip->submode_start_time = Missiontime;
8299                 } else if (Missiontime - aip->submode_start_time > i2f(1)/2) {
8300                         if (might_collide_with_ship(Pl_objp, En_objp, dot_to_enemy, dist_to_enemy, 3.0f)) {
8301                                 aip->submode_start_time = Missiontime;
8302                         } else {
8303                                 aip->submode = SM_GET_BEHIND;
8304                                 aip->submode_start_time = Missiontime;
8305                         }
8306                 }
8307
8308                 break;
8309
8310         case SM_GET_BEHIND:
8311                 if ((dot_from_enemy < -0.7f) || (Missiontime - aip->submode_start_time > i2f(2))) {
8312                         aip->submode = SM_ATTACK;
8313                         aip->submode_start_time = Missiontime;
8314                         aip->last_attack_time = Missiontime;
8315                 }
8316                 break;
8317
8318         case SM_GET_AWAY:
8319                 if (Missiontime - aip->submode_start_time > i2f(2)) {
8320                         float   rand_dist;
8321
8322                         rand_dist = ((Missiontime >> 17) & 0x03) * 100.0f + 200.0f;     //      Some value in 200..500
8323                         if ((Missiontime - aip->submode_start_time > i2f(5)) || (dist_to_enemy > rand_dist) || (dot_from_enemy < 0.4f)) {
8324                                 aip->ai_flags |= AIF_ATTACK_SLOWLY;
8325                                 aip->submode = SM_ATTACK;
8326                                 aip->time_enemy_in_range = 2.0f;                //      Cheat.  Presumably if they were running away from you, they were monitoring you!
8327                                 aip->submode_start_time = Missiontime;
8328                                 aip->last_attack_time = Missiontime;
8329                         }
8330                 }
8331                 break;
8332
8333         case SM_EVADE_WEAPON:
8334                 if (aip->danger_weapon_objnum == -1) {
8335                         aip->submode = SM_ATTACK;
8336                         aip->submode_start_time = Missiontime;
8337                         aip->last_attack_time = Missiontime;
8338                 }
8339                 break;
8340
8341         // Either change to SM_ATTACK or AIM_FIND_STEALTH
8342         case SM_STEALTH_FIND:
8343                 // if time > 5 sec change mode to sweep
8344                 if ( !(aip->ai_flags & AIF_STEALTH_PURSIUT) || (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_VISIBLE) ) {
8345                         aip->submode = SM_ATTACK;
8346                         aip->submode_start_time = Missiontime;
8347                         aip->last_attack_time = Missiontime;
8348                         // sweep if I can't find in 5 sec or bail from find
8349                 } else if ( ((Missiontime - aip->submode_start_time) > i2f(5)) || (aip->submode_parm0 == SM_SF_BAIL) ) {
8350                         // begin sweep mode
8351                         aip->submode = SM_STEALTH_SWEEP;
8352                         aip->submode_start_time = Missiontime;
8353                         aip->last_attack_time = Missiontime;
8354                         aip->submode_parm0 = SM_SS_SET_GOAL;
8355                 }
8356                 break;
8357
8358         case SM_STEALTH_SWEEP:
8359                 if ( !(aip->ai_flags & AIF_STEALTH_PURSIUT) || (ai_is_stealth_visible(Pl_objp, En_objp) == STEALTH_VISIBLE) ) {
8360                         aip->submode = SM_ATTACK;
8361                         aip->submode_start_time = Missiontime;
8362                         aip->last_attack_time = Missiontime;
8363                 } else if ( (timestamp() - aip->stealth_last_visible_stamp) < 5000 ) {
8364                         // go back to find mode
8365                         aip->submode = SM_STEALTH_FIND;
8366                         aip->submode_start_time = Missiontime;
8367                         aip->submode_parm0 = SM_SF_AHEAD;
8368                 } else if ( /*(Missiontime - aip->submode_start_time) > i2f(30) || */ aip->submode_parm0 == SM_SS_DONE ) {
8369                         // set target objnum = -1
8370                         set_target_objnum(aip, -1);
8371
8372                         // set submode to attack
8373                         aip->submode = SM_ATTACK;
8374                         aip->submode_start_time = Missiontime;
8375                         aip->last_attack_time = Missiontime;
8376                 }
8377                 break;
8378
8379         case SM_ATTACK_FOREVER: //      Engines blown, just attack.
8380                 break;
8381
8382         default:
8383                 //Int3();
8384                 aip->submode = SM_ATTACK;
8385                 aip->last_attack_time = Missiontime;
8386
8387                 aip->submode_start_time = Missiontime;
8388         }
8389
8390         //
8391         //      Maybe fire primary weapon and update time_enemy_in_range
8392         //
8393         //nprintf(("AI", "time_enemy_in_range = %7.3f, dot = %7.3f\n", aip->time_enemy_in_range, dot_to_enemy));
8394
8395         if (aip->mode != AIM_EVADE) {
8396                 if (dot_to_enemy > 0.95f - 0.5f * En_objp->radius/max(1.0f, En_objp->radius + dist_to_enemy)) {
8397                         aip->time_enemy_in_range += flFrametime;
8398                         
8399                         //      Chance of hitting ship is based on dot product of firing ship's forward vector with vector to ship
8400                         //      and also the size of the target relative to distance to target.
8401                         if (dot_to_enemy > max(0.5f, 0.90f + aip->ai_accuracy/10.0f - En_objp->radius/max(1.0f,dist_to_enemy))) {
8402
8403                                 ship *temp_shipp;
8404                                 ship_weapon *tswp;
8405
8406                                 temp_shipp = &Ships[Pl_objp->instance];
8407                                 tswp = &temp_shipp->weapons;
8408                                 if ( tswp->num_primary_banks > 0 ) {
8409                                         float   scale;
8410                                         SDL_assert(tswp->current_primary_bank < tswp->num_primary_banks);
8411                                         weapon_info     *pwip = &Weapon_info[tswp->primary_bank_weapons[tswp->current_primary_bank]];
8412
8413                                         //      Less likely to fire if far away and moving.
8414                                         scale = pwip->max_speed/(En_objp->phys_info.speed + pwip->max_speed);
8415                                         if (scale > 0.6f)
8416                                                 scale = (scale - 0.6f) * 1.5f;
8417                                         else
8418                                                 scale = 0.0f;
8419                                         if (dist_to_enemy < pwip->max_speed * (1.0f + scale)) {
8420                                                 ai_fire_primary_weapon(Pl_objp);
8421                                         }
8422
8423                                         //      Don't fire secondaries at a protected ship.
8424                                         if (!(En_objp->flags & OF_PROTECTED)) {
8425                                                 ai_choose_secondary_weapon(Pl_objp, aip, En_objp);
8426                                                 int current_bank = tswp->current_secondary_bank;
8427                                                 weapon_info     *swip = &Weapon_info[tswp->secondary_bank_weapons[tswp->current_secondary_bank]];
8428
8429                                                 if (current_bank > -1) {
8430                                                         if (aip->ai_flags & AIF_UNLOAD_SECONDARIES) {
8431                                                                 if (timestamp_until(swp->next_secondary_fire_stamp[current_bank]) > swip->fire_wait*1000.0f) {
8432                                                                         swp->next_secondary_fire_stamp[current_bank] = timestamp((int) (swip->fire_wait*1000.0f));
8433                                                                 }
8434                                                         }
8435
8436                                                         if (timestamp_elapsed(swp->next_secondary_fire_stamp[current_bank])) {
8437                                                                 if (tswp->current_secondary_bank >= 0) {
8438                                                                         weapon_info     *swip = &Weapon_info[tswp->secondary_bank_weapons[tswp->current_secondary_bank]];
8439                                                                         float firing_range;
8440                                                                         
8441                                                                         if (swip->wi_flags & WIF_BOMB)
8442                                                                                 firing_range = swip->max_speed * swip->lifetime * 0.75f;
8443                                                                         else
8444                                                                                 firing_range = swip->max_speed * swip->lifetime * (Game_skill_level + 1 + aip->ai_class/2)/NUM_SKILL_LEVELS;
8445
8446                                                                         // reduce firing range in nebula
8447                                                                         extern int Nebula_sec_range;
8448                                                                         if ((The_mission.flags & MISSION_FLAG_FULLNEB) && Nebula_sec_range) {
8449                                                                                 firing_range *= 0.8f;
8450                                                                         }
8451
8452                                                                         //      If firing a spawn weapon, distance doesn't matter.
8453                                                                         int     spawn_fire = 0;
8454
8455                                                                         if (swip->wi_flags & WIF_SPAWN) {
8456                                                                                 int     count;
8457
8458                                                                                 count = num_nearby_fighters(get_enemy_team_mask(OBJ_INDEX(Pl_objp)), &Pl_objp->pos, 1000.0f);
8459
8460                                                                                 if (count > 3)
8461                                                                                         spawn_fire = 1;
8462                                                                                 else if (count >= 1) {
8463                                                                                         float hull_percent = Pl_objp->hull_strength/sip->initial_hull_strength;
8464
8465                                                                                         if (hull_percent < 0.01f)
8466                                                                                                 hull_percent = 0.01f;
8467
8468                                                                                         if (frand() < 0.25f/(30.0f*hull_percent) * count)       //      With timestamp below, this means could fire in 30 seconds if one enemy.
8469                                                                                                 spawn_fire = 1;
8470                                                                                 }
8471                                                                         }
8472
8473                                                                         if (spawn_fire || (dist_to_enemy < firing_range)) {
8474                                                                                 if (ai_fire_secondary_weapon(Pl_objp)) {
8475                                                                                         //      Only if weapon was fired do we specify time until next fire.  If not fired, done in ai_fire_secondary...
8476                                                                                         float t;
8477                                                                                         
8478                                                                                         if (aip->ai_flags & AIF_UNLOAD_SECONDARIES) {
8479                                                                                                 t = swip->fire_wait;
8480                                                                                         } else {
8481                                                                                                 t = set_secondary_fire_delay(aip, temp_shipp, swip);
8482                                                                                         }
8483                                                                                         //nprintf(("AI", "Next secondary to be fired in %7.3f seconds.\n", t));
8484                                                                                         swp->next_secondary_fire_stamp[current_bank] = timestamp((int) (t*1000.0f));
8485                                                                                 }
8486                                                                         } else {
8487                                                                                 swp->next_secondary_fire_stamp[current_bank] = timestamp(250);
8488                                                                         }
8489                                                                 }
8490                                                         }
8491                                                 }
8492                                         }
8493                                 }
8494                         }
8495                 } else {
8496                         aip->time_enemy_in_range *= (1.0f - flFrametime);
8497                 }
8498         } else
8499                 aip->time_enemy_in_range *= (1.0f - flFrametime);
8500
8501 }
8502
8503 //      Make the object *objp move so that the point *dp on the object moves towards the point *vp
8504 //      Return distance.
8505 void dock_move_towards_point(object *objp, vector *dp, vector *vp, float speed_scale, float other_obj_speed = 0.0f)
8506 {
8507         physics_info    *pi = &objp->phys_info;
8508         float                           dist;                   //      dist to goal
8509         vector                  v2g;                    //      vector to goal
8510         vector                  abs_pnt;                //      location of dock point, ie objp->pos + db
8511
8512         if (dp == NULL)
8513                 abs_pnt = objp->pos;
8514         else
8515                 vm_vec_add(&abs_pnt, &objp->pos, dp);
8516
8517         dist = vm_vec_dist_quick(vp, &abs_pnt);
8518         if (dist > 0.0f) {
8519                 float   speed;
8520
8521                 dist = vm_vec_normalized_dir(&v2g, vp, &abs_pnt);
8522                 speed = fl_sqrt(dist) * speed_scale;
8523                 if (other_obj_speed < MAX_REPAIR_SPEED*0.75f)
8524                         speed += other_obj_speed;
8525                 else
8526                         speed += MAX_REPAIR_SPEED*0.75f;
8527
8528                 vm_vec_copy_scale(&pi->desired_vel, &v2g, speed);
8529         } else
8530                 vm_vec_zero(&pi->desired_vel);
8531 }
8532
8533 //      Set the orientation in the global reference frame for an object to attain
8534 //      to dock with another object.
8535 //      *dom            resultant global matrix
8536 //      *db_dest        pointer to destination docking bay information
8537 //      *db_src pointer to source docking bay information
8538 //      *dorient        pointer to global orientation of docking bay (ie, the dockee object's orient)
8539 //      *sorient        pointer to global orientation of docker
8540 void set_goal_dock_orient(matrix *dom, dock_bay *db_dest, dock_bay *db_src, matrix *dorient, matrix *sorient)
8541 {
8542         vector  fvec, uvec;
8543         matrix  m1, m2, m3;
8544
8545         //      Compute the global orientation of the docker's (dest) docking bay.
8546         fvec = db_dest->norm[0];
8547         vm_vec_negate(&fvec);
8548
8549         vm_vec_normalized_dir(&uvec, &db_dest->pnt[1], &db_dest->pnt[0]);
8550         vm_vector_2_matrix(&m1, &fvec, &uvec, NULL);
8551
8552         vm_matrix_x_matrix(&m3, dorient, &m1);
8553
8554         //      Compute the matrix given by the source docking bay.
8555         //      Pre-multiply the orientation of the source object (sorient) by the transpose
8556         //      of the docking bay's orientation, ie unrotate the source object's matrix.
8557         fvec = db_src->norm[0];
8558         vm_vec_normalized_dir(&uvec, &db_src->pnt[1], &db_src->pnt[0]);
8559         vm_vector_2_matrix(&m2, &fvec, &uvec, NULL);
8560         vm_transpose(&m2);
8561
8562         vm_matrix_x_matrix(dom, &m3, &m2);
8563 }
8564
8565 #define DOCK_BACKUP_RETURN_VAL  99999.9f
8566
8567 //      Make objp dock with dobjp
8568 //      Returns distance to goal, defined as distance between corresponding dock points, plus 10.0f * rotational velocity vector (DOA_DOCK only)
8569 //      DOA_APPROACH    means   approach point aip->path_cur
8570 //      DOA_DOCK                        means dock
8571 //      DOA_UNDOCK_1    means undock, moving to point nearest dock bay
8572 //      DOA_UNDOCK_2    means undock, moving to point nearest dock bay and facing away from ship
8573 //      DOA_DOCK_STAY   means rigidly maintain position in dock bay.
8574 float dock_orient_and_approach(object *objp, object *dobjp, int dock_mode)
8575 {
8576         ship_info       *sip0, *sip1;
8577         polymodel       *pm0, *pm1;
8578         ai_info         *aip;
8579         matrix          dom, nm;
8580         vector          goal_point, docker_point;
8581         float                   fdist = UNINITIALIZED_VALUE;
8582         int                     docker_index, dockee_index;             // index into docking_bays[] array for objects docking
8583                                                                                                                                 // docker is Pl_objp -- dockee is dobjp
8584         aip = &Ai_info[Ships[objp->instance].ai_index];
8585
8586         //      If dockee has moved much, then path will be recreated.
8587         //      Might need to change state if moved too far.
8588         if ((dock_mode != DOA_DOCK_STAY) && (dock_mode != DOA_DOCK)) {
8589                 if (maybe_recreate_path(objp, &Ai_info[Ships[objp->instance].ai_index], 0) > 5.0f) {
8590 /*                      if (dock_mode == DOA_APPROACH) {
8591                                 return DOCK_BACKUP_RETURN_VAL;
8592                         } else if (dock_mode == DOA_DOCK) {
8593                                 return DOCK_BACKUP_RETURN_VAL;          
8594                         }
8595 */              }
8596         }
8597
8598         objp->phys_info.forward_thrust = 0.0f;          //      Kill thrust so we don't have a sputtering thruster.
8599
8600         sip0 = &Ship_info[Ships[objp->instance].ship_info_index];
8601         sip1 = &Ship_info[Ships[dobjp->instance].ship_info_index];
8602         pm0 = model_get( sip0->modelnum );
8603         pm1 = model_get( sip1->modelnum );
8604
8605         docker_index = aip->dock_index;
8606         dockee_index = aip->dockee_index;
8607
8608         SDL_assert( docker_index >= 0 );
8609         SDL_assert( dockee_index >= 0 );
8610
8611         SDL_assert(pm0->docking_bays[docker_index].num_slots == 2);
8612         SDL_assert(pm1->docking_bays[dockee_index].num_slots == 2);
8613
8614         float speed_scale = 1.0f;
8615         if (sip0->flags & SIF_SUPPORT) {
8616                 speed_scale = 3.0f;
8617         }
8618
8619         switch (dock_mode) {
8620         case DOA_APPROACH:
8621                 {
8622                 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8623                         return 9999.9f;
8624                 }
8625                 
8626                 //      Compute the desired global orientation matrix for the docker's station.
8627                 //      That is, the normal vector of the docking station must be the same as the
8628                 //      forward vector and the vector between its two points must be the uvec.
8629                 set_goal_dock_orient(&dom, &pm1->docking_bays[dockee_index], &pm0->docking_bays[docker_index], &dobjp->orient, &objp->orient);
8630
8631                 //      Compute new orientation matrix and update rotational velocity.
8632                 vector  w_in, w_out, vel_limit, acc_limit;
8633                 float           tdist, mdist, ss1;
8634
8635                 w_in = objp->phys_info.rotvel;
8636                 vel_limit = objp->phys_info.max_rotvel;
8637                 vm_vec_copy_scale(&acc_limit, &vel_limit, 0.3f);
8638                 
8639                 if (sip0->flags & SIF_SUPPORT)
8640                         vm_vec_scale(&acc_limit, 2.0f);
8641
8642                 // 1 at end of line prevent overshoot
8643                 vm_matrix_interpolate(&dom, &objp->orient, &w_in, flFrametime, &nm, &w_out, &vel_limit, &acc_limit, 1);
8644                 objp->phys_info.rotvel = w_out;
8645                 objp->orient = nm;
8646
8647                 //      Translate towards goal and note distance to goal.
8648                 goal_point = Path_points[aip->path_cur].pos;
8649                 mdist = ai_matrix_dist(&objp->orient, &dom);
8650                 tdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8651
8652                 //      If translation is badly lagging rotation, speed up translation.
8653                 if (mdist > 0.1f) {
8654                         ss1 = tdist/(10.0f * mdist);
8655                         if (ss1 > 2.0f)
8656                                 ss1 = 2.0f;
8657                 } else
8658                         ss1 = 2.0f;
8659
8660                 // nprintf(("AI", "speed scale = %7.3f\n", ss1));
8661                 speed_scale *= 1.0f + ss1;
8662
8663                 dock_move_towards_point(objp, NULL, &goal_point, speed_scale, dobjp->phys_info.speed);
8664
8665                 fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8666
8667                 //      Note, we're interested in distance from goal, so if we're still turning, bash that into return value.
8668                 // nprintf(("AI", "matrix dist = %7.3f, threshold = %7.3f\n", mdist, 2*flFrametime));
8669                 fdist += 2.0f * mdist;
8670
8671                 break;
8672         }
8673         case DOA_DOCK:
8674                 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8675                         return 9999.9f;
8676                 }
8677         case DOA_DOCK_STAY:
8678                 //      Compute the desired global orientation matrix for the docker's station.
8679                 //      That is, the normal vector of the docking station must be the same as the
8680                 //      forward vector and the vector between its two points must be the uvec.
8681                 set_goal_dock_orient(&dom, &pm1->docking_bays[dockee_index], &pm0->docking_bays[docker_index], &dobjp->orient, &objp->orient);
8682
8683                 //      Compute distance between dock bay points.
8684                 vector  db0, db1, db2, db3;
8685
8686                 vm_vec_unrotate(&db0, &pm0->docking_bays[docker_index].pnt[0], &objp->orient);
8687                 vm_vec_add2(&db0, &objp->pos);
8688
8689                 vm_vec_unrotate(&db1, &pm0->docking_bays[docker_index].pnt[1], &objp->orient);
8690                 vm_vec_add2(&db1, &objp->pos);
8691
8692                 vm_vec_unrotate(&db2, &pm1->docking_bays[dockee_index].pnt[0], &dobjp->orient);
8693                 vm_vec_add2(&db2, &dobjp->pos);
8694
8695                 vm_vec_unrotate(&db3, &pm1->docking_bays[dockee_index].pnt[1], &dobjp->orient);
8696                 vm_vec_add2(&db3, &dobjp->pos);
8697
8698                 vm_vec_avg(&goal_point, &db2, &db3);
8699
8700                 vm_vec_avg(&docker_point, &db0, &db1);
8701                 vm_vec_sub2(&docker_point, &objp->pos);
8702
8703                 if (dock_mode == DOA_DOCK) {
8704                         vector  t1, t2;
8705                         vector  w_in, w_out, vel_limit, acc_limit;
8706
8707                         fdist = vm_vec_dist_quick(vm_vec_avg(&t1, &db0, &db1), vm_vec_avg(&t2, &db2, &db3));
8708
8709                         //      Compute new orientation matrix and update rotational velocity.
8710                         w_in = objp->phys_info.rotvel;
8711                         vel_limit = objp->phys_info.max_rotvel;
8712                         vm_vec_copy_scale(&acc_limit, &vel_limit, 0.3f);
8713
8714                         if (sip0->flags & SIF_SUPPORT)
8715                                 vm_vec_scale(&acc_limit, 2.0f);
8716
8717                         vm_matrix_interpolate(&dom, &objp->orient, &w_in, flFrametime, &nm, &w_out, &vel_limit, &acc_limit);
8718                         objp->phys_info.rotvel = w_out;
8719                         objp->orient = nm;
8720
8721                         //      Note, we're interested in distance from goal, so if we're still turning, bash that into return value.
8722                         fdist += 10.0f * vm_vec_mag_quick(&w_out);
8723
8724                         dock_move_towards_point(objp, &docker_point, &goal_point, speed_scale, dobjp->phys_info.speed);
8725                 } else {
8726                         SDL_assert(dock_mode == DOA_DOCK_STAY);
8727                         objp->orient = dom;
8728                         vector  temp;
8729                         vm_vec_sub(&temp, &goal_point, &docker_point);
8730                         vm_vec_sub(&objp->pos, &goal_point, &docker_point);
8731                 }
8732
8733                 break;
8734         case DOA_UNDOCK_1: {
8735                 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8736                         return 9999.9f;
8737                 }
8738
8739                 //      Undocking.
8740                 //      Move to point on dock path nearest to dock station.
8741                 SDL_assert(aip->path_length >= 2);
8742                 goal_point = Path_points[aip->path_start + aip->path_length-2].pos;
8743
8744                 vm_vec_zero(&docker_point);
8745                 fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8746
8747                 dock_move_towards_point(objp, &docker_point, &goal_point, speed_scale);
8748
8749                 break;
8750                           }
8751
8752         case DOA_UNDOCK_2: {
8753                 //      Undocking.
8754                 //      Move to point on dock path nearest to dock station and orient away from big ship.
8755                 int             desired_index;
8756
8757                 if (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) {
8758                         return 9999.9f;
8759                 }
8760
8761                 SDL_assert(aip->path_length >= 2);
8762 //              if (aip->path_length >= 3)
8763 //                      desired_index = aip->path_length-3;
8764 //              else
8765                         desired_index = aip->path_length-2;
8766
8767                 goal_point = Path_points[aip->path_start + desired_index].pos;
8768
8769                 dock_move_towards_point(objp, NULL, &goal_point, speed_scale);
8770
8771                 fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8772                 break;
8773                           }
8774         case DOA_UNDOCK_3: {
8775                 float           dist, goal_dist;
8776                 vector  away_vec;
8777
8778                 goal_dist = objp->radius + dobjp->radius + 25.0f;
8779
8780                 dist = vm_vec_normalized_dir(&away_vec, &objp->pos, &dobjp->pos);
8781                 vm_vec_scale_add(&goal_point, &dobjp->pos, &away_vec, goal_dist);
8782                 if (vm_vec_dist_quick(&goal_point, &dobjp->pos) < vm_vec_dist_quick(&objp->pos, &dobjp->pos))
8783                         fdist = 0.0f;
8784                 else {
8785                         float   dot, accel;
8786                         float turn_time = Ship_info[Ships[objp->instance].ship_info_index].srotation_time;
8787                         ai_turn_towards_vector(&goal_point, objp, flFrametime, turn_time, NULL, NULL, 0.0f, 0);
8788
8789                         dot = vm_vec_dot(&objp->orient.v.fvec, &away_vec);
8790                         accel = 0.1f;
8791                         if (dot > accel)
8792                                 accel = dot;
8793                         if (dist > goal_dist/2)
8794                                 accel *= 1.2f - 0.5f*goal_dist/dist;
8795
8796                         accelerate_ship(aip, accel);
8797                         fdist = vm_vec_dist_quick(&objp->pos, &goal_point);
8798                 }
8799
8800                 break;
8801                                                          }
8802         }
8803
8804 #ifndef NDEBUG
8805         //      For debug purposes, compute global orientation of both dock vectors and show
8806         //      how close they are.
8807         vector  d0, d1;
8808
8809         vm_vec_unrotate(&d0, &pm0->docking_bays[docker_index].norm[0], &objp->orient);
8810         vm_vec_unrotate(&d1, &pm1->docking_bays[dockee_index].norm[0], &dobjp->orient);
8811
8812         //nprintf(("AI", "or/app: dist = %7.3f/%7.3f, dot = %7.3f, global dot = %7.3f\n", 
8813         //      vm_vec_dist_quick(&goal_point, &objp->pos), fdist,
8814         //      vm_vec_dot(&objp->orient.v.fvec, &dom.v.fvec), 
8815         //      vm_vec_dot(&d0, &d1)));
8816 #endif
8817
8818         // -- Note, A lot of callers don't care about fdist, so OK to return ERROR value: SDL_assert(fdist != UNINITIALIZED_VALUE);
8819         return fdist;
8820
8821 }
8822
8823 void debug_find_guard_object()
8824 {
8825         ship                    *shipp = &Ships[Pl_objp->instance];     
8826         object          *objp;
8827
8828         for ( objp = GET_FIRST(&obj_used_list); objp !=END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) ) {
8829                 if ((Pl_objp != objp) && (objp->type == OBJ_SHIP)) {
8830                         if (objp->instance != -1) {
8831                                 if (Ships[objp->instance].team == shipp->team)  {
8832                                         // nprintf(("AI", "Setting guard object for %s to %s\n", shipp->ship_name, Ships[objp->instance].ship_name));
8833                                         ai_set_guard_object(Pl_objp, objp);
8834                                 }
8835                         }
8836                 }
8837         }
8838
8839 }
8840
8841 //      Given an object number, return the number of ships attacking it.
8842 int num_ships_attacking(int objnum)
8843 {
8844         object  *objp;
8845         ship_obj        *so;
8846         int             count = 0;
8847
8848         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
8849                 objp = &Objects[so->objnum];
8850                 if (objp->instance != -1) {
8851                         ai_info *aip;
8852                         aip = &Ai_info[Ships[objp->instance].ai_index];
8853
8854                         if ((aip->mode == AIM_CHASE) && (aip->target_objnum == objnum))
8855                                 if (Ships[objp->instance].team != Ships[Objects[objnum].instance].team)
8856                                         count++;
8857                 }
8858         }
8859
8860         return count;
8861 }
8862
8863 //      For all objects attacking object #objnum, remove the one that is farthest away.
8864 //      Do this by resuming previous behavior, if any.  If not, set target_objnum to -1.
8865 void remove_farthest_attacker(int objnum)
8866 {
8867         object  *objp, *objp2, *farthest_objp;
8868         ship_obj        *so;
8869         float           farthest_dist;
8870
8871         objp2 = &Objects[objnum];
8872
8873         farthest_dist = 9999999.9f;
8874         farthest_objp = NULL;
8875
8876         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
8877                 objp = &Objects[so->objnum];
8878                 if ( !(objp->flags & OF_PLAYER_SHIP)) {
8879                         if (objp->instance != -1) {
8880                                 ai_info *aip2;
8881
8882                                 aip2 = &Ai_info[Ships[objp->instance].ai_index];
8883
8884                                 if ((aip2->mode == AIM_CHASE) && (aip2->target_objnum == objnum)) {
8885                                         if (Ships[objp->instance].team != Ships[Objects[objnum].instance].team) {
8886                                                 float   dist;
8887
8888                                                 dist = vm_vec_dist_quick(&objp->pos, &objp2->pos);
8889                                                 if (dist < farthest_dist) {
8890                                                         farthest_dist = dist;
8891                                                         farthest_objp = objp;
8892                                                 }
8893                                         }
8894                                 }
8895                         }
8896                 }
8897         }
8898
8899         if (farthest_objp != NULL) {
8900                 ai_info *aip;
8901                 SDL_assert(farthest_objp->type == OBJ_SHIP);
8902                 SDL_assert((farthest_objp->instance > -1) && (farthest_objp->instance < MAX_SHIPS));
8903                 SDL_assert(Ships[farthest_objp->instance].ai_index > -1);
8904
8905                 aip = &Ai_info[Ships[farthest_objp->instance].ai_index];
8906
8907                 if (!maybe_resume_previous_mode(Pl_objp, aip)) {
8908                         //      If already ignoring something under player's orders, don't ignore current target.
8909                         if ((aip->ignore_objnum == UNUSED_OBJNUM) || (aip->ai_flags & AIF_TEMPORARY_IGNORE)) {
8910                                 aip->ignore_objnum = aip->target_objnum;
8911                                 aip->ignore_signature = Objects[aip->target_objnum].signature;
8912                                 aip->ai_flags |= AIF_TEMPORARY_IGNORE;
8913                                 aip->ignore_expire_timestamp = timestamp(((myrand() % 10) + 20) * 1000);        //      OK to attack again in 20 to 24 seconds.
8914                         }
8915                         aip->target_objnum = -1;
8916                         ai_do_default_behavior(farthest_objp);
8917                 }
8918         }
8919 }
8920
8921 // Maybe limit the number of attackers on attack_objnum.  For now, only limit attackers
8922 // in attacked_objnum is the player
8923 // input:       attacked_objnum =>              object index for ship we want to limit attacks on
8924 //
8925 //      exit:                   1       =>      num attackers exceeds maximum, abort
8926 //                                      0       =>      removed the farthest attacker
8927 //                                      -1      =>      nothing was done
8928 int ai_maybe_limit_attackers(int attacked_objnum)
8929 {
8930         int rval=-1;
8931
8932         // limit the number of ships attacking the _player_ only
8933 //      if ( attacked_objnum == OBJ_INDEX(Player_obj) ) {
8934         if ( Objects[attacked_objnum].flags & OF_PLAYER_SHIP) {
8935                 int num_attacking;
8936                 num_attacking = num_ships_attacking(attacked_objnum);
8937
8938                 if (num_attacking == Skill_level_max_attackers[Game_skill_level]) {
8939                         remove_farthest_attacker(attacked_objnum);
8940                         rval=0;
8941                 } else if (num_attacking > Skill_level_max_attackers[Game_skill_level]) {
8942                         rval=1;
8943                 }
8944                 //nprintf(("AI", "Num attacking player = %i\n", num_attacking));
8945         }
8946
8947         return rval;
8948 }
8949
8950 //      Object being guarded by object *guard_objp was hit by object *hitter_objp
8951 void guard_object_was_hit(object *guard_objp, object *hitter_objp)
8952 {
8953         int             hitter_objnum;
8954         ai_info *aip;
8955
8956         aip = &Ai_info[Ships[guard_objp->instance].ai_index];
8957
8958         if (guard_objp == hitter_objp) {
8959                 // Int3();      //      Bogus!  Who tried to get me to attack myself!  Trace out and fix!
8960                 return;
8961         }
8962
8963         if (guard_objp->type == OBJ_GHOST || hitter_objp->type == OBJ_GHOST)
8964                 return;
8965
8966         if (aip->ai_flags & AIF_NO_DYNAMIC)     //      Not allowed to pursue dynamic goals.  So, why are we guarding?
8967                 return;
8968
8969         SDL_assert( (hitter_objp->type == OBJ_SHIP) || (hitter_objp->type == OBJ_ASTEROID) || (hitter_objp->type == OBJ_WEAPON) );
8970
8971         hitter_objnum = OBJ_INDEX(hitter_objp);
8972
8973         if ( hitter_objp->type == OBJ_SHIP ) {
8974                 //      If the hitter object is the ignore object, don't attack it.
8975                 if (is_ignore_object(aip, hitter_objp-Objects))
8976                         return;
8977
8978                 //      If hitter is on same team as me, don't attack him.
8979                 if (Ships[guard_objp->instance].team == Ships[hitter_objp->instance].team)
8980                         return;
8981
8982                 // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
8983                 if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
8984                         return;
8985                 }
8986
8987                 // dont attack if you can't see him
8988                 if ( awacs_get_level(hitter_objp, &Ships[aip->shipnum], 1) < 1 ) {
8989                         // if he's a stealth and visible, but not targetable, ok to attack.
8990                         if ( is_object_stealth_ship(hitter_objp) ) {
8991                                 if ( ai_is_stealth_visible(guard_objp, hitter_objp) != STEALTH_VISIBLE ) {
8992                                         return;
8993                                 }
8994                         }
8995                 }
8996         }
8997
8998         if (aip->target_objnum == -1) {
8999                 aip->ok_to_target_timestamp = timestamp(0);
9000         }
9001
9002         if ((aip->submode == AIS_GUARD_PATROL) || (aip->submode == AIS_GUARD_STATIC)) {
9003
9004                 if ( hitter_objp->type == OBJ_SHIP ) {
9005                         if (!(Ship_info[Ships[guard_objp->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
9006                                 return;
9007                         }
9008
9009                         // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
9010                         if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
9011                                 return;
9012                         }
9013                 }
9014
9015                 if (aip->target_objnum != hitter_objnum) {
9016                         aip->aspect_locked_time = 0.0f;
9017                 }
9018
9019                 aip->ok_to_target_timestamp = timestamp(0);
9020
9021                 set_target_objnum(aip, hitter_objnum);
9022                 //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));
9023                 aip->previous_mode = AIM_GUARD;
9024                 aip->previous_submode = aip->submode;
9025                 aip->mode = AIM_CHASE;
9026                 aip->submode = SM_ATTACK;
9027                 aip->submode_start_time = Missiontime;
9028                 aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
9029         } else if (aip->previous_mode == AIM_GUARD) {
9030                 if (aip->target_objnum == -1) {
9031
9032                         if ( hitter_objp->type == OBJ_SHIP ) {
9033                                 // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
9034                                 if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
9035                                         return;
9036                                 }
9037                         }
9038
9039                         set_target_objnum(aip, hitter_objnum);
9040                 //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));
9041                         aip->mode = AIM_CHASE;
9042                         aip->submode = SM_ATTACK;
9043                         aip->submode_start_time = Missiontime;
9044                         aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
9045                 } else {
9046                         int     num_attacking_cur, num_attacking_new;
9047
9048                         num_attacking_cur = num_ships_attacking(aip->target_objnum);
9049                         if (num_attacking_cur > 1) {
9050                                 num_attacking_new = num_ships_attacking(hitter_objnum);
9051
9052                                 if (num_attacking_new < num_attacking_cur) {
9053
9054                                         if ( hitter_objp->type == OBJ_SHIP ) {
9055                                                 // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
9056                                                 if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
9057                                                         return;
9058                                                 }
9059                                         }
9060                                         set_target_objnum(aip, hitter_objp-Objects);
9061                 //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));
9062                                         aip->mode = AIM_CHASE;
9063                                         aip->submode = SM_ATTACK;
9064                                         aip->submode_start_time = Missiontime;
9065                                         aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
9066                                 }
9067                         }
9068                 }
9069         }
9070 }
9071
9072 //      Ship object *hit_objp was hit by ship object *hitter_objp.
9073 //      See if anyone is guarding hit_objp and, if so, do something useful.
9074 void maybe_update_guard_object(object *hit_objp, object *hitter_objp)
9075 {
9076         object  *objp;
9077         ship_obj        *so;
9078
9079         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
9080                 objp = &Objects[so->objnum];
9081                 if (objp->instance != -1) {
9082                         ai_info *aip;
9083                         aip = &Ai_info[Ships[objp->instance].ai_index];
9084
9085                         if ((aip->mode == AIM_GUARD) || (aip->active_goal == AI_ACTIVE_GOAL_DYNAMIC)) {
9086                                 if (aip->guard_objnum == hit_objp-Objects) {
9087                                         guard_object_was_hit(objp, hitter_objp);
9088                                 } else if ((aip->guard_wingnum != -1) && (aip->guard_wingnum == Ai_info[Ships[hit_objp->instance].ai_index].wing)) {
9089                                         guard_object_was_hit(objp, hitter_objp);
9090                                 }
9091                         }
9092                 }
9093         }
9094 }
9095
9096 // Scan missile list looking for bombs homing on guarded_objp
9097 // return 1 if bomb is found (and targeted by guarding_objp), otherwise return 0
9098 int ai_guard_find_nearby_bomb(object *guarding_objp, object *guarded_objp)
9099 {       
9100         missile_obj     *mo;
9101         object          *bomb_objp, *closest_bomb_objp=NULL;
9102         float                   dist, dist_to_guarding_obj,closest_dist_to_guarding_obj=999999.0f;
9103         weapon          *wp;
9104         weapon_info     *wip;
9105
9106         for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
9107                 SDL_assert(mo->objnum >= 0 && mo->objnum < MAX_OBJECTS);
9108                 bomb_objp = &Objects[mo->objnum];
9109
9110                 wp = &Weapons[bomb_objp->instance];
9111                 wip = &Weapon_info[wp->weapon_info_index];
9112
9113                 if ( !(wip->wi_flags & WIF_BOMB) ) {
9114                         continue;
9115                 }
9116
9117                 if ( wp->homing_object != guarded_objp ) {
9118                         continue;
9119                 }
9120
9121                 dist = vm_vec_dist_quick(&bomb_objp->pos, &guarded_objp->pos);
9122
9123                 if (dist < (MAX_GUARD_DIST + guarded_objp->radius)*3) {
9124                         dist_to_guarding_obj = vm_vec_dist_quick(&bomb_objp->pos, &guarding_objp->pos);
9125                         if ( dist_to_guarding_obj < closest_dist_to_guarding_obj ) {
9126                                 closest_dist_to_guarding_obj = dist_to_guarding_obj;
9127                                 closest_bomb_objp = bomb_objp;
9128                         }
9129                 }
9130         }
9131
9132         if ( closest_bomb_objp ) {
9133                 guard_object_was_hit(guarding_objp, closest_bomb_objp);
9134                 return 1;
9135         }
9136
9137         return 0;
9138 }
9139
9140 //      Scan enemy ships and see if one is near enough to guard object to be pursued.
9141 void ai_guard_find_nearby_ship(object *guarding_objp, object *guarded_objp)
9142 {
9143         ship            *guarding_shipp = &Ships[guarding_objp->instance];
9144         ai_info *guarding_aip = &Ai_info[guarding_shipp->ai_index];
9145         ship_obj        *so;
9146         object  *enemy_objp;
9147         float           dist;
9148
9149         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
9150                 enemy_objp = &Objects[so->objnum];
9151
9152                 if (enemy_objp->instance < 0) {
9153                         continue;
9154                 }
9155
9156                 ship    *eshipp = &Ships[enemy_objp->instance];
9157
9158                 //      Don't attack a cargo container or other harmless ships
9159                 if (!(Ship_info[eshipp->ship_info_index].flags & SIF_HARMLESS)) {
9160                         if (guarding_shipp->team != eshipp->team)       {
9161                                 dist = vm_vec_dist_quick(&enemy_objp->pos, &guarded_objp->pos);
9162                                 if (dist < (MAX_GUARD_DIST + guarded_objp->radius)*3) {
9163                                         guard_object_was_hit(guarding_objp, enemy_objp);
9164                                 } else if ((dist < 3000.0f) && (Ai_info[eshipp->ai_index].target_objnum == guarding_aip->guard_objnum)) {
9165                                         //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));
9166                                         guard_object_was_hit(guarding_objp, enemy_objp);
9167                                 }
9168                         }
9169                 }
9170         }
9171 }
9172
9173 // Scan for nearby asteroids.  Favor asteroids which have their collide_objnum set to that of the
9174 // guarded ship.  Also, favor asteroids that are closer to the guarding ship, since it looks cooler
9175 // when a ship blows up an asteroid then goes after the pieces that break off.
9176 void ai_guard_find_nearby_asteroid(object *guarding_objp, object *guarded_objp)
9177 {       
9178         float           dist;
9179
9180         object  *closest_asteroid_objp=NULL, *danger_asteroid_objp=NULL, *asteroid_objp;
9181         float           dist_to_self, closest_danger_asteroid_dist=999999.0f, closest_asteroid_dist=999999.0f;
9182
9183         for ( asteroid_objp = GET_FIRST(&obj_used_list); asteroid_objp != END_OF_LIST(&obj_used_list); asteroid_objp = GET_NEXT(asteroid_objp) ) {
9184                 if ( asteroid_objp->type == OBJ_ASTEROID ) {
9185                         // Attack asteroid if near guarded ship
9186                         dist = vm_vec_dist_quick(&asteroid_objp->pos, &guarded_objp->pos);
9187                         if ( dist < (MAX_GUARD_DIST + guarded_objp->radius)*2) {
9188                                 dist_to_self = vm_vec_dist_quick(&asteroid_objp->pos, &guarding_objp->pos);
9189                                 if ( OBJ_INDEX(guarded_objp) == asteroid_collide_objnum(asteroid_objp) ) {
9190                                         if( dist_to_self < closest_danger_asteroid_dist ) {
9191                                                 danger_asteroid_objp=asteroid_objp;
9192                                                 closest_danger_asteroid_dist=dist_to_self;
9193                                         }
9194                                 } 
9195                                 if ( dist_to_self < closest_asteroid_dist ) {
9196                                         // only attack if moving slower than own max speed
9197                                         if ( vm_vec_mag_quick(&asteroid_objp->phys_info.vel) < guarding_objp->phys_info.max_vel.xyz.z ) {
9198                                                 closest_asteroid_dist = dist_to_self;
9199                                                 closest_asteroid_objp = asteroid_objp;
9200                                         }
9201                                 }
9202                         }
9203                 }
9204         }
9205
9206         if ( danger_asteroid_objp ) {
9207                 guard_object_was_hit(guarding_objp, danger_asteroid_objp);
9208         } else if ( closest_asteroid_objp ) {
9209                 guard_object_was_hit(guarding_objp, closest_asteroid_objp);
9210         }
9211 }
9212
9213 //      Scan potential harmful objects and see if one is near enough to guard object to be pursued.
9214 void ai_guard_find_nearby_object()
9215 {
9216         ship                    *shipp = &Ships[Pl_objp->instance];
9217         ai_info         *aip = &Ai_info[shipp->ai_index];
9218         object          *guardobjp;
9219         int                     bomb_found=0;
9220
9221         guardobjp = &Objects[aip->guard_objnum];
9222         
9223         // highest priority is a bomb fired on guarded ship
9224         bomb_found = ai_guard_find_nearby_bomb(Pl_objp, guardobjp);
9225
9226         if ( !bomb_found ) {
9227                 // check for ships if there are no bombs fired at guarded ship
9228                 ai_guard_find_nearby_ship(Pl_objp, guardobjp);
9229
9230                 // if not attacking anything, go for asteroid close to guarded ship
9231                 if ( (aip->target_objnum == -1) && asteroid_count() ) {
9232                         ai_guard_find_nearby_asteroid(Pl_objp, guardobjp);
9233                 }
9234         }
9235 }
9236
9237 // gets closest point on extended axis of cylinder, r_vec, and radius of cylinder
9238 // returns z of axis_point in cyl_objp reference frame
9239 float get_cylinder_points(object *other_objp, object *cyl_objp, vector *axis_pt, vector *r_vec, float *radius)
9240 {
9241         SDL_assert(other_objp->type == OBJ_SHIP);
9242         SDL_assert(cyl_objp->type == OBJ_SHIP);
9243
9244         // get radius of cylinder
9245         polymodel *pm = model_get(Ships[cyl_objp->instance].modelnum);
9246         float tempx, tempy;
9247         tempx = max(-pm->mins.xyz.x, pm->maxs.xyz.x);
9248         tempy = max(-pm->mins.xyz.y, pm->maxs.xyz.y);
9249         *radius = max(tempx, tempy);
9250
9251         // get vec from cylinder to other_obj
9252         vector r_sph;
9253         vm_vec_sub(&r_sph, &other_objp->pos, &cyl_objp->pos);
9254
9255         // get point on axis and on cylinder
9256         // extended_cylinder_z is along extended cylinder
9257         // cylinder_z is capped within cylinder
9258         float extended_cylinder_z = vm_vec_dotprod(&r_sph, &cyl_objp->orient.v.fvec);
9259
9260         // get pt on axis of extended cylinder
9261         vm_vec_scale_add(axis_pt, &cyl_objp->pos, &cyl_objp->orient.v.fvec, extended_cylinder_z);
9262
9263         // get r_vec (pos - axis_pt) normalized
9264         vm_vec_normalized_dir(r_vec, &other_objp->pos, axis_pt);
9265
9266         return extended_cylinder_z;
9267 }
9268
9269 // handler for guard behavior when guarding BIG ships
9270 //      When someone has attacked guarded ship, then attack that ship.
9271 // To attack another ship, switch out of guard mode into chase mode.
9272 void ai_big_guard()
9273 {
9274         
9275         ship                    *shipp = &Ships[Pl_objp->instance];
9276         ai_info         *aip = &Ai_info[shipp->ai_index];
9277         object          *guard_objp;
9278
9279         // sanity checks already done in ai_guard()
9280         guard_objp = &Objects[aip->guard_objnum];
9281
9282         switch (aip->submode) {
9283         case AIS_GUARD_STATIC:
9284         case AIS_GUARD_PATROL:
9285                 {
9286                 vector axis_pt, r_vec, theta_vec;
9287                 float radius, extended_z;
9288
9289                 // get random [0 to 1] based on OBJNUM
9290                 float objval = static_randf(Pl_objp-Objects);
9291
9292                 // get position relative to cylinder of guard_objp              
9293                 extended_z = get_cylinder_points(Pl_objp, guard_objp, &axis_pt, &r_vec, &radius);
9294                 vm_vec_crossprod(&theta_vec, &guard_objp->orient.v.fvec, &r_vec);
9295
9296                 // half ships circle each way
9297                 if (objval > 0.5f) {
9298                         vm_vec_negate(&theta_vec);
9299                 }
9300
9301                 float min_guard_dist = radius + Pl_objp->radius + 50.0f;
9302                 float desired_guard_dist = min_guard_dist + 0.5f * ((1.0f + objval) * MAX_GUARD_DIST);
9303                 float max_guard_dist =     min_guard_dist + 1.0f * ((1.0f + objval) * MAX_GUARD_DIST);
9304
9305                 // get z extents
9306                 float min_z, max_z, length;
9307                 polymodel *pm = model_get(Ships[guard_objp->instance].modelnum);
9308                 min_z = pm->mins.xyz.z;
9309                 max_z = pm->maxs.xyz.z;
9310                 length = max_z - min_z;
9311
9312                 // get desired z
9313                 // how often to choose new desired_z
9314                 // 1*(64) sec < 2000, 2*(64) < 2-4000 3*(64) > 4-8000, etc (Missiontime >> 22 is 64 sec intervals)
9315                 int time_choose = int(floor(log(length * 0.001) / log(2.0)));
9316                 float desired_z = min_z + length * static_randf( (Pl_objp-Objects) ^ (Missiontime >> (22 + time_choose)) );
9317
9318                 // get r from guard_ship
9319                 float cur_guard_rad = vm_vec_dist(&Pl_objp->pos, &axis_pt);
9320
9321                 // is ship within extents of cylinder of ship it is guarding
9322                 int inside = (extended_z > min_z) && (extended_z < min_z + length);
9323
9324                 vector goal_pt;
9325                 // maybe go into orbit mode
9326                 if (cur_guard_rad < max_guard_dist) {
9327                         if ( cur_guard_rad > min_guard_dist ) {
9328                                 if (inside) {
9329                                         // orbit
9330                                         vm_vec_scale_add(&goal_pt, &axis_pt, &r_vec, desired_guard_dist);
9331                                         vm_vec_scale_add2(&goal_pt, &theta_vec, desired_guard_dist);
9332                                 } else {
9333                                         // move to where I can orbit
9334                                         if (extended_z < min_z) {
9335                                                 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, min_z);
9336                                         } else {
9337                                                 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, max_z);
9338                                         }
9339                                         vm_vec_scale_add2(&goal_pt, &r_vec, desired_guard_dist);
9340                                         vm_vec_scale_add2(&goal_pt, &theta_vec, desired_guard_dist);
9341                                 }
9342                         } else {
9343                                 // too close for orbit mode
9344                                 if (inside) {
9345                                         // inside (fly straight out and return circle)
9346                                         vm_vec_scale_add(&goal_pt, &axis_pt, &r_vec, max_guard_dist);
9347                                 } else {
9348                                         // outside (fly to edge and circle)
9349                                         if (extended_z < min_z) {
9350                                                 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, min_z);
9351                                         } else {
9352                                                 vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, max_z);
9353                                         }
9354                                         vm_vec_scale_add2(&goal_pt, &r_vec, max_guard_dist);
9355                                         vm_vec_scale_add2(&goal_pt, &theta_vec, desired_guard_dist);
9356                                 }
9357                         }
9358
9359                         if (Pl_objp->phys_info.fspeed > 0) {
9360                                 // modify goal_pt to take account moving guard objp
9361                                 float dist = vm_vec_dist_quick(&Pl_objp->pos, &goal_pt);
9362                                 float time = dist / Pl_objp->phys_info.fspeed;
9363                                 vm_vec_scale_add2(&goal_pt, &guard_objp->phys_info.vel, time);
9364
9365                                 // now modify to move to desired z (at a max of 20 m/s)
9366                                 float delta_z = desired_z - extended_z;
9367                                 float v_z = delta_z * 0.2f;
9368                                 if (v_z < -20) {
9369                                         v_z = -20.0f;
9370                                 } else if (v_z > 20) {
9371                                         v_z = 20.0f;
9372                                 }
9373
9374                                 vm_vec_scale_add2(&goal_pt, &guard_objp->orient.v.fvec, v_z*time);
9375                         }
9376
9377                 } else {
9378                         // cast vector to center of guard_ship adjusted by desired_z
9379                         float delta_z = desired_z - extended_z;
9380                         vm_vec_scale_add(&goal_pt, &guard_objp->pos, &guard_objp->orient.v.fvec, delta_z);
9381                 }
9382
9383                 // try not to bump into things along the way
9384                 if ( (cur_guard_rad > max_guard_dist) || (extended_z < min_z) || (extended_z > max_z) ) {
9385                         if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_pt, 5.0f)) {
9386                                 return;
9387                         }
9388
9389                         if (avoid_player(Pl_objp, &goal_pt)) {
9390                                 return;
9391                         }
9392                 } else {
9393                         if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_pt, 5.0f)) {
9394                                 return;
9395                         }
9396                 }
9397
9398                 // got the point, now let's go there
9399                 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);
9400 //              aip->goal_point = goal_pt;
9401                 accelerate_ship(aip, 1.0f);
9402
9403                 //      Periodically, scan for a nearby ship to attack.
9404                 if (((AI_FrameCount ^ (Pl_objp-Objects)) & 0x07) == 0) {
9405                         ai_guard_find_nearby_object();
9406                 }
9407                 }
9408                 break;
9409
9410         case AIS_GUARD_ATTACK:
9411                 //      The guarded ship has been attacked.  Do something useful!
9412                 ai_chase();
9413                 break;
9414
9415         default:
9416                 //Int3();       //      Illegal submode for Guard mode.
9417                 // AL 06/03/97 comment out Int3() to allow milestone to get out the door
9418                 aip->submode = AIS_GUARD_PATROL;
9419                 break;
9420         }
9421 }
9422
9423 //      Main handler for guard behavior.
9424 //      When someone has attacked guarded ship, then attack that ship.
9425 // To attack another ship, switch out of guard mode into chase mode.
9426 void ai_guard()
9427 {
9428         ship                    *shipp = &Ships[Pl_objp->instance];
9429         ai_info         *aip = &Ai_info[shipp->ai_index];
9430         object          *guard_objp;    
9431         float                   dist_to_guardobj;
9432         vector          vec_to_guardobj;
9433
9434         /*      //      Debug code, find an object to guard.
9435         int finding_guard_objnum = 0;   //      Debug code, to see if body of "if" below gets executed. 
9436         if (aip->guard_objnum == -1) {
9437                 finding_guard_objnum = 1;
9438                 debug_find_guard_object();
9439                 if (aip->guard_objnum == -1)
9440                         return;
9441         }
9442 */
9443         if (aip->guard_objnum == -1) {
9444                 aip->mode = AIM_NONE;
9445                 return;
9446         }
9447
9448         SDL_assert(aip->guard_objnum != -1);
9449
9450         guard_objp = &Objects[aip->guard_objnum];
9451
9452         if (guard_objp == Pl_objp) {
9453                 Int3();         //      This seems illegal.  Why is a ship guarding itself?
9454                 aip->guard_objnum = -1;
9455                 return;
9456         }
9457
9458         // check that I have someone to guard
9459         if (guard_objp->instance == -1) {
9460                 return;
9461         }
9462
9463         //      Not sure whether this should be impossible, or a reasonable cleanup condition.
9464         //      For now (3/31/97), it's getting trapped by an SDL_assert, so clean it up.
9465         if (guard_objp->type != OBJ_SHIP) {
9466                 aip->guard_objnum = -1;
9467                 return;
9468         }
9469
9470         // handler for gurad object with BIG radius
9471         if (guard_objp->radius > BIG_GUARD_RADIUS) {
9472                 ai_big_guard();
9473                 return;
9474         }
9475
9476         float                   objval;
9477         vector          goal_point;
9478         vector          rel_vec;
9479         float                   dist_to_goal_point, dot_to_goal_point, accel_scale;
9480         vector          v2g, rvec;
9481
9482         // get random [0 to 1] based on OBJNUM
9483         objval = static_randf(Pl_objp-Objects);
9484
9485         switch (aip->submode) {
9486         case AIS_GUARD_STATIC:
9487         case AIS_GUARD_PATROL:
9488                 //      Stay near ship
9489                 dist_to_guardobj = vm_vec_normalized_dir(&vec_to_guardobj, &guard_objp->pos, &Pl_objp->pos);
9490
9491                 rel_vec = aip->guard_vec;
9492                 vm_vec_add(&goal_point, &guard_objp->pos, &rel_vec);
9493
9494                 vm_vec_normalized_dir(&v2g, &goal_point, &Pl_objp->pos);
9495                 dist_to_goal_point = vm_vec_dist_quick(&goal_point, &Pl_objp->pos);
9496                 dot_to_goal_point = vm_vec_dot(&v2g, &Pl_objp->orient.v.fvec);
9497                 accel_scale = (1.0f + dot_to_goal_point)/2.0f;
9498
9499                 //      If far away, get closer
9500                 if (dist_to_goal_point > MAX_GUARD_DIST + 1.5 * (Pl_objp->radius + guard_objp->radius)) {
9501                         if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_point, 5.0f)) {
9502                                 return;
9503                         }
9504
9505                         if (avoid_player(Pl_objp, &goal_point)) {
9506                                 return;
9507                         }
9508
9509                         // quite far away, so try to go straight to 
9510                         compute_desired_rvec(&rvec, &goal_point, &Pl_objp->pos);
9511                         ai_turn_towards_vector(&goal_point, Pl_objp, flFrametime, Ship_info[shipp->ship_info_index].srotation_time, NULL, NULL, 0.0f, 0, &rvec);
9512
9513                         accelerate_ship(aip, accel_scale * (0.25f + dist_to_goal_point/700.0f));
9514                 } else {
9515                         if (maybe_avoid_big_ship(Pl_objp, guard_objp, aip, &goal_point, 2.0f)) {
9516                                 return;
9517                         }
9518
9519                         // get max of guard_objp (1) normal speed (2) dock speed
9520                         float speed = guard_objp->phys_info.speed;
9521
9522                         if (guard_objp->type == OBJ_SHIP) {
9523                                 ai_info *guard_aip = &Ai_info[Ships[guard_objp->instance].ai_index];
9524
9525                                 if (guard_aip->dock_objnum != -1) {
9526                                         speed = max(speed, Objects[guard_aip->dock_objnum].phys_info.speed);
9527                                 }
9528                         }
9529                         
9530                         //      Deal with guarding a small object.
9531                         //      If going to guard_vec might cause a collision with guarded object, pick a new guard point.
9532                         if (vm_vec_dot(&v2g, &vec_to_guardobj) > 0.8f) {
9533                                 if (dist_to_guardobj < dist_to_goal_point) {
9534                                         ai_set_guard_vec(Pl_objp, guard_objp);  //      OK to return here.
9535                                         return;
9536                                 }
9537                         } 
9538
9539                         if (speed > 10.0f) {
9540                                 //      If goal ship is moving more than a tiny bit, don't orbit it, get near it.
9541                                 if (vm_vec_dist_quick(&goal_point, &Pl_objp->pos) > 40.0f) {
9542                                         if (vm_vec_dot(&Pl_objp->orient.v.fvec, &v2g) < 0.0f) {
9543                                                 //      Just slow down, don't turn.
9544                                                 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed - dist_to_goal_point/10.0f);
9545                                         } else {
9546                                                 //      Goal point is in front.
9547
9548                                                 //      If close to goal point, don't change direction, just change speed.
9549                                                 if (dist_to_goal_point > Pl_objp->radius + 10.0f) {
9550                                                         turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
9551                                                 }
9552                                                 
9553                                                 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed + (dist_to_goal_point-40.0f)/20.0f);
9554                                         }
9555                                 } else {
9556                                         if (dot_to_goal_point > 0.8f) {
9557                                                 turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
9558                                                 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed + dist_to_goal_point*0.1f);
9559                                         } else {
9560                                                 set_accel_for_target_speed(Pl_objp, guard_objp->phys_info.speed - dist_to_goal_point*0.1f - 1.0f);
9561                                         }
9562                                 }
9563                         // consider guard object STILL
9564                         } else if (guard_objp->radius < 50.0f) {
9565                                 if (dist_to_goal_point > 15.0f) {
9566                                         turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
9567                                         set_accel_for_target_speed(Pl_objp, (dist_to_goal_point-10.0f)/2.0f);
9568                                 } else if (Pl_objp->phys_info.speed < 1.0f) {
9569                                         turn_away_from_point(Pl_objp, &guard_objp->pos, 0.0f);
9570                                 }
9571                                 //      It's a big ship
9572                         } else if (dist_to_guardobj > MAX_GUARD_DIST + Pl_objp->radius + guard_objp->radius) {
9573                                 //      Orbiting ship, too far away
9574                                 float dot = turn_towards_tangent(Pl_objp, &guard_objp->pos, (1.0f + objval/2) * guard_objp->radius);
9575                                 accelerate_ship(aip, (1.0f + dot)/2.0f);
9576                         } else if (dist_to_guardobj < Pl_objp->radius + guard_objp->radius) {
9577                                 //      Orbiting ship, got too close
9578                                 turn_away_from_point(Pl_objp, &guard_objp->pos, 0.0f);
9579                                 if ((dist_to_guardobj > guard_objp->radius + Pl_objp->radius + 50.0f) && (guard_objp->phys_info.speed > Pl_objp->phys_info.speed - 1.0f))
9580                                         change_acceleration(aip, 0.25f);
9581                                 else
9582                                         accelerate_ship(aip, 0.5f + objval/4.0f);
9583                         } else {
9584                                 //      Orbiting ship, about the right distance away.
9585                                 float dot = turn_towards_tangent(Pl_objp, &guard_objp->pos, (1.5f + objval/2.0f)*guard_objp->radius);
9586                                 if ((dist_to_guardobj > guard_objp->radius + Pl_objp->radius + 50.0f) && (guard_objp->phys_info.speed > Pl_objp->phys_info.speed - 1.0f))
9587                                         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));
9588                                 else
9589                                         accelerate_ship(aip, 0.5f * (1.0f + dot) * (0.3f + objval/3.0f));
9590                         }
9591                 }
9592
9593                 //      Periodically, scan for a nearby ship to attack.
9594                 if (((AI_FrameCount ^ (Pl_objp-Objects)) & 0x07) == 0) {
9595                         ai_guard_find_nearby_object();
9596                 }
9597                 break;
9598
9599         case AIS_GUARD_ATTACK:
9600                 //      The guarded ship has been attacked.  Do something useful!
9601                 ai_chase();
9602
9603                 break;
9604         default:
9605                 //Int3();       //      Illegal submode for Guard mode.
9606                 // AL 06/03/97 comment out Int3() to allow milestone to get out the door
9607                 aip->submode = AIS_GUARD_PATROL;
9608                 break;
9609         }
9610
9611 }
9612
9613 // Return the object of the ship that the given object is docked
9614 // with.  Currently, we know a ship is docked when his ai_mode is AIM_DOCK,
9615 // and his submode is AIS_DOCK_3.  I suppose that this is likely to change though.
9616 // Also, the objnum that was is passed in may not be the object that actually
9617 // performed the docking maneuver.  This code will account for that case.
9618 object *ai_find_docked_object( object *docker )
9619 {
9620         ai_info *aip;
9621
9622         // we are trying to find the dockee of docker.  (Note that that these terms
9623         // are totally relative to what is passed in as a parameter.)
9624
9625         // first thing to attempt is to check and see if this object is docked with something.
9626         SDL_assert( docker->type == OBJ_SHIP );         // this had probably better be a ship!!!
9627         aip = &Ai_info[Ships[docker->instance].ai_index];
9628         if ( !(aip->ai_flags & AIF_DOCKED) )            // flag not set if not docked with anything
9629                 return NULL;
9630
9631         if ( aip->dock_objnum == -1 ) {
9632                 Int3();                                                                                 // mwa says this is wrong wrong wrong
9633                 ai_do_objects_undocked_stuff( docker, NULL );
9634                 return NULL;
9635         }
9636
9637         return &Objects[aip->dock_objnum];
9638
9639 }
9640
9641
9642 // define for the points subtracted from score for a rearm started on a player.
9643 #define REPAIR_PENALTY          50
9644
9645
9646 // function to clean up ai flags, variables, and other interesting information
9647 // for a ship that was getting repaired.  The how parameter is useful for multiplayer
9648 // only in that it tells us why the repaired ship is being cleaned up.
9649 void ai_do_objects_repairing_stuff( object *repaired_objp, object *repair_objp, int how )
9650 {
9651         ai_info *aip, *repair_aip;
9652         int             stamp = -1;
9653
9654         SDL_assert( repaired_objp->type == OBJ_SHIP);
9655         aip = &Ai_info[Ships[repaired_objp->instance].ai_index];
9656
9657         // multiplayer
9658         int p_index;
9659         p_index = -1;
9660         if(Game_mode & GM_MULTIPLAYER){
9661                 p_index = multi_find_player_by_object(repaired_objp);           
9662         }               
9663         else {          
9664                 if(repaired_objp == Player_obj){
9665                         p_index = Player_num;
9666                 }
9667         }
9668
9669         switch( how ) {
9670         case REPAIR_INFO_BEGIN:
9671                 aip->ai_flags |= AIF_BEING_REPAIRED;
9672                 aip->ai_flags &= ~AIF_AWAITING_REPAIR;
9673                 stamp = timestamp(-1);
9674
9675                 // if this is a player ship, then subtract the repair penalty from this player's score
9676                 if ( repaired_objp->flags & OF_PLAYER_SHIP ) {
9677                         if ( !(Game_mode & GM_MULTIPLAYER) ) {
9678                                 Player->stats.m_score -= (int)(REPAIR_PENALTY * scoring_get_scale_factor());                    // subtract the penalty
9679                         } else {
9680                                 /*
9681                                 int pnum;
9682
9683                                 // multiplayer game -- find the player, then subtract the score
9684                                 pnum = multi_find_player_by_object( repaired_objp );
9685                                 if ( pnum != -1 ) {
9686                                         Net_players[pnum].player->stats.m_score -= (int)(REPAIR_PENALTY * scoring_get_scale_factor());
9687
9688                                         // squad war
9689                                         multi_team_maybe_add_score(-(int)(REPAIR_PENALTY * scoring_get_scale_factor()), Net_players[pnum].p_info.team);
9690                                 } else {
9691                                         nprintf(("Network", "Couldn't find player for ship %s for repair penalty\n", Ships[repaired_objp->instance].ship_name));
9692                                 }
9693                                 */
9694                         }
9695                 }
9696                 break;
9697
9698         case REPAIR_INFO_BROKEN:
9699                 aip->ai_flags &= ~AIF_BEING_REPAIRED;
9700                 aip->ai_flags |= AIF_AWAITING_REPAIR;
9701                 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9702                 break;
9703
9704         case REPAIR_INFO_END:
9705                 // when only awaiting repair, and the repair is ended, then set dock_objnum to -1.
9706                 if ( aip->ai_flags & AIF_AWAITING_REPAIR ){
9707                         aip->dock_objnum = -1;
9708                 }
9709                 aip->ai_flags &= ~(AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED );
9710                 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9711                 break;
9712
9713         case REPAIR_INFO_QUEUE:
9714                 aip->ai_flags |= AIF_AWAITING_REPAIR;
9715                 if ( aip == Player_ai ){
9716                         hud_support_view_start();
9717                 }
9718                 stamp = timestamp(-1);
9719                 break;
9720
9721         case REPAIR_INFO_ABORT:
9722         case REPAIR_INFO_KILLED:
9723                 // 5/4/98 -- MWA -- Need to set dock objnum to -1 to let code know this guy who was getting
9724                 // repaired (or queued for repair), isn't really going to be docked with anyone anymore.
9725                 aip->dock_objnum = -1;
9726                 aip->ai_flags &= ~AIF_DOCKED;
9727                 aip->ai_flags &= ~(AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED );
9728                 if (repair_objp != NULL) {
9729                         repair_aip = &Ai_info[Ships[repair_objp->instance].ai_index];
9730                         repair_aip->ai_flags &= ~(AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED );
9731                 }               
9732
9733                 if ( p_index >= 0 ) {
9734                         hud_support_view_abort();
9735
9736                         // send appropriate message to player here
9737                         if ( how == REPAIR_INFO_KILLED ){
9738                                 message_send_builtin_to_player( MESSAGE_SUPPORT_KILLED, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_SOON, 0, 0, p_index, -1 );
9739                         } else {
9740                                 if ( repair_objp ){
9741                                         message_send_builtin_to_player( MESSAGE_REPAIR_ABORTED, &Ships[repair_objp->instance], MESSAGE_PRIORITY_NORMAL, MESSAGE_TIME_SOON, 0, 0, p_index, -1 );
9742                                 }
9743                         }
9744                 }
9745
9746                 // add log entry if this is a player
9747                 if ( repaired_objp->flags & OF_PLAYER_SHIP ){
9748                         mission_log_add_entry(LOG_PLAYER_REARM_ABORT, Ships[repaired_objp->instance].ship_name, NULL);
9749                 }
9750
9751                 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9752                 break;
9753
9754         case REPAIR_INFO_COMPLETE:
9755                 // clear the being repaired flag -- and 
9756                 if ( p_index >= 0 ) {
9757                         SDL_assert( repair_objp );
9758                         
9759                         hud_support_view_stop();                        
9760
9761                         message_send_builtin_to_player(MESSAGE_REPAIR_DONE, &Ships[repair_objp->instance], MESSAGE_PRIORITY_LOW, MESSAGE_TIME_SOON, 0, 0, p_index, -1);
9762                 }
9763                 stamp = timestamp((int) ((30 + 10*frand()) * 1000));
9764                 break;
9765
9766         case REPAIR_INFO_ONWAY:
9767                 // need to set the dock_signature so that clients in multiplayer games rearm correctly
9768                 SDL_assert( repair_objp );
9769                 aip->dock_signature = repair_objp->signature; 
9770                 aip->dock_objnum = OBJ_INDEX(repair_objp);
9771                 stamp = timestamp(-1);
9772                 break;
9773
9774         default:
9775                 Int3();                 // bogus type of repair info
9776         }
9777
9778         if (repair_objp){
9779                 Ai_info[Ships[repair_objp->instance].ai_index].warp_out_timestamp = stamp;
9780         }
9781
9782         // repair_objp might be NULL is we are cleaning up this mode because of the support ship
9783         // getting killed.
9784         if ( repair_objp ) {
9785                 aip = &Ai_info[Ships[repair_objp->instance].ai_index];
9786                 switch ( how ) {
9787                 case REPAIR_INFO_ONWAY:
9788                         SDL_assert( repaired_objp != NULL );
9789                         aip->goal_objnum = OBJ_INDEX(repaired_objp);
9790                         aip->ai_flags |= AIF_REPAIRING;
9791                         break;
9792
9793                 case REPAIR_INFO_BROKEN:
9794                         break;
9795
9796                 case REPAIR_INFO_END:
9797                 case REPAIR_INFO_ABORT:
9798                 case REPAIR_INFO_KILLED:
9799                         if ( how == REPAIR_INFO_ABORT )
9800                                 aip->goal_objnum = -1;
9801
9802                         aip->ai_flags &= ~AIF_REPAIRING;
9803                         break;
9804                         
9805                 case REPAIR_INFO_QUEUE:
9806                         ai_add_rearm_goal( repaired_objp, repair_objp );
9807                         break;
9808
9809                 case REPAIR_INFO_BEGIN:
9810                 case REPAIR_INFO_COMPLETE:
9811                         break;
9812
9813                 default:
9814                         Int3();         // bogus type of repair info
9815                 }
9816         }
9817
9818         multi_maybe_send_repair_info( repaired_objp, repair_objp, how );
9819 }
9820
9821 //      Cleanup AI stuff for when a ship was supposed to dock with another, but the ship
9822 //      it was supposed to dock with is no longer valid.
9823 void ai_cleanup_dock_mode(ai_info *aip, ship *shipp)
9824 {
9825         object *objp;
9826
9827         objp = &Objects[shipp->objnum];
9828         aip->mode = AIM_NONE;
9829
9830         if (aip->ai_flags & AIF_REPAIRING) {
9831                 SDL_assert( aip->goal_objnum != -1 );
9832                 ai_do_objects_repairing_stuff( &Objects[aip->goal_objnum], &Objects[shipp->objnum], REPAIR_INFO_KILLED );
9833         } else if ( aip->ai_flags & AIF_BEING_REPAIRED ) {
9834                 // MWA -- note that we have to use dock_objnum here instead of goal_objnum.
9835                 SDL_assert( aip->dock_objnum != -1 );
9836                 ai_do_objects_repairing_stuff( &Objects[shipp->objnum], &Objects[aip->dock_objnum], REPAIR_INFO_KILLED );
9837         } else if ( aip->ai_flags & AIF_AWAITING_REPAIR ) {
9838                 // need to find the support ship that has me as a goal_objnum
9839                 // MWA -- note that we have to use dock_objnum here instead of goal_objnum.
9840                 // MWA -- 3/38/98  Check to see if this guy is queued for a support ship, or there is already
9841                 // one in the mission
9842                 if ( mission_is_repair_scheduled(objp) ) {
9843                         mission_remove_scheduled_repair( objp );                        // this function will notify multiplayer clients.
9844                 } else {
9845                         if ( aip->dock_objnum != -1 )
9846                                 ai_do_objects_repairing_stuff( objp, &Objects[aip->dock_objnum], REPAIR_INFO_ABORT );
9847                         else
9848                                 ai_do_objects_repairing_stuff( objp, NULL, REPAIR_INFO_ABORT );
9849                 }
9850         }
9851
9852         if ( aip->ai_flags & AIF_DOCKED ) {
9853                 ai_info *other_aip;
9854
9855                 SDL_assert( aip->dock_objnum != -1 );
9856
9857                 // if docked, and the dock_objnum is not undocking, force them to near last stage
9858                 other_aip = &Ai_info[Ships[Objects[aip->dock_objnum].instance].ai_index];
9859                 if ( (other_aip->mode == AIM_DOCK) && (other_aip->submode < AIS_UNDOCK_3) )
9860                         other_aip->submode = AIS_UNDOCK_3;
9861                 ai_do_objects_undocked_stuff( objp, &Objects[aip->dock_objnum] );
9862         }
9863 }
9864
9865 /*
9866 //      Make dockee_objp shake a bit due to docking.
9867 void ai_dock_shake(object *docker_objp, object *dockee_objp)
9868 {
9869         vector  tangles;
9870         matrix  rotmat, tmp;
9871         float           scale;
9872         angles  *ap;
9873
9874         scale = 0.25f;          //      Compute this based on mass and speed at time of docking.
9875
9876         vm_vec_rand_vec_quick(&tangles);
9877         vm_vec_scale(&tangles, scale);
9878
9879         ap = (angles *) &tangles;
9880
9881         vm_angles_2_matrix(&rotmat, ap);
9882         vm_matrix_x_matrix( &tmp, &dockee_objp->orient, &rotmat );
9883         dockee_objp->orient = tmp;
9884
9885         vm_orthogonalize_matrix(&dockee_objp->orient);
9886
9887         dock_orient_and_approach(docker_objp, dockee_objp, DOA_DOCK_STAY);
9888
9889 }
9890 */
9891
9892 //      Make Pl_objp point at aip->goal_point.
9893 void ai_still()
9894 {
9895         ship    *shipp;
9896         ai_info *aip;
9897
9898         SDL_assert(Pl_objp->type == OBJ_SHIP);
9899         SDL_assert((Pl_objp->instance >= 0) && (Pl_objp->instance < MAX_OBJECTS));
9900
9901         shipp = &Ships[Pl_objp->instance];
9902         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
9903
9904         aip = &Ai_info[shipp->ai_index];
9905
9906         turn_towards_point(Pl_objp, &aip->goal_point, NULL, 0.0f);
9907 }
9908
9909 //      Make *Pl_objp stay near another ship.
9910 void ai_stay_near()
9911 {
9912         ai_info *aip;
9913         int             goal_objnum;
9914
9915         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
9916
9917         goal_objnum = aip->goal_objnum;
9918
9919         if ((goal_objnum < 0) || (Objects[goal_objnum].type != OBJ_SHIP) || (Objects[goal_objnum].signature != aip->goal_signature)) {
9920                 aip->mode = AIM_NONE;
9921         } else {
9922                 float           dist, max_dist, scale;
9923                 vector  rand_vec, goal_pos, vec_to_goal;
9924                 object  *goal_objp;
9925
9926                 goal_objp = &Objects[goal_objnum];
9927
9928                 //      Make not all ships pursue same point.
9929                 static_randvec(Pl_objp-Objects, &rand_vec);
9930
9931                 //      Make sure point is in front hemisphere (relative to Pl_objp's position.
9932                 vm_vec_sub(&vec_to_goal, &goal_objp->pos, &Pl_objp->pos);
9933                 if (vm_vec_dot(&rand_vec, &vec_to_goal) > 1.0f) {
9934                         vm_vec_negate(&rand_vec);
9935                 }
9936
9937                 //      Scale the random vector by an amount proportional to the distance from Pl_objp to the true goal.
9938                 dist = vm_vec_dist_quick(&goal_objp->pos, &Pl_objp->pos);
9939                 max_dist = aip->stay_near_distance;
9940                 scale = dist - max_dist/2;
9941                 if (scale < 0.0f)
9942                         scale = 0.0f;
9943
9944                 vm_vec_scale_add(&goal_pos, &goal_objp->pos, &rand_vec, scale);
9945
9946                 if (max_dist < Pl_objp->radius + goal_objp->radius + 25.0f)
9947                         max_dist = Pl_objp->radius + goal_objp->radius + 25.0f;
9948
9949                 if (dist > max_dist) {
9950                         turn_towards_point(Pl_objp, &goal_pos, NULL, 0.0f);
9951                         accelerate_ship(aip, dist / max_dist - 0.8f);
9952                 }
9953         
9954         }
9955
9956 }
9957
9958 //      Warn player if dock path is obstructed.
9959 int maybe_dock_obstructed(object *cur_objp, object *goal_objp, int big_only_flag)
9960 {
9961         vector  *goalpos, *curpos;
9962         float           radius;
9963         ai_info *aip;
9964         int             collide_objnum;
9965
9966         aip = &Ai_info[Ships[cur_objp->instance].ai_index];
9967
9968         Ai_info[Ships[goal_objp->instance].ai_index].ai_flags &= ~AIF_REPAIR_OBSTRUCTED;
9969
9970         if (goal_objp != Player_obj)
9971                 return -1;
9972
9973         curpos = &cur_objp->pos;
9974         radius = cur_objp->radius;
9975         goalpos = &Path_points[aip->path_cur].pos;
9976         collide_objnum = pp_collide_any(curpos, goalpos, radius, cur_objp, goal_objp, big_only_flag);
9977
9978         if (collide_objnum != -1)
9979                 Ai_info[Ships[goal_objp->instance].ai_index].ai_flags |= AIF_REPAIR_OBSTRUCTED;
9980
9981         return collide_objnum;
9982 }
9983
9984
9985 int Dock_path_warning_given = 0;
9986
9987 //      Docking behavior.
9988 //      Approach a ship, follow path to docking platform, approach platform, after awhile,
9989 //      undock.
9990 void ai_dock()
9991 {
9992         ship                    *shipp = &Ships[Pl_objp->instance];
9993         ai_info         *aip = &Ai_info[shipp->ai_index];
9994         object          *goal_objp;
9995         ship_info       *sip = &Ship_info[shipp->ship_info_index];
9996
9997         //      Make sure object we're supposed to dock with still exists.
9998         if ((aip->goal_objnum == -1) || (Objects[aip->goal_objnum].signature != aip->goal_signature)) {
9999                 ai_cleanup_dock_mode(aip, shipp);
10000                 return;
10001         }
10002
10003         goal_objp = &Objects[aip->goal_objnum];
10004
10005         //      For docking submodes (ie, not undocking), follow path.  Once at second last
10006         //      point on path (point just before point on dock platform), orient into position.
10007         // For undocking, first mode pushes docked ship straight back from docking point
10008         // second mode turns ship and moves to point on docking radius
10009         switch (aip->submode) {
10010
10011                 //      This mode means to find the path to the docking point.
10012         case AIS_DOCK_0:
10013                 //aip->path_start = -1;
10014                 //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10015                 ai_path();
10016                 if (!Dock_path_warning_given && (aip->path_length < 4)) {
10017                         Warning( LOCATION, "Ship '%s' has only %i points on dock path.  Docking will look strange.  Contact Adam.", shipp->ship_name, aip->path_length );
10018                         Dock_path_warning_given = 1;            //      This is on a mission-wide basis, but it's just a hack for now...
10019                 }
10020
10021                 aip->submode = AIS_DOCK_1;
10022                 aip->path_start = -1;
10023                 aip->submode_start_time = Missiontime;
10024                 break;
10025
10026                 //      This mode means to follow the path until just before the end.
10027         case AIS_DOCK_1: {
10028         //      float   dist;
10029                 int     r;
10030
10031                 if ((r = maybe_dock_obstructed(Pl_objp, goal_objp, 1)) != -1) {
10032                         int     r1;
10033                         if ((r1 = maybe_avoid_big_ship(Pl_objp, goal_objp, aip, &goal_objp->pos, 7.0f)) != 0) {
10034                                 nprintf(("AI", "Support ship %s avoiding large ship %s\n", Ships[Pl_objp->instance].ship_name, Ships[Objects[r1].instance].ship_name));
10035                                 break;
10036                         } /*else {
10037                                 nprintf(("AI", "Dock 1: Obstructed by %s\n", Ships[Objects[r].instance].ship_name));
10038                                 accelerate_ship(aip, 0.0f);
10039                                 aip->submode = AIS_DOCK_0;
10040                         } */
10041                 } //else {
10042                 {
10043                         /*dist =*/ ai_path();
10044                         //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10045                         //nprintf(("AI", "Dock 1: Frame: %i, goal point = %i, dist = %7.3f\n", Framecount, aip->path_cur-aip->path_start, dist));
10046
10047                         if (aip->path_cur-aip->path_start >= aip->path_length-1) {              //      If got this far, advance no matter what.
10048                                 aip->submode = AIS_DOCK_2;
10049                                 aip->submode_start_time = Missiontime;
10050                                 aip->path_cur--;
10051                                 SDL_assert(aip->path_cur-aip->path_start >= 0);
10052                         } else if (aip->path_cur-aip->path_start >= aip->path_length-2) {
10053                                 if (Pl_objp->phys_info.speed > goal_objp->phys_info.speed + 1.5f) {
10054                                         set_accel_for_target_speed(Pl_objp, goal_objp->phys_info.speed);
10055                                 } else {
10056                                         aip->submode = AIS_DOCK_2;
10057                                         aip->submode_start_time = Missiontime;
10058                                 }
10059                         }
10060                 }
10061                 break;
10062                                           }
10063         //      This mode means to drag oneself right to the second last point on the path.
10064         //      Path code allows it to overshoot.
10065         case AIS_DOCK_2: {
10066                 float           dist;
10067                 int     r;
10068
10069                 if ((r = maybe_dock_obstructed(Pl_objp, goal_objp,0)) != -1) {
10070                         nprintf(("AI", "Dock 2: Obstructed by %s\n", Ships[Objects[r].instance].ship_name));
10071                         accelerate_ship(aip, 0.0f);
10072                         aip->submode = AIS_DOCK_1;
10073                 } else {
10074                         //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10075                         dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_APPROACH);
10076                         SDL_assert(dist != UNINITIALIZED_VALUE);
10077
10078                         if (dist == DOCK_BACKUP_RETURN_VAL) {
10079                                 int path_num;
10080                                 aip->submode = AIS_DOCK_1;
10081                                 path_num = ai_return_path_num_from_dockbay(&Objects[aip->goal_objnum], aip->dockee_index);
10082                                 SDL_assert(aip->goal_objnum >= 0 && aip->goal_objnum < MAX_OBJECTS);
10083                                 ai_find_path(Pl_objp, aip->goal_objnum, path_num, 0);
10084                                 break;
10085                         }
10086
10087                         //nprintf(("AI", "Dock 2: dist = %7.3f\n", vm_vec_dist_quick(&Pl_objp->pos, &goal_point)));
10088                         float   tolerance;
10089                         if (Objects[aip->goal_objnum].flags & OF_PLAYER_SHIP)
10090                                 tolerance = 6*flFrametime + 1.0f;
10091                         else
10092                                 tolerance = 4*flFrametime + 0.5f;
10093
10094                         if ( dist < tolerance) {
10095                                 aip->submode = AIS_DOCK_3;
10096                                 aip->submode_start_time = Missiontime;
10097                                 aip->path_cur++;
10098                         }
10099                 }
10100                 break;
10101                                                   }
10102
10103         case AIS_DOCK_3:
10104         case AIS_DOCK_3A:
10105                 {
10106                 SDL_assert(aip->goal_objnum != -1);
10107                 int     r;
10108
10109                 if ((r = maybe_dock_obstructed(Pl_objp, goal_objp,0)) != -1) {
10110                         nprintf(("AI", "Dock 1: Obstructed by %s\n", Ships[Objects[r].instance].ship_name));
10111                         accelerate_ship(aip, 0.0f);
10112                         aip->submode = AIS_DOCK_2;
10113                 } else {
10114
10115                         //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10116                         float dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_DOCK);
10117                         SDL_assert(dist != UNINITIALIZED_VALUE);
10118
10119                         if (dist == DOCK_BACKUP_RETURN_VAL) {
10120                                 aip->submode = AIS_DOCK_2;
10121                                 break;
10122                         }
10123
10124                         //nprintf(("AI", "Dock 3: dist = %7.3f\n", dist));
10125
10126                         if (dist < 2*flFrametime * (1.0f + fl_sqrt(goal_objp->phys_info.speed))) {
10127                                 // - Removed by MK on 11/7/97, causes errors for ships docked at mission start: maybe_recreate_path(Pl_objp, aip, 1);
10128                                 dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_DOCK);
10129                                 SDL_assert(dist != UNINITIALIZED_VALUE);
10130
10131                                 physics_ship_init(Pl_objp);
10132
10133                                 ai_do_objects_docked_stuff( Pl_objp, goal_objp );
10134
10135                                 if (aip->submode == AIS_DOCK_3) {
10136                                         snd_play_3d( &Snds[SND_DOCK_ATTACH], &Pl_objp->pos, &View_position );
10137                                         hud_maybe_flash_docking_text(Pl_objp);
10138                                         // ai_dock_shake(Pl_objp, goal_objp);
10139
10140                                         if ((Pl_objp == Player_obj) || (goal_objp == Player_obj))
10141                                                 joy_ff_docked();  // shake player's joystick a little
10142                                 }
10143
10144                                 //      If this ship is repairing another ship...
10145                                 if (aip->ai_flags & AIF_REPAIRING) {
10146                                         aip->submode = AIS_DOCK_4;                      //      Special rearming only dock mode.
10147                                         aip->submode_start_time = Missiontime;
10148                                 } else {
10149                                         aip->submode = AIS_DOCK_4A;
10150                                         aip->submode_start_time = Missiontime;
10151                                 }
10152                         }
10153                 }
10154                 break;
10155                 }
10156
10157                 //      Yes, we just sit here.  We wait for further orders.  No, it's not a bug.
10158         case AIS_DOCK_4A:
10159                 //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10160                 //nprintf(("AI", "."));
10161                 if (aip->active_goal >= 0) {
10162                         mission_log_add_entry(LOG_SHIP_DOCK, Ships[Pl_objp->instance].ship_name, Ships[goal_objp->instance].ship_name);
10163
10164                         if (aip->goals[aip->active_goal].ai_mode == AI_GOAL_DOCK) {
10165                                 ai_mission_goal_complete( aip );                                        // Note, this calls ai_set_default_behavior().
10166                         } 
10167                 } else {        //      Can happen for initially docked ships.
10168                         ai_do_default_behavior( &Objects[Ships[aip->shipnum].objnum] );         // do the default behavior
10169                 }
10170                 
10171                 break;
10172
10173         case AIS_DOCK_4: {
10174                 //      This mode is only for rearming/repairing.
10175                 //      The ship that is performing the rearm enters this mode after it docks.
10176                 SDL_assert((aip->goal_objnum >= -1) && (aip->goal_objnum < MAX_OBJECTS));
10177
10178                 //nprintf(("AI", "Time = %7.3f, submode = %i\n", f2fl(Missiontime), aip->submode));
10179                 float dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_DOCK);
10180                 SDL_assert(dist != UNINITIALIZED_VALUE);
10181
10182                 object  *goal_objp = &Objects[aip->goal_objnum];
10183                 SDL_assert(goal_objp->type == OBJ_SHIP);
10184                 ship                    *goal_shipp = &Ships[goal_objp->instance];              
10185                 ai_info         *goal_aip = &Ai_info[goal_shipp->ai_index];
10186
10187                 //nprintf(("AI", "Dock 4: dist = %7.3f\n", dist));
10188
10189                 //      Make sure repair has not broken off.
10190                 if (dist > 5.0f) {      //      Oops, too far away!
10191                         if ( goal_aip->ai_flags & AIF_BEING_REPAIRED )
10192                                 ai_do_objects_repairing_stuff( goal_objp, Pl_objp, REPAIR_INFO_BROKEN);
10193
10194                         if (dist > Pl_objp->radius*2 + goal_objp->radius*2) {
10195                                 //      Got real far away from goal, so move back a couple modes and try again.
10196                                 aip->submode = AIS_DOCK_2;
10197                                 aip->submode_start_time = Missiontime;
10198                         }
10199                 } else {
10200                         if ( goal_aip->ai_flags & AIF_AWAITING_REPAIR )
10201                                 ai_do_objects_repairing_stuff( goal_objp, Pl_objp, REPAIR_INFO_BEGIN );
10202                 }
10203
10204                 break;
10205                                                   }
10206
10207         case AIS_UNDOCK_0: {
10208                 int path_num;
10209                 //      First stage of undocking.
10210
10211                 //nprintf(("AI", "Undock 0:\n"));
10212
10213                 aip->submode = AIS_UNDOCK_1;
10214                 aip->submode_start_time = Missiontime;
10215                 if (aip->dock_objnum == -1) {
10216                         aip->submode = AIS_UNDOCK_3;
10217                 } else {
10218
10219                         // set up the path points for the undocking procedure.  dock_path_index member should
10220                         // have gotten set in the docking code.
10221                         SDL_assert( aip->dock_path_index != -1 );
10222                         path_num = ai_return_path_num_from_dockbay(goal_objp, aip->dock_path_index);
10223                         ai_find_path(Pl_objp, goal_objp-Objects, path_num, 0);
10224
10225                         // Play a ship docking detach sound
10226                         snd_play_3d( &Snds[SND_DOCK_DETACH], &Pl_objp->pos, &View_position );
10227                 }
10228                 break;
10229                                                          }
10230         case AIS_UNDOCK_1: {
10231                 //      Using thrusters, exit from dock station to nearest next dock path point.
10232                 float   dist;
10233                 
10234                 //nprintf(("AI", "Undock 1: time in this mode = %7.3f\n", f2fl(Missiontime - aip->submode_start_time)));
10235
10236                 if (Missiontime - aip->submode_start_time < REARM_BREAKOFF_DELAY) {
10237                         break;          //      Waiting for one second to elapse to let detach sound effect play out.
10238                 }
10239                 else {  // AL - added 05/16/97.  Hack to play depart sound.  Will probably take out.
10240                                         // Assumes that the submode_start_time is not used for AIS_UNDOCK_1 anymore
10241                         if ( aip->submode_start_time != 0 )
10242                                 snd_play_3d( &Snds[SND_DOCK_DEPART], &Pl_objp->pos, &View_position );
10243                         aip->submode_start_time = 0;
10244                 }
10245
10246                 dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_UNDOCK_1);
10247                 SDL_assert(dist != UNINITIALIZED_VALUE);
10248
10249                 float dist_to_dock_obj = vm_vec_dist_quick(&Pl_objp->pos, &Objects[aip->goal_objnum].pos);
10250
10251                 //      Move to within 0.1 units of second last point on path before orienting, or just plain far away from docked-to ship.
10252                 //      This allows undock to complete if first ship flies away.
10253                 if ((dist < 2*flFrametime) || (dist_to_dock_obj > 2*Pl_objp->radius)) {
10254                         aip->submode = AIS_UNDOCK_2;
10255                         aip->submode_start_time = Missiontime;
10256                 }
10257                 break;
10258                                                          }
10259         case AIS_UNDOCK_2: {
10260                 float dist;
10261                 //ai_info *other_aip;
10262
10263                 // get pointer to docked object's aip to reset flags, etc
10264                 SDL_assert( aip->dock_objnum != -1 );
10265                 //other_aip = &Ai_info[Ships[Objects[aip->dock_objnum].instance].ai_index];
10266
10267                 //      Second stage of undocking.
10268                 dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_UNDOCK_2);
10269                 SDL_assert(dist != UNINITIALIZED_VALUE);
10270
10271
10272                 //nprintf(("AI", "Undock 2: dist = %7.3f\n", dist));
10273                 
10274                 //      If at goal point, or quite far away from dock object
10275                 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) ) {
10276                         // reset the dock flags.  If rearm/repair, reset rearm repair flags for those ships as well.
10277                         if ( sip->flags & SIF_SUPPORT ) {
10278                                 ai_do_objects_repairing_stuff( &Objects[aip->dock_objnum], Pl_objp, REPAIR_INFO_END );
10279                         }
10280
10281                         // clear out flags for AIF_DOCKED for both objects.
10282                         ai_do_objects_undocked_stuff( Pl_objp, goal_objp );
10283                         physics_ship_init(Pl_objp);
10284                         aip->submode = AIS_UNDOCK_3;                            //      The do-nothing mode, until another order is issued
10285
10286                         //aip->ai_flags &= ~AIF_DOCKED;         //      @MK, 9/18/97
10287                         //other_aip->ai_flags &= ~AIF_DOCKED;
10288                         //aip->dock_objnum = -1;                                        // invalidate who obj is docked with
10289                         //other_aip->dock_objnum = -1;                  // MWA 10/07/97 invalide docked objects dock_objnum value as well
10290
10291                         // don't add undock log entries for support ships.
10292                         if ( !(sip->flags & SIF_SUPPORT) )
10293                                 mission_log_add_entry(LOG_SHIP_UNDOCK, Ships[Pl_objp->instance].ship_name, Ships[goal_objp->instance].ship_name);
10294
10295                 }
10296                 break;
10297                 }
10298         case AIS_UNDOCK_3: {
10299                 float dist = dock_orient_and_approach(Pl_objp, &Objects[aip->goal_objnum], DOA_UNDOCK_3);
10300                 SDL_assert(dist != UNINITIALIZED_VALUE);
10301
10302                 if (dist < Pl_objp->radius/2 + 5.0f) {
10303                         aip->submode = AIS_UNDOCK_4;
10304                 }
10305
10306                 // possible that this flag hasn't been cleared yet.  When aborting a rearm, this submode might
10307                 // be entered directly.
10308                 if ( (sip->flags & SIF_SUPPORT) && (aip->ai_flags & AIF_REPAIRING) ) {
10309                         ai_do_objects_repairing_stuff( &Objects[aip->goal_objnum], Pl_objp, REPAIR_INFO_ABORT );
10310                 }
10311
10312                 break;
10313                                                  }
10314         case AIS_UNDOCK_4: {
10315                 //ai_info *other_aip;
10316
10317                 // MWA 10/07/97  I'm slightly confused by the dual use of goal_objnum and dock_objnum.  Seems to me
10318                 // that goal_objnum and dock_objnum are the same through this whole docking/undocking process, although
10319                 // I could be wrong.  dock_objnum was reset in undock_2 submode so try to use goal_objnum here to
10320                 // get other ships ai_info pointer
10321                 //SDL_assert( aip->goal_objnum != -1 );
10322                 //other_aip = &Ai_info[Ships[Objects[aip->goal_objnum].instance].ai_index];
10323
10324                 aip->mode = AIM_NONE;
10325                 aip->dock_path_index = -1;              // invalidate the docking path index
10326
10327                 // these flags should have been cleared long ago!
10328                 // Get Allender if you hit one of these!!!!!
10329                 // removed by allender on 2/16 since a ship may be docked with some other ship, but still be the
10330                 // goal_objnum of this ship ending it's undocking mode.
10331                 //SDL_assert( !(aip->ai_flags & AIF_DOCKED) );
10332                 //SDL_assert( !(other_aip->ai_flags & AIF_DOCKED) );
10333                 //SDL_assert( !(aip->ai_flags & AIF_REPAIRING) );
10334                 //SDL_assert( !(other_aip->ai_flags & AIF_BEING_REPAIRED) );
10335                 //SDL_assert( !(other_aip->ai_flags & AIF_AWAITING_REPAIR) );
10336
10337                 // only call mission goal complete if this was indeed an undock goal
10338                 if ( aip->active_goal > -1 ) {
10339                         if ( aip->goals[aip->active_goal].ai_mode == AI_GOAL_UNDOCK )
10340                                 ai_mission_goal_complete( aip );                        // this call should reset the AI mode
10341                         //else
10342                         //      aip->active_goal = -1;                                          // this ensures that this ship might get new goal
10343                 }
10344
10345                 break;
10346                                                          }
10347         default:
10348                 Int3(); //      Error, bogus submode
10349         }
10350
10351 }
10352
10353 // TURRET BEGIN
10354
10355 //      Given an object and a turret on that object, return the global position and forward vector
10356 //      of the turret.   The gun normal is the unrotated gun normal, (the center of the FOV cone), not
10357 // the actual gun normal given using the current turret heading.  But it _is_ rotated into the model's orientation
10358 //      in global space.
10359 void ship_get_global_turret_info(object *objp, model_subsystem *tp, vector *gpos, vector *gvec)
10360 {
10361         matrix  m;
10362         vm_copy_transpose_matrix(&m, &objp->orient);
10363 //      vm_vec_rotate(gpos, &tp->turret_avg_firing_point, &m);
10364         vm_vec_rotate(gpos, &tp->pnt, &m);
10365         vm_vec_add2(gpos, &objp->pos);
10366         vm_vec_rotate(gvec, &tp->turret_norm, &m);      
10367 }
10368
10369 // Given an object and a turret on that object, return the actual firing point of the gun
10370 // and its normal.   This uses the current turret angles.  We are keeping track of which
10371 // gun to fire next in the ship specific info for this turret subobject.  Use this info
10372 // to determine which position to fire from next.
10373 //      Stuffs:
10374 //              *gpos: absolute position of gun firing point
10375 //              *gvec: vector fro *gpos to *targetp
10376 void ship_get_global_turret_gun_info(object *objp, ship_subsys *ssp, vector *gpos, vector *gvec, int use_angles, vector *targetp)
10377 {
10378         vector * gun_pos;
10379         model_subsystem *tp = ssp->system_info;
10380
10381         ship_model_start(objp);
10382
10383         gun_pos = &tp->turret_firing_point[ssp->turret_next_fire_pos % tp->turret_num_firing_points];
10384
10385         model_find_world_point(gpos, gun_pos, tp->model_num, tp->turret_gun_sobj, &objp->orient, &objp->pos );
10386
10387         if (use_angles)
10388                 model_find_world_dir(gvec, &tp->turret_norm, tp->model_num, tp->turret_gun_sobj, &objp->orient, &objp->pos );
10389         else {
10390                 //vector        gun_pos2;
10391                 //vm_vec_add(&gun_pos2, gpos, gun_pos);
10392                 vm_vec_normalized_dir(gvec, targetp, gpos);
10393         }
10394
10395         ship_model_stop(objp);  
10396 }
10397
10398 //      Rotate a turret towards an enemy.
10399 //      Return TRUE if caller should use angles in subsequent rotations.
10400 //      Some obscure model thing only John Slagel knows about.
10401 //      Sets predicted enemy position.
10402 //      If the turret (*ss) has a subsystem targeted, the subsystem is used as the predicted point.
10403 int aifft_rotate_turret(ship *shipp, int parent_objnum, ship_subsys *ss, object *objp, object *lep, vector *predicted_enemy_pos, vector *gvec)
10404 {
10405         if (ss->turret_enemy_objnum != -1)      {
10406                 model_subsystem *tp = ss->system_info;
10407                 vector  gun_pos, gun_vec;
10408                 float           weapon_speed;
10409                 float           weapon_system_strength;
10410
10411                 //      weapon_system_strength scales time enemy in range in 0..1.  So, the lower this is, the worse the aiming will be.
10412                 weapon_system_strength = ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS);
10413
10414                 ship_get_global_turret_info(&Objects[parent_objnum], tp, &gun_pos, &gun_vec);
10415
10416                 weapon_speed = Weapon_info[tp->turret_weapon_type].max_speed;
10417                 float weapon_travel_dist = weapon_speed * Weapon_info[tp->turret_weapon_type].lifetime;
10418
10419                 vector  enemy_point;
10420                 if (ss->targeted_subsys != NULL) {
10421                         if (ss->turret_enemy_objnum != -1) {
10422                                 vm_vec_unrotate(&enemy_point, &ss->targeted_subsys->system_info->pnt, &Objects[ss->turret_enemy_objnum].orient);
10423                                 vm_vec_add2(&enemy_point, &Objects[ss->turret_enemy_objnum].pos);
10424                         }
10425                 } else {
10426                         if ((lep->type == OBJ_SHIP) && (Ship_info[Ships[lep->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
10427                                 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));
10428                         } else {
10429                                 enemy_point = lep->pos;
10430                         }
10431                 }
10432
10433                 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);
10434
10435                 if (weapon_system_strength < 0.7f) {
10436                         vector  rand_vec;
10437
10438                         static_randvec(Missiontime >> 18, &rand_vec);   //      Return same random number for two seconds.
10439                         //      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.
10440                         vm_vec_scale_add2(predicted_enemy_pos, &rand_vec, (1.0f - weapon_system_strength)*1.5f * lep->radius);
10441                 }
10442
10443                 vector  v2e;
10444                 vm_vec_normalized_dir(&v2e, predicted_enemy_pos, &gun_pos);
10445                 if (vm_vec_dot(&v2e, gvec) > tp->turret_fov) {
10446                         model_rotate_gun(shipp->modelnum, ss->system_info, &Objects[parent_objnum].orient,
10447                                 &ss->submodel_info_1.angs, &ss->submodel_info_2.angs,
10448                                 &Objects[parent_objnum].pos, predicted_enemy_pos);
10449                 }
10450         }
10451
10452         return 0;
10453 }
10454
10455 //      Determine if subsystem *enemy_subsysp is hittable from objp.
10456 //      If so, return dot product of vector from point abs_gunposp to *enemy_subsysp
10457 float   aifft_compute_turret_dot(object *objp, object *enemy_objp, vector *abs_gunposp, ship_subsys *turret_subsysp, ship_subsys *enemy_subsysp)
10458 {
10459         float   dot_out;
10460         vector  subobj_pos, vector_out;
10461
10462         vm_vec_unrotate(&subobj_pos, &enemy_subsysp->system_info->pnt, &enemy_objp->orient);
10463         vm_vec_add2(&subobj_pos, &enemy_objp->pos);
10464
10465         if (ship_subsystem_in_sight(enemy_objp, enemy_subsysp, abs_gunposp, &subobj_pos, 1, &dot_out, &vector_out)) {
10466                 vector  turret_norm;
10467
10468                 vm_vec_rotate(&turret_norm, &turret_subsysp->system_info->turret_norm, &objp->orient);
10469                 return vm_vec_dot(&turret_norm, &vector_out);
10470         } else
10471                 return -1.0f;
10472
10473 }
10474
10475 #define MAX_AIFFT_TURRETS                       60
10476 ship_subsys *aifft_list[MAX_AIFFT_TURRETS];
10477 float aifft_rank[MAX_AIFFT_TURRETS];
10478 int aifft_list_size = 0;
10479 int aifft_max_checks = 5;
10480 DCF(mf, "")
10481 {
10482         dc_get_arg(ARG_INT);
10483         aifft_max_checks = Dc_arg_int;
10484 }
10485
10486
10487 //      Pick a subsystem to attack on enemy_objp.
10488 //      Only pick one if enemy_objp is a big ship or a capital ship.
10489 //      Returns dot product from turret to subsystem in *dot_out
10490 ship_subsys *aifft_find_turret_subsys(object *objp, ship_subsys *ssp, object *enemy_objp, float *dot_out)
10491 {
10492         ship    *eshipp;
10493         ship_info       *esip;
10494         ship_subsys     *best_subsysp = NULL;
10495         float dot;
10496
10497         SDL_assert(enemy_objp->type == OBJ_SHIP);
10498
10499         eshipp = &Ships[enemy_objp->instance];
10500         esip = &Ship_info[eshipp->ship_info_index];
10501
10502         float   best_dot = 0.0f;
10503         *dot_out = best_dot;
10504
10505         //      Compute absolute gun position.
10506         vector  abs_gun_pos;
10507         vm_vec_unrotate(&abs_gun_pos, &ssp->system_info->pnt, &objp->orient);
10508         vm_vec_add2(&abs_gun_pos, &objp->pos);
10509
10510         //      Only pick a turret to attack on large ships.
10511         if (!(esip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)))
10512                 return best_subsysp;
10513
10514         // Make sure big or huge ship *actually* has subsystems  (ie, knossos)
10515         if (esip->n_subsystems == 0) {
10516                 return best_subsysp;
10517         }
10518
10519         // first build up a list subsystems to traverse
10520         ship_subsys     *pss;
10521         aifft_list_size = 0;
10522         for ( pss = GET_FIRST(&eshipp->subsys_list); pss !=END_OF_LIST(&eshipp->subsys_list); pss = GET_NEXT(pss) ) {
10523                 model_subsystem *psub = pss->system_info;
10524
10525                 // if we've reached max turrets bail
10526                 if(aifft_list_size >= MAX_AIFFT_TURRETS){
10527                         break;
10528                 }
10529
10530                 // Don't process destroyed objects
10531                 if ( pss->current_hits <= 0.0f ){
10532                         continue;
10533                 }
10534                 
10535                 switch (psub->type) {
10536                 case SUBSYSTEM_WEAPONS:
10537                         aifft_list[aifft_list_size] = pss;
10538                         aifft_rank[aifft_list_size++] = 1.4f;
10539                         break;
10540
10541                 case SUBSYSTEM_TURRET:
10542                         aifft_list[aifft_list_size] = pss;
10543                         aifft_rank[aifft_list_size++] = 1.2f;
10544                         break;
10545
10546                 case SUBSYSTEM_SENSORS:
10547                 case SUBSYSTEM_ENGINE:
10548                         aifft_list[aifft_list_size] = pss;
10549                         aifft_rank[aifft_list_size++] = 1.0f;
10550                         break;
10551                 }
10552         }
10553
10554         // DKA:  6/28/99 all subsystems can be destroyed.
10555         //SDL_assert(aifft_list_size > 0);
10556         if (aifft_list_size == 0) {
10557                 return best_subsysp;
10558         }
10559
10560         // determine a stride value so we're not checking too many turrets
10561         int stride = aifft_list_size > aifft_max_checks ? aifft_list_size / aifft_max_checks : 1;
10562         if(stride <= 0){
10563                 stride = 1;
10564         }
10565         int offset = (int)frand_range(0.0f, (float)(aifft_list_size % stride));
10566         int idx;
10567         for(idx=offset; idx<aifft_list_size; idx+=stride){
10568                 dot = aifft_compute_turret_dot(objp, enemy_objp, &abs_gun_pos, ssp, aifft_list[idx]);                   
10569
10570                 if (dot* aifft_rank[idx] > best_dot) {
10571                         best_dot = dot*aifft_rank[idx];
10572                         best_subsysp = aifft_list[idx];
10573                 }
10574         }
10575
10576         SDL_assert(best_subsysp != &eshipp->subsys_list);
10577
10578         *dot_out = best_dot;
10579         return best_subsysp;
10580 }
10581
10582 // Set active weapon for turret
10583 void ai_turret_select_default_weapon(ship_subsys *turret)
10584 {
10585         ship_weapon *twp;
10586
10587         twp = &turret->weapons;
10588
10589         // If a primary weapon is available, select it
10590         if ( twp->num_primary_banks > 0 ) {
10591                 turret->system_info->turret_weapon_type = twp->primary_bank_weapons[0];
10592         } else if ( twp->num_secondary_banks > 0 ) {
10593                 turret->system_info->turret_weapon_type = twp->secondary_bank_weapons[0];
10594         }
10595 }
10596
10597 // return !0 if the specified target should scan for a new target, otherwise return 0
10598 int turret_should_pick_new_target(ship_subsys *turret)
10599 {
10600 //      int target_type;
10601
10602         if ( timestamp_elapsed(turret->turret_next_enemy_check_stamp) ) {
10603                 return 1;
10604         }
10605
10606         return 0;
10607
10608 /*
10609         if ( turret->turret_enemy_objnum == -1 ) {
10610                 return 1;
10611         }
10612                 
10613         target_type = Objects[turret->turret_enemy_objnum].type;
10614         if ( (target_type != OBJ_SHIP) && (target_type != OBJ_ASTEROID) ) {
10615                 return 1;
10616         }
10617
10618         return 0;
10619 */
10620 }
10621
10622 // Set the next fire timestamp for a turret, based on weapon type and ai class
10623 void turret_set_next_fire_timestamp(ship_subsys *turret, ai_info *aip)
10624 {
10625         float   wait;
10626         int     weapon_id;
10627
10628         weapon_id = turret->system_info->turret_weapon_type;
10629
10630         wait = Weapon_info[weapon_id].fire_wait * 1000.0f;
10631
10632         // make side even for team vs. team
10633         if ((Game_mode & GM_MULTIPLAYER) && (Netgame.type_flags & NG_TYPE_TEAM)) {
10634                 // flak guns need to fire more rapidly
10635                 if (Weapon_info[weapon_id].wi_flags & WIF_FLAK) {
10636                         wait *= Ship_fire_delay_scale_friendly[Game_skill_level] * 0.5f;
10637                         wait += (Num_ai_classes - aip->ai_class - 1) * 40.0f;
10638                 } else {
10639                         wait *= Ship_fire_delay_scale_friendly[Game_skill_level];
10640                         wait += (Num_ai_classes - aip->ai_class - 1) * 100.0f;
10641                 }
10642         } else {
10643                 // flak guns need to fire more rapidly
10644                 if (Weapon_info[weapon_id].wi_flags & WIF_FLAK) {
10645                         if (Ships[aip->shipnum].team == TEAM_FRIENDLY) {
10646                                 wait *= Ship_fire_delay_scale_friendly[Game_skill_level] * 0.5f;
10647                         } else {
10648                                 wait *= Ship_fire_delay_scale_hostile[Game_skill_level] * 0.5f;
10649                         }       
10650                         wait += (Num_ai_classes - aip->ai_class - 1) * 40.0f;
10651
10652                 } else if (Weapon_info[weapon_id].wi_flags & WIF_HUGE) {
10653                         // make huge weapons fire independently of team
10654                         wait *= Ship_fire_delay_scale_friendly[Game_skill_level];
10655                         wait += (Num_ai_classes - aip->ai_class - 1) * 100.0f;
10656                 } else {
10657                         // give team friendly an advantage
10658                         if (Ships[aip->shipnum].team == TEAM_FRIENDLY) {
10659                                 wait *= Ship_fire_delay_scale_friendly[Game_skill_level];
10660                         } else {
10661                                 wait *= Ship_fire_delay_scale_hostile[Game_skill_level];
10662                         }       
10663                         wait += (Num_ai_classes - aip->ai_class - 1) * 100.0f;
10664                 }
10665         }
10666
10667         // vary wait time +/- 10%
10668         wait *= frand_range(0.9f, 1.1f);
10669         turret->turret_next_fire_stamp = timestamp((int) wait);
10670 }
10671
10672 // Decide  if a turret should launch an aspect seeking missile
10673 int turret_should_fire_aspect(ship_subsys *turret, float dot, int weapon_class)
10674 {
10675         weapon_info *wip;
10676
10677         wip = &Weapon_info[weapon_class];
10678
10679         if ( (dot > AICODE_TURRET_DUMBFIRE_ANGLE) && (turret->turret_time_enemy_in_range >= min(wip->min_lock_time,AICODE_TURRET_MAX_TIME_IN_RANGE)) ) {
10680                 return 1;
10681         }
10682
10683         return 0;
10684 }
10685
10686 // Update how long current target has been in this turrets range
10687 void turret_update_enemy_in_range(ship_subsys *turret, float seconds)
10688 {
10689         turret->turret_time_enemy_in_range += seconds;
10690
10691         if ( turret->turret_time_enemy_in_range < 0.0f ) {
10692                 turret->turret_time_enemy_in_range = 0.0f;
10693         }
10694
10695         if ( turret->turret_time_enemy_in_range > AICODE_TURRET_MAX_TIME_IN_RANGE ) {
10696                 turret->turret_time_enemy_in_range = AICODE_TURRET_MAX_TIME_IN_RANGE;
10697         }
10698 }
10699
10700
10701
10702 // Fire a weapon from a turret
10703 void turret_fire_weapon(ship_subsys *turret, int parent_objnum, vector *turret_pos, vector *turret_fvec, vector *predicted_pos = NULL)
10704 {
10705         matrix  turret_orient;
10706         int             turret_weapon_class, weapon_objnum;
10707         ai_info *parent_aip;
10708         ship            *parent_ship;
10709         beam_fire_info fire_info;
10710         float flak_range = 0.0f;
10711
10712         parent_aip = &Ai_info[Ships[Objects[parent_objnum].instance].ai_index];
10713         parent_ship = &Ships[Objects[parent_objnum].instance];
10714         turret_weapon_class = turret->system_info->turret_weapon_type;
10715
10716         if (check_ok_to_fire(parent_objnum, turret->turret_enemy_objnum, &Weapon_info[turret_weapon_class])) {
10717                 vm_vector_2_matrix(&turret_orient, turret_fvec, NULL, NULL);
10718                 turret->turret_last_fire_direction = *turret_fvec;
10719
10720                 // set next fire timestamp for the turret
10721                 turret_set_next_fire_timestamp(turret, parent_aip);
10722
10723                 // if this weapon is a beam weapon, handle it specially
10724                 if(Weapon_info[turret_weapon_class].wi_flags & WIF_BEAM){
10725                         // if this beam isn't free to fire
10726                         if (!(turret->weapons.flags & SW_FLAG_BEAM_FREE)) {
10727                                 Int3(); // should never get this far
10728                                 return;
10729                         }
10730
10731                         // stuff beam firing info
10732                         memset(&fire_info, 0, sizeof(beam_fire_info));
10733                         fire_info.accuracy = 1.0f;
10734                         fire_info.beam_info_index = turret_weapon_class;
10735                         fire_info.beam_info_override = NULL;
10736                         fire_info.shooter = &Objects[parent_objnum];
10737                         fire_info.target = &Objects[turret->turret_enemy_objnum];
10738                         fire_info.target_subsys = NULL;
10739                         fire_info.turret = turret;
10740
10741                         // fire a beam weapon
10742                         beam_fire(&fire_info);
10743                 } else {
10744
10745                         // don't fire swarm, but set up swarm info
10746                         if (Weapon_info[turret_weapon_class].wi_flags & WIF_SWARM) {
10747                                 turret_swarm_set_up_info(parent_objnum, turret, turret_weapon_class);
10748                                 return;
10749                         } else {
10750                                 weapon_objnum = weapon_create( turret_pos, &turret_orient, turret_weapon_class, parent_objnum, 0, -1, 1);
10751                                 weapon_set_tracking_info(weapon_objnum, parent_objnum, turret->turret_enemy_objnum, 1, turret->targeted_subsys);                
10752                         }
10753
10754                         //nprintf(("AI", "Turret_time_enemy_in_range = %7.3f\n", ss->turret_time_enemy_in_range));              
10755                         if (weapon_objnum != -1) {
10756                                 Weapons[Objects[weapon_objnum].instance].target_num = turret->turret_enemy_objnum;
10757                                 // AL 1-6-97: Store pointer to turret subsystem
10758                                 Weapons[Objects[weapon_objnum].instance].turret_subsys = turret;
10759
10760                                 if ( Weapon_info[turret_weapon_class].launch_snd != -1 ) {
10761                                         // Don't play turret firing sound if turret sits on player ship... it gets annoying.
10762                                         if ( parent_objnum != OBJ_INDEX(Player_obj) ) {                                         
10763                                                 snd_play_3d( &Snds[Weapon_info[turret_weapon_class].launch_snd], turret_pos, &View_position );                                          
10764                                         }
10765                                 }               
10766
10767                                 // if the gun is a flak gun
10768                                 if(Weapon_info[turret_weapon_class].wi_flags & WIF_FLAK){                       
10769                                         // show a muzzle flash
10770                                         flak_muzzle_flash(turret_pos, turret_fvec, turret_weapon_class);
10771
10772                                         // pick a firing range so that it detonates properly                    
10773                                         flak_pick_range(&Objects[weapon_objnum], predicted_pos, ship_get_subsystem_strength(parent_ship, SUBSYSTEM_WEAPONS));
10774
10775                                         // determine what that range was
10776                                         flak_range = flak_get_range(&Objects[weapon_objnum]);
10777                                 }
10778
10779                                 // in multiplayer (and the master), then send a turret fired packet.
10780                                 if ( MULTIPLAYER_MASTER && (weapon_objnum != -1) ) {
10781                                         int subsys_index;
10782
10783                                         subsys_index = ship_get_index_from_subsys(turret, parent_objnum );
10784                                         SDL_assert( subsys_index != -1 );
10785                                         if(Weapon_info[turret_weapon_class].wi_flags & WIF_FLAK){                       
10786                                                 send_flak_fired_packet( parent_objnum, subsys_index, weapon_objnum, flak_range );
10787                                         } else {
10788                                                 send_turret_fired_packet( parent_objnum, subsys_index, weapon_objnum );
10789                                         }
10790                                 }
10791                         }
10792                 }
10793         } else {
10794                 float wait = 1000.0f * frand_range(0.9f, 1.1f);
10795                 turret->turret_next_fire_stamp = timestamp((int) wait);
10796         }
10797 }
10798
10799 void turret_swarm_fire_from_turret(ship_subsys *turret, int parent_objnum, int target_objnum, ship_subsys *target_subsys)
10800 {
10801         int turret_weapon_class, weapon_objnum;
10802         matrix turret_orient;
10803         vector turret_pos, turret_fvec;
10804
10805         // parent not alive, quick out.
10806         if (Objects[parent_objnum].type != OBJ_SHIP) {
10807                 return;
10808         }
10809
10810         //      change firing point
10811         ship_get_global_turret_gun_info(&Objects[parent_objnum], turret, &turret_pos, &turret_fvec, 1, NULL);
10812         turret->turret_next_fire_pos++;
10813
10814         // get class [index into Weapon_info array
10815         turret_weapon_class = turret->system_info->turret_weapon_type;
10816         SDL_assert(Weapon_info[turret_weapon_class].wi_flags & WIF_SWARM);
10817
10818         // make turret_orient from turret_fvec -- turret->turret_last_fire_direction
10819         vm_vector_2_matrix(&turret_orient, &turret_fvec, NULL, NULL);
10820
10821         // create weapon and homing info
10822         weapon_objnum = weapon_create(&turret_pos, &turret_orient, turret_weapon_class, parent_objnum, 0, -1, 1);
10823         weapon_set_tracking_info(weapon_objnum, parent_objnum, target_objnum, 1, target_subsys);
10824
10825         // do other cool stuff if weapon is created.
10826         if (weapon_objnum > -1) {
10827                 Weapons[Objects[weapon_objnum].instance].turret_subsys = turret;
10828                 Weapons[Objects[weapon_objnum].instance].target_num = turret->turret_enemy_objnum;
10829
10830                 // maybe sound
10831                 if ( Weapon_info[turret_weapon_class].launch_snd != -1 ) {
10832                         // Don't play turret firing sound if turret sits on player ship... it gets annoying.
10833                         if ( parent_objnum != OBJ_INDEX(Player_obj) ) {
10834                                 snd_play_3d( &Snds[Weapon_info[turret_weapon_class].launch_snd], &turret_pos, &View_position );
10835                         }
10836                 }
10837                 
10838                 // in multiplayer (and the master), then send a turret fired packet.
10839                 if ( MULTIPLAYER_MASTER && (weapon_objnum != -1) ) {
10840                         int subsys_index;
10841
10842                         subsys_index = ship_get_index_from_subsys(turret, parent_objnum );
10843                         SDL_assert( subsys_index != -1 );
10844                         send_turret_fired_packet( parent_objnum, subsys_index, weapon_objnum );
10845                 }
10846         }
10847 }
10848
10849 int Num_ai_firing = 0;
10850 int Num_find_turret_enemy = 0;
10851 int Num_turrets_fired = 0;
10852 //      Given a turret tp and its parent parent_objnum, fire from the turret at its enemy.
10853 void ai_fire_from_turret(ship *shipp, ship_subsys *ss, int parent_objnum)
10854 {
10855         float           weapon_firing_range;
10856         vector  v2e;
10857         object  *lep;           //      Last enemy pointer
10858         model_subsystem *tp = ss->system_info;
10859         int             use_angles, turret_weapon_class;
10860         vector  predicted_enemy_pos;
10861         object  *objp;
10862         ai_info *aip;
10863
10864         if (!Ai_firing_enabled) {
10865                 return;
10866         }
10867
10868         if (ss->current_hits < 0.0f) {
10869                 return;
10870         }
10871
10872         if ( ship_subsys_disrupted(ss) ){               // AL 1/19/98: Make sure turret isn't suffering disruption effects
10873                 return;
10874         }
10875
10876         // Check turret free
10877         if (ss->weapons.flags & SW_FLAG_TURRET_LOCK) {
10878                 return;
10879         }
10880
10881         // If beam weapon, check beam free
10882         if ( (Weapon_info[tp->turret_weapon_type].wi_flags & WIF_BEAM) && !(ss->weapons.flags & SW_FLAG_BEAM_FREE) ) {
10883                 return;
10884         }
10885
10886         SDL_assert( shipp->objnum == parent_objnum );
10887
10888         if ( tp->turret_weapon_type < 0 ){
10889                 return;
10890         }
10891
10892         // Monitor number of calls to ai_fire_from_turret
10893         Num_ai_firing++;
10894
10895         turret_weapon_class = tp->turret_weapon_type;
10896
10897         // AL 09/14/97: ensure ss->turret_enemy_objnum != -1 before setting lep
10898         if ( (ss->turret_enemy_objnum >= 0 && ss->turret_enemy_objnum < MAX_OBJECTS) && (ss->turret_enemy_sig == Objects[ss->turret_enemy_objnum].signature)) {
10899                 lep = &Objects[ss->turret_enemy_objnum];
10900
10901                 // MK -- here is where turret is targeting a bomb.  I simply return for now.  We should force
10902                 // a target change -- or better yet, never pick a weapon when this turret has a "huge" weapon
10903                 // loaded.
10904
10905                 // we only care about targets which are ships.
10906                 //if ( lep->type != OBJ_SHIP )
10907                 //      return;
10908
10909                 //      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.
10910                 if ( Weapon_info[turret_weapon_class].wi_flags & WIF_HUGE ) {
10911                         if ( lep->type != OBJ_SHIP ) {
10912                                 return;
10913                         }
10914                         if ( !(Ship_info[Ships[lep->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) ) {
10915                                 return;
10916                         }
10917                 }
10918
10919                 // If targeting protected or beam protected ship, don't fire.  Reset enemy objnum
10920                 if (lep->type == OBJ_SHIP) {
10921                         // Check if we're targeting a protected ship
10922                         if (lep->flags & OF_PROTECTED) {
10923                                 ss->turret_enemy_objnum = -1;
10924                                 ss->turret_time_enemy_in_range = 0.0f;
10925                                 return;
10926                         }
10927
10928                         // Check if we're targeting a beam protected ship with a beam weapon
10929                         if ( (lep->flags & OF_BEAM_PROTECTED) && (Weapon_info[turret_weapon_class].wi_flags & WIF_BEAM) ) {
10930                                 ss->turret_enemy_objnum = -1;
10931                                 ss->turret_time_enemy_in_range = 0.0f;
10932                                 return;
10933                         }
10934                 }
10935         } else {
10936                 ss->turret_enemy_objnum = -1;
10937                 lep = NULL;
10938         }
10939         
10940         SDL_assert((parent_objnum >= 0) && (parent_objnum < MAX_OBJECTS));
10941         objp = &Objects[parent_objnum];
10942         SDL_assert(objp->type == OBJ_SHIP);
10943         aip = &Ai_info[Ships[objp->instance].ai_index];
10944
10945         // Use the turret info for all guns, not one gun in particular.
10946         vector   gvec, gpos;
10947         ship_get_global_turret_info(&Objects[parent_objnum], tp, &gpos, &gvec);
10948
10949         // Rotate the turret even if time hasn't elapsed, since it needs to turn to face its target.
10950         use_angles = aifft_rotate_turret(shipp, parent_objnum, ss, objp, lep, &predicted_enemy_pos, &gvec);
10951
10952         if ( !timestamp_elapsed(ss->turret_next_fire_stamp)){
10953                 return;
10954         }
10955
10956         // Don't try to fire beyond weapon_limit_range
10957         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);
10958
10959         // if beam weapon in nebula and target not tagged, decrase firing range
10960         extern int Nebula_sec_range;
10961         if (Weapon_info[turret_weapon_class].wi_flags & WIF_BEAM) {
10962                 if ( !((shipp->tag_left > 0) || (shipp->level2_tag_left > 0)) ) {
10963                         if (Nebula_sec_range) {
10964                                 weapon_firing_range *= float(BEAM_NEBULA_RANGE_REDUCE_FACTOR);
10965                         }
10966                 }
10967         }
10968
10969         if (ss->turret_enemy_objnum != -1) {
10970                 float dist_to_enemy = vm_vec_normalized_dir(&v2e, &predicted_enemy_pos, &gpos) - lep->radius;
10971                 if (dist_to_enemy > weapon_firing_range) {
10972                         ss->turret_enemy_objnum = -1;           //      Force picking of new enemy.
10973                 }
10974         }
10975
10976         // Turret spawn weapons are a special case.  They fire if there are enough enemies in the 
10977         // immediate area (not necessarily in the turret fov).
10978         if ( Weapon_info[turret_weapon_class].wi_flags & WIF_SPAWN ) {
10979                 int num_ships_nearby;
10980                 num_ships_nearby = num_nearby_fighters(get_enemy_team_mask(parent_objnum), &gpos, 1500.0f);
10981                 if (( num_ships_nearby >= 3 ) || ((num_ships_nearby >= 2) && (frand() < 0.1f))) {
10982                         turret_fire_weapon(ss, parent_objnum, &gpos, &ss->turret_last_fire_direction);
10983                 } else {
10984                         ss->turret_next_fire_stamp = timestamp(1000);   //      Regardless of firing rate, don't check whether should fire for awhile.
10985                 }
10986                 return;
10987         }
10988
10989         //      Maybe pick a new enemy.
10990         if ( turret_should_pick_new_target(ss) ) {
10991                 Num_find_turret_enemy++;
10992                 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);
10993                 SDL_assert(objnum < 0 || is_target_beam_valid(ss, objnum));
10994
10995                 if (objnum != -1) {
10996                         if (ss->turret_enemy_objnum == -1) {
10997                                 ss->turret_enemy_objnum = objnum;
10998                                 ss->turret_enemy_sig = Objects[objnum].signature;
10999                                 // why return?
11000                                 return;
11001                         } else {
11002                                 ss->turret_enemy_objnum = objnum;
11003                                 ss->turret_enemy_sig = Objects[objnum].signature;
11004                         }
11005                 } else {
11006                         ss->turret_enemy_objnum = -1;
11007                 }
11008
11009                 if (ss->turret_enemy_objnum != -1) {
11010                         float   dot = 1.0f;
11011                         lep = &Objects[ss->turret_enemy_objnum];
11012                         if ( lep->type == OBJ_SHIP ) {
11013                                 ss->targeted_subsys = aifft_find_turret_subsys(objp, ss, lep, &dot);                            
11014                         }
11015                         ss->turret_next_enemy_check_stamp = timestamp((int) (max(dot, 0.5f)*2000.0f) + 1000);
11016                 } else {
11017                         ss->turret_next_enemy_check_stamp = timestamp((int) (2000.0f * frand_range(0.9f, 1.1f)));       //      Check every two seconds
11018                 }
11019         }
11020
11021         //      If still don't have an enemy, return.  Or, if enemy is protected, return.
11022         if (ss->turret_enemy_objnum != -1) {
11023                 //      Don't shoot at ship we're going to dock with.
11024                 if (ss->turret_enemy_objnum == aip->dock_objnum) {
11025                         ss->turret_enemy_objnum = -1;
11026                         return;
11027                 }
11028
11029                 if (Objects[ss->turret_enemy_objnum].flags & OF_PROTECTED) {
11030                         //      This can happen if the enemy was selected before it became protected.
11031                         ss->turret_enemy_objnum = -1;
11032                         return;
11033                 }
11034                 lep = &Objects[ss->turret_enemy_objnum];
11035         } else {
11036                 if (timestamp_until(ss->turret_next_fire_stamp) < 500) {
11037                         ss->turret_next_fire_stamp = timestamp(500);
11038                 }
11039                 return;
11040         }
11041
11042         if ( lep == NULL ){
11043                 return;
11044         }
11045
11046         SDL_assert(ss->turret_enemy_objnum != -1);
11047
11048         float dot = vm_vec_dot(&v2e, &gvec);
11049
11050         if (dot > tp->turret_fov ) {
11051                 // Ok, the turret is lined up... now line up a particular gun.
11052                 int ok_to_fire = 0;
11053                 float dist_to_enemy;
11054
11055                 // We're ready to fire... now get down to specifics, like where is the
11056                 // actual gun point and normal, not just the one for whole turret.
11057                 ship_get_global_turret_gun_info(&Objects[parent_objnum], ss, &gpos, &gvec, use_angles, &predicted_enemy_pos);
11058                 ss->turret_next_fire_pos++;
11059
11060                 // Fire in the direction the turret is facing, not right at the target regardless of turret dir.
11061                 vm_vec_sub(&v2e, &predicted_enemy_pos, &gpos);
11062                 dist_to_enemy = vm_vec_normalize(&v2e);
11063                 dot = vm_vec_dot(&v2e, &gvec);
11064
11065                 // 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
11066                 // and make them less lethal
11067                 if(Weapon_info[turret_weapon_class].wi_flags & WIF_FLAK){
11068                         flak_jitter_aim(&v2e, dist_to_enemy, ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS));
11069                 }
11070
11071                 // Fire if:
11072                 //              dumbfire and nearly pointing at target.
11073                 //              heat seeking and target in a fairly wide cone.
11074                 //              aspect seeking and target is locked.
11075                 turret_weapon_class = tp->turret_weapon_type;
11076
11077                 // if dumbfire (lasers and non-homing missiles)
11078                 if ( !(Weapon_info[turret_weapon_class].wi_flags & WIF_HOMING) ) {
11079                         if ((dist_to_enemy < 75.0f) || (dot > AICODE_TURRET_DUMBFIRE_ANGLE )) {
11080                                 turret_update_enemy_in_range(ss, 2*Weapon_info[turret_weapon_class].fire_wait);
11081                                 ok_to_fire = 1;
11082                         }
11083                 } else if ( Weapon_info[turret_weapon_class].wi_flags & WIF_HOMING_HEAT ) {     // if heat seekers
11084                         if ((dist_to_enemy < 50.0f) || (dot > AICODE_TURRET_HEATSEEK_ANGLE )) {
11085                                 turret_update_enemy_in_range(ss, 2*Weapon_info[turret_weapon_class].fire_wait);
11086                                 ok_to_fire = 1;
11087                         }
11088                 } else if ( Weapon_info[turret_weapon_class].wi_flags & WIF_HOMING_ASPECT ) {   // if aspect seeker
11089                         if ((dist_to_enemy < 50.0f) || (dot > AICODE_TURRET_DUMBFIRE_ANGLE )) {
11090                                 turret_update_enemy_in_range(ss, 2*Weapon_info[turret_weapon_class].fire_wait);
11091                         }
11092                         if ( turret_should_fire_aspect(ss, dot, turret_weapon_class) ) {
11093                                 ok_to_fire = 1;
11094                         }
11095                 }
11096
11097                 if ( ok_to_fire ) {
11098                         Num_turrets_fired++;
11099                         
11100                         turret_fire_weapon(ss, parent_objnum, &gpos, &v2e, &predicted_enemy_pos);                                               
11101                 } else {
11102                         turret_update_enemy_in_range(ss, -4*Weapon_info[tp->turret_weapon_type].fire_wait);
11103                         ss->turret_next_fire_stamp = timestamp(500);
11104                 }
11105         } else {
11106                 // Lost him!
11107                 ss->turret_enemy_objnum = -1;           //      Reset enemy objnum, find a new one next frame.
11108                 ss->turret_time_enemy_in_range = 0.0f;
11109         }
11110 }
11111
11112 // TURRET END
11113
11114 #ifndef NDEBUG
11115 #define MAX_AI_DEBUG_RENDER_STUFF       100
11116 typedef struct ai_render_stuff {
11117         ship_subsys     *ss;
11118         int                     parent_objnum;
11119 } ai_render_stuff;
11120
11121 ai_render_stuff AI_debug_render_stuff[MAX_AI_DEBUG_RENDER_STUFF];
11122
11123 int     Num_AI_debug_render_stuff = 0;
11124
11125 void ai_debug_render_stuff()
11126 {
11127         vertex  vert1, vert2;
11128         vector  gpos2;
11129         int             i;
11130
11131         for (i=0; i<Num_AI_debug_render_stuff; i++) {
11132                 ship_subsys     *ss;
11133                 int     parent_objnum;
11134                 vector  gpos, gvec;
11135                 model_subsystem *tp;
11136
11137                 ss = AI_debug_render_stuff[i].ss;
11138                 tp = ss->system_info;
11139
11140                 parent_objnum = AI_debug_render_stuff[i].parent_objnum;
11141
11142                 ship_get_global_turret_info(&Objects[parent_objnum], tp, &gpos, &gvec);
11143                 g3_rotate_vertex(&vert1, &gpos);
11144                 vm_vec_scale_add(&gpos2, &gpos, &gvec, 20.0f);
11145                 g3_rotate_vertex(&vert2, &gpos2);
11146                 gr_set_color(0, 0, 255);
11147                 g3_draw_sphere(&vert1, 2.0f);
11148                 gr_set_color(255, 0, 255);
11149                 g3_draw_sphere(&vert2, 2.0f);
11150                 g3_draw_line(&vert1, &vert2);
11151         }
11152
11153         // draw from beta to its goal point
11154 /*      for (i=0; i<6; i++) {
11155                 ai_info *aip = &Ai_info[i];
11156                 gr_set_color(0, 0, 255);
11157                 g3_rotate_vertex(&vert1, &Objects[i].pos);
11158                 g3_rotate_vertex(&vert2, &aip->goal_point);
11159                 g3_draw_line(&vert1, &vert2);
11160         } */
11161         
11162
11163         Num_AI_debug_render_stuff = 0;
11164 }
11165
11166 #endif
11167
11168 #ifndef NDEBUG
11169 int     Msg_count_4996 = 0;
11170 #endif
11171
11172 //      --------------------------------------------------------------------------
11173 // Process subobjects of object objnum.
11174 //      Deal with engines disabled.
11175 void process_subobjects(int objnum)
11176 {
11177         model_subsystem *psub;
11178         ship_subsys     *pss;
11179         object  *objp = &Objects[objnum];
11180         ship            *shipp = &Ships[objp->instance];
11181         ai_info *aip = &Ai_info[shipp->ai_index];
11182         ship_info       *sip = &Ship_info[shipp->ship_info_index];
11183
11184         for ( pss = GET_FIRST(&shipp->subsys_list); pss !=END_OF_LIST(&shipp->subsys_list); pss = GET_NEXT(pss) ) {
11185                 psub = pss->system_info;
11186
11187                 // Don't process destroyed objects
11188                 if ( pss->current_hits <= 0.0f ) 
11189                         continue;
11190
11191                 switch (psub->type) {
11192                 case SUBSYSTEM_TURRET:
11193                         if ( psub->turret_num_firing_points > 0 )       {
11194                                 ai_fire_from_turret(shipp, pss, objnum);
11195                         } else {
11196 #ifndef NDEBUG
11197                                 if (!Msg_count_4996) {
11198                                         Warning( LOCATION, "Ship '%s' has turrets with no guns!\nProbably a model problem, so get an artist!", shipp->ship_name );
11199                                         Msg_count_4996++;
11200                                 }
11201 #endif
11202                                 }
11203                         break;
11204
11205                 case SUBSYSTEM_ENGINE:
11206                 case SUBSYSTEM_NAVIGATION:
11207                 case SUBSYSTEM_COMMUNICATION:
11208                 case SUBSYSTEM_WEAPONS:
11209                 case SUBSYSTEM_SENSORS:
11210                 case SUBSYSTEM_UNKNOWN:
11211                         break;
11212
11213                 // next set of subsystems may rotation
11214                 case SUBSYSTEM_RADAR:
11215                 case SUBSYSTEM_SOLAR:
11216                 case SUBSYSTEM_GAS_COLLECT:
11217                 case SUBSYSTEM_ACTIVATION:
11218                         break;
11219                 default:
11220                         Error(LOCATION, "Illegal subsystem type.\n");
11221                 }
11222
11223                 // do solar/radar/gas/activator rotation here
11224                 if ( psub->flags & MSS_FLAG_ROTATES )   {
11225                         if (psub->flags & MSS_FLAG_STEPPED_ROTATE       ) {
11226                                 submodel_stepped_rotate(psub, &pss->submodel_info_1);
11227                         } else {
11228                                 submodel_rotate(psub, &pss->submodel_info_1 );
11229                         }
11230                 }
11231
11232         }
11233
11234         //      Deal with a ship with blown out engines.
11235         if (ship_get_subsystem_strength(shipp, SUBSYSTEM_ENGINE) == 0.0f) {
11236                 if (sip->flags & (SIF_FIGHTER | SIF_BOMBER)) {
11237                         // AL: Only attack forever if not trying to depart to a docking bay.  Need to have this in, since
11238                         //     a ship may get repaired... and it should still try to depart.  Since docking bay departures
11239                         //     are not handled as goals, we don't want to leave the AIM_BAY_DEPART mode.
11240                         if ( aip->mode != AIM_BAY_DEPART ) {
11241                                 ai_attack_object(objp, NULL, 99, NULL);         //      Regardless of current mode, enter attack mode.
11242                                 aip->submode = SM_ATTACK_FOREVER;                               //      Never leave attack submode, don't avoid, evade, etc.
11243                         }
11244                 }
11245         }
11246
11247
11248 }
11249
11250 //      Given an object and the wing it's in, return its index in the wing list.
11251 //      This defines its location in the wing formation.
11252 //      If the object can't be found in the wing, return -1.
11253 //      *objp           object of interest
11254 //      wingnum the wing *objp is in
11255 int get_wing_index(object *objp, int wingnum)
11256 {
11257         wing    *wingp;
11258         int     i;
11259
11260         SDL_assert((wingnum >= 0) && (wingnum < MAX_WINGS));
11261
11262         wingp = &Wings[wingnum];
11263
11264         for (i=wingp->current_count-1; i>=0; i--)
11265                 if ( objp->instance == wingp->ship_index[i] )
11266                         break;
11267
11268         return i;               //      Note, returns -1 if string not found.
11269 }
11270
11271 //      Given a wing, return a pointer to the object of its leader.
11272 //      Asserts if object not found.
11273 //      Currently, the wing leader is defined as the first object in the wing.
11274 //      wingnum         Wing number in Wings array.
11275 //      If wing leader is disabled, swap it with another ship.
11276 object * get_wing_leader(int wingnum)
11277 {
11278         wing            *wingp;
11279         int             ship_num;
11280
11281         SDL_assert((wingnum >= 0) && (wingnum < MAX_WINGS));
11282
11283         wingp = &Wings[wingnum];
11284
11285         SDL_assert(wingp->current_count != 0);                  //      Make sure there is a leader
11286
11287         ship_num = wingp->ship_index[0];
11288
11289         //      If this ship is disabled, try another ship in the wing.
11290         int n = 0;
11291         while (ship_get_subsystem_strength(&Ships[ship_num], SUBSYSTEM_ENGINE) == 0.0f) {
11292                 n++;
11293                 if (n >= wingp->current_count)
11294                         break;  
11295                 ship_num = wingp->ship_index[n];
11296         }
11297
11298         if (( n != 0) && (n != wingp->current_count)) {
11299                 int t = wingp->ship_index[0];
11300                 wingp->ship_index[0] = wingp->ship_index[n];
11301                 wingp->ship_index[n] = t;
11302         }
11303
11304         return &Objects[Ships[ship_num].objnum];
11305 }
11306
11307 #define DEFAULT_WING_X_DELTA            1.0f
11308 #define DEFAULT_WING_Y_DELTA            0.25f
11309 #define DEFAULT_WING_Z_DELTA            0.75f
11310 #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))
11311 // next constant is higher that MAX_SHIPS_IN_WINGS to deal with forming on player's wing
11312 #define MAX_FORMATION_ROWS              4
11313
11314 //      Given a position in a wing, return the desired location of the ship relative to the leader
11315 //      *_delta_vec             OUTPUT.  delta vector based on wing_index
11316 //      wing_index              position in wing.
11317 void get_wing_delta(vector *_delta_vec, int wing_index)
11318 {
11319         int     wi0;
11320
11321         SDL_assert(wing_index >= 0);
11322
11323         int     k, row, column;
11324
11325         int bank = wing_index / (MAX_FORMATION_ROWS*(MAX_FORMATION_ROWS+1)/2);
11326         wi0 = wing_index % (MAX_FORMATION_ROWS * (MAX_FORMATION_ROWS+1)/2);
11327
11328         k = 0;
11329         for (row=1; row<MAX_FORMATION_ROWS+1; row++) {
11330                 k += row;
11331                 if (wi0 < k)
11332                         break;
11333         }
11334
11335         row--;
11336         column = wi0 - k + row + 1;
11337
11338         _delta_vec->xyz.x = ((float) column - (float) row/2.0f) * DEFAULT_WING_X_DELTA/DEFAULT_WING_MAG;
11339         _delta_vec->xyz.y = ((float)row + (float)bank*2.25f) * DEFAULT_WING_Y_DELTA/DEFAULT_WING_MAG;
11340         _delta_vec->xyz.z = - ((float)row + 0.5f * (float) bank) * DEFAULT_WING_Z_DELTA/DEFAULT_WING_MAG;
11341 }
11342
11343 //      Compute the largest radius of a ship in a *objp's wing.
11344 float gwlr_1(object *objp, ai_info *aip)
11345 {
11346         int             wingnum = aip->wing;
11347         float           max_radius;
11348         object  *o;
11349         ship_obj        *so;
11350
11351         SDL_assert(wingnum >= 0);
11352
11353         max_radius = objp->radius;
11354
11355         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11356                 o = &Objects[so->objnum];
11357                 if (Ai_info[Ships[o->instance].ai_index].wing == wingnum)
11358                         if (o->radius > max_radius)
11359                                 max_radius = o->radius;
11360         }
11361
11362         return max_radius;
11363 }
11364
11365 //      Compute the largest radius of a ship forming on *objp's wing.
11366 float gwlr_object_1(object *objp, ai_info *aip)
11367 {
11368         float           max_radius;
11369         object  *o;
11370         ship_obj        *so;
11371
11372         max_radius = objp->radius;
11373
11374         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11375                 o = &Objects[so->objnum];
11376                 if (Ai_info[Ships[o->instance].ai_index].goal_objnum == OBJ_INDEX(objp))
11377                         if (o->radius > max_radius)
11378                                 max_radius = o->radius;
11379         }
11380
11381         return max_radius;
11382 }
11383
11384 //      For the wing that *objp is part of, return the largest ship radius in that wing.
11385 float get_wing_largest_radius(object *objp, int formation_object_flag)
11386 {
11387         ship            *shipp;
11388         ai_info *aip;
11389
11390         SDL_assert(objp->type == OBJ_SHIP);
11391         SDL_assert((objp->instance >= 0) && (objp->instance < MAX_OBJECTS));
11392         shipp = &Ships[objp->instance];
11393         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11394         aip = &Ai_info[shipp->ai_index];
11395
11396         if (formation_object_flag) {
11397                 return gwlr_object_1(objp, aip);
11398         } else {
11399                 return gwlr_1(objp, aip);
11400         }
11401
11402 }
11403
11404 float Wing_y_scale = 2.0f;
11405 float Wing_scale = 1.0f;
11406 DCF(wing_y_scale, "")
11407 {
11408         dc_get_arg(ARG_FLOAT);
11409         Wing_y_scale = Dc_arg_float;
11410 }
11411
11412 DCF(wing_scale, "")
11413 {
11414         dc_get_arg(ARG_FLOAT);
11415         Wing_scale = Dc_arg_float;
11416 }
11417
11418 // Given a wing leader and a position in the wing formation, return the desired absolute location to fly to.
11419 //      Returns result in *result_pos.
11420 void get_absolute_wing_pos(vector *result_pos, object *leader_objp, int wing_index, int formation_object_flag)
11421 {
11422         vector  wing_delta, rotated_wing_delta;
11423         float           wing_spread_size;
11424
11425         get_wing_delta(&wing_delta, wing_index);                //      Desired location in leader's reference frame
11426
11427         wing_spread_size = max(50.0f, 3.0f * get_wing_largest_radius(leader_objp, formation_object_flag) + 15.0f);
11428
11429         // for player obj (1) move ships up 20% (2) scale formation up 20%
11430         if (leader_objp->flags & OF_PLAYER_SHIP) {
11431                 wing_delta.xyz.y *= Wing_y_scale;
11432                 wing_spread_size *= Wing_scale;
11433         }
11434
11435         vm_vec_scale(&wing_delta, wing_spread_size * (1.0f + leader_objp->phys_info.speed/70.0f));
11436
11437         vm_vec_unrotate(&rotated_wing_delta, &wing_delta, &leader_objp->orient);        //      Rotate into leader's reference.
11438
11439         vm_vec_add(result_pos, &leader_objp->pos, &rotated_wing_delta); //      goal_point is absolute 3-space point.
11440 }
11441
11442 #ifndef NDEBUG
11443 int Debug_render_wing_phantoms;
11444
11445 void render_wing_phantoms(object *objp)
11446 {
11447         int             i;
11448         ship            *shipp;
11449         ai_info *aip;
11450         int             wingnum;
11451         int             wing_index;             //      Index in wing struct, defines 3-space location in wing.
11452         vector  goal_point;
11453         
11454         SDL_assert(objp->type == OBJ_SHIP);
11455         SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11456
11457         shipp = &Ships[objp->instance];
11458         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11459
11460         aip = &Ai_info[shipp->ai_index];
11461
11462         wingnum = aip->wing;
11463
11464         if (wingnum == -1)
11465                 return;
11466
11467         wing_index = get_wing_index(objp, wingnum);
11468
11469         //      If this ship is NOT the leader, abort.
11470         if (wing_index != 0)
11471                 return;
11472
11473         for (i=0; i<32; i++)
11474                 if (Debug_render_wing_phantoms & (1 << i)) {
11475                         get_absolute_wing_pos(&goal_point, objp, i, 0);
11476         
11477                         vertex  vert;
11478                         gr_set_color(255, 0, 128);
11479                         g3_rotate_vertex(&vert, &goal_point);
11480                         g3_draw_sphere(&vert, 2.0f);
11481                 }
11482
11483         Debug_render_wing_phantoms = 0;
11484
11485 }
11486
11487 void render_wing_phantoms_all()
11488 {
11489         object  *objp;
11490         ship_obj        *so;
11491
11492         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11493                 ship            *shipp;
11494                 ai_info *aip;
11495                 int             wingnum;
11496                 int             wing_index;             //      Index in wing struct, defines 3-space location in wing.
11497
11498                 objp = &Objects[so->objnum];
11499                 
11500                 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11501                 shipp = &Ships[objp->instance];
11502                 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11503
11504                 aip = &Ai_info[shipp->ai_index];
11505
11506                 wingnum = aip->wing;
11507
11508                 if (wingnum == -1)
11509                         continue;
11510
11511                 wing_index = get_wing_index(objp, wingnum);
11512
11513                 //      If this ship is NOT the leader, abort.
11514                 if (wing_index != 0)
11515                         continue;
11516                 
11517                 render_wing_phantoms(objp);
11518
11519                 return;
11520         }
11521 }
11522
11523 #endif
11524
11525 //      Hook from goals code to AI.
11526 //      Force a wing to fly in formation.
11527 //      Sets AIF_FORMATION bit in ai_flags.
11528 //      wingnum         Wing to force to fly in formation
11529 void ai_fly_in_formation(int wingnum)
11530 {
11531         object  *objp;
11532         ship            *shipp;
11533         ship_obj        *so;
11534
11535         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11536                 objp = &Objects[so->objnum];
11537                 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11538
11539                 shipp = &Ships[objp->instance];
11540                 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11541
11542                 if (Ai_info[shipp->ai_index].wing == wingnum) {
11543                         Ai_info[shipp->ai_index].ai_flags |= AIF_FORMATION_WING;
11544                         Ai_info[shipp->ai_index].ai_flags &= ~AIF_FORMATION_OBJECT;
11545                 }
11546         }
11547 }
11548
11549 //      Hook from goals code to AI.
11550 //      Force a wing to abandon formation flying.
11551 //      Clears AIF_FORMATION bit in ai_flags.
11552 //      wingnum         Wing to force to fly in formation
11553 void ai_disband_formation(int wingnum)
11554 {
11555         object  *objp;
11556         ship            *shipp;
11557         ship_obj        *so;
11558
11559         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11560                 objp = &Objects[so->objnum];
11561                 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11562
11563                 shipp = &Ships[objp->instance];
11564                 SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11565
11566                 if (Ai_info[shipp->ai_index].wing == wingnum) {
11567                         Ai_info[shipp->ai_index].ai_flags &= ~AIF_FORMATION_WING;
11568                 }
11569         }
11570 }
11571
11572 float   Leader_chaos = 0.0f;
11573 int Chaos_frame = -1;
11574
11575 //      Return true if objp is flying in an erratic manner
11576 //      Only true if objp is a player
11577 int formation_is_leader_chaotic(object *objp)
11578 {
11579         if (Game_mode & GM_MULTIPLAYER)
11580                 return 0;
11581
11582         if (objp != Player_obj)
11583                 return 0;
11584
11585         if (Framecount != Chaos_frame) {
11586                 float   speed_scale;
11587                 float   fdot, udot;
11588
11589                 speed_scale = 3.0f + objp->phys_info.speed * 0.1f;
11590
11591                 fdot = 5.0f * (1.0f - vm_vec_dot(&objp->orient.v.fvec, &objp->last_orient.v.fvec)) * flFrametime;
11592                 udot = 8.0f * (1.0f - vm_vec_dot(&objp->orient.v.uvec, &objp->last_orient.v.uvec)) * flFrametime;
11593
11594                 Leader_chaos += fdot * speed_scale + udot * speed_scale;
11595
11596                 Leader_chaos *= (1.0f - flFrametime*0.2f);
11597
11598                 if (Leader_chaos < 0.0f)
11599                         Leader_chaos = 0.0f;
11600                 else if (Leader_chaos > 1.7f)
11601                         Leader_chaos = 1.7f;
11602
11603                 //nprintf(("AI", "Frame %i: chaos = %7.4f\n", Framecount, Leader_chaos));
11604
11605                 Chaos_frame = Framecount;
11606         }
11607
11608         return (Leader_chaos > 1.0f);
11609 }
11610
11611 // Fly in formation.
11612 //      Make Pl_objp assume its proper place in formation.
11613 //      If the leader of the wing is doing something stupid, like fighting a battle,
11614 //      then the poor sap wingmates will be in for a "world of hurt"
11615 //      Return TRUE if we need to process this object's normal mode
11616 int ai_formation()
11617 {
11618         object  *leader_objp;
11619         ship            *shipp;
11620         ai_info *aip, *laip;
11621         int             wingnum;
11622         int             wing_index;             //      Index in wing struct, defines 3-space location in wing.
11623         int             player_wing;    // index of the players wingnum
11624         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;
11625         float           dot_to_goal, dist_to_goal, leader_speed;
11626
11627         SDL_assert(Pl_objp->type == OBJ_SHIP);
11628         SDL_assert((Pl_objp->instance >= 0) && (Pl_objp->instance < MAX_SHIPS));
11629
11630         shipp = &Ships[Pl_objp->instance];
11631
11632         SDL_assert((shipp->ai_index >= 0) && (shipp->ai_index < MAX_AI_INFO));
11633
11634         aip = &Ai_info[shipp->ai_index];
11635
11636         SDL_assert((aip->ai_flags & AIF_FORMATION) != AIF_FORMATION);   //      Make sure not both types of formation flying in effect.
11637
11638         //      Determine which kind of formation flying.
11639         //      If tracking an object, not in waypoint mode:
11640         if (aip->ai_flags & AIF_FORMATION_OBJECT) {
11641                 if ((aip->goal_objnum < 0) || (aip->goal_objnum >= MAX_OBJECTS)) {
11642                         aip->ai_flags &= ~AIF_FORMATION_OBJECT;
11643                         return 1;
11644                 }
11645                 
11646                 wing_index = ai_formation_object_get_slotnum(aip->goal_objnum, Pl_objp);
11647                 leader_objp = &Objects[aip->goal_objnum];
11648         } else {        //      Formation flying in waypoint mode.
11649                 SDL_assert(aip->ai_flags & AIF_FORMATION_WING);
11650                 if (aip->mode != AIM_WAYPOINTS) {
11651                         aip->ai_flags &= ~AIF_FORMATION_WING;
11652                         return 1;
11653                 }
11654
11655                 wingnum = aip->wing;
11656
11657                 if (wingnum == -1)
11658                         return 1;
11659
11660                 // disable formation flying for any ship in the players wing
11661                 player_wing = Ships[Player_obj->instance].wingnum;
11662                 if ( (player_wing != -1) && (wingnum == player_wing) )
11663                         return 1;
11664
11665                 wing_index = get_wing_index(Pl_objp, wingnum);
11666
11667                 leader_objp = get_wing_leader(wingnum);
11668
11669         }
11670
11671         //      If docked with a ship in this wing, only the more massive one actually flies in formation.
11672         if (aip->dock_objnum != -1) {
11673                 object  *other_objp = &Objects[aip->dock_objnum];
11674                 ai_info *other_aip = &Ai_info[Ships[other_objp->instance].ai_index];
11675
11676                 if (aip->wing == other_aip->wing) {
11677                         if (Pl_objp->phys_info.mass < other_objp->phys_info.mass)
11678                                 return 0;
11679                         else if (Pl_objp->phys_info.mass == other_objp->phys_info.mass) {
11680                                 if (Pl_objp->signature < other_objp->signature)
11681                                         return 0;
11682                         }
11683                 }
11684         }
11685
11686         SDL_assert(leader_objp != NULL);
11687         laip = &Ai_info[Ships[leader_objp->instance].ai_index];
11688
11689         //      Make sure we're really in this wing.
11690         if (wing_index == -1)
11691                 return 1;
11692
11693         //      If this ship is the leader, abort, as he doesn't have to follow anyone.
11694         if (wing_index == 0) {
11695                 // nprintf(("AI", "Hmm, wing leader %s in ai_formation for no good reason.\n", shipp->ship_name));
11696                 return 1;
11697         }
11698
11699         if (aip->mode == AIM_WAYPOINTS) {
11700                 aip->wp_list = laip->wp_list;
11701                 if (laip->wp_index < Waypoint_lists[laip->wp_list].count)
11702                         aip->wp_index = laip->wp_index;
11703                 else
11704                         aip->wp_index = Waypoint_lists[laip->wp_list].count - 1;
11705                 aip->wp_flags = laip->wp_flags;
11706                 aip->wp_dir = laip->wp_dir;
11707         }
11708
11709         #ifndef NDEBUG
11710         Debug_render_wing_phantoms |= (1 << wing_index);
11711         #endif
11712
11713         leader_speed = leader_objp->phys_info.speed;
11714         vector leader_vec = leader_objp->phys_info.vel;
11715
11716         get_absolute_wing_pos(&goal_point, leader_objp, wing_index, aip->ai_flags & AIF_FORMATION_OBJECT);
11717         vm_vec_scale_add(&future_goal_point_5, &goal_point, &leader_vec, 10.0f);
11718         vm_vec_scale_add(&future_goal_point_2, &goal_point, &leader_vec, 5.0f);
11719         vm_vec_scale_add(&future_goal_point_x, &goal_point, &leader_objp->orient.v.fvec, 10.0f);        //      used when very close to destination
11720         vm_vec_scale_add(&future_goal_point_1000x, &goal_point, &leader_objp->orient.v.fvec, 1000.0f);  //      used when very close to destination
11721
11722         //      Now, get information telling this object how to turn and accelerate to get to its
11723         //      desired location.
11724         vm_vec_sub(&vec_to_goal, &goal_point, &Pl_objp->pos);
11725         if ( vm_vec_mag_quick(&vec_to_goal) < AICODE_SMALL_MAGNITUDE )
11726                 vec_to_goal.xyz.x += 0.1f;
11727
11728         vm_vec_copy_normalize(&dir_to_goal, &vec_to_goal);
11729         //dot_to_goal = vm_vec_dot(&dir_to_goal, &leader_objp->orient.v.fvec);
11730         dot_to_goal = vm_vec_dot(&dir_to_goal, &Pl_objp->orient.v.fvec);
11731         dist_to_goal = vm_vec_dist_quick(&Pl_objp->pos, &goal_point);
11732         float   dist_to_goal_2 = vm_vec_dist_quick(&Pl_objp->pos, &future_goal_point_2);
11733
11734         // 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));
11735
11736         int     chaotic_leader = 0;
11737
11738         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.
11739
11740         if (dist_to_goal > 500.0f) {
11741                 turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
11742                 accelerate_ship(aip, 1.0f);
11743         } else if (dist_to_goal > 200.0f) {
11744                 if (dot_to_goal > -0.5f) {
11745                         turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
11746                         float range_speed = shipp->current_max_speed - leader_speed;
11747                         if (range_speed > 0.0f)
11748                                 set_accel_for_target_speed(Pl_objp, leader_speed + range_speed * (dist_to_goal+100.0f)/500.0f);
11749                         else
11750                                 set_accel_for_target_speed(Pl_objp, shipp->current_max_speed);
11751                 } else {
11752                         turn_towards_point(Pl_objp, &future_goal_point_5, NULL, 0.0f);
11753                         if (leader_speed > 10.0f)
11754                                 set_accel_for_target_speed(Pl_objp, leader_speed *(1.0f + dot_to_goal));
11755                         else
11756                                 set_accel_for_target_speed(Pl_objp, 10.0f);
11757                 }
11758         } else {
11759                 vector  v2f2;
11760                 float   dot_to_f2;
11761
11762                 vm_vec_normalized_dir(&v2f2, &future_goal_point_2, &Pl_objp->pos);
11763                 dot_to_f2 = vm_vec_dot(&v2f2, &Pl_objp->orient.v.fvec);
11764
11765                 //      Leader flying like a maniac.  Don't try hard to form on wing.
11766                 if (chaotic_leader) {
11767                         turn_towards_point(Pl_objp, &future_goal_point_2, NULL, 0.0f);
11768                         set_accel_for_target_speed(Pl_objp, min(leader_speed*0.8f, 20.0f));
11769                 } else if (dist_to_goal > 75.0f) {
11770                         turn_towards_point(Pl_objp, &future_goal_point_2, NULL, 0.0f);
11771                         float   delta_speed;
11772                         float range_speed = shipp->current_max_speed - leader_speed;
11773                         if (range_speed > 0.0f)
11774                                 delta_speed = dist_to_goal_2/500.0f * range_speed;
11775                         else
11776                                 delta_speed = shipp->current_max_speed - leader_speed;
11777                         if (dot_to_goal < 0.0f) {
11778                                 delta_speed = -delta_speed;
11779                                 if (-delta_speed > leader_speed/2)
11780                                         delta_speed = -leader_speed/2;
11781                         }
11782
11783                         if (leader_speed < 5.0f)
11784                                 if (delta_speed < 5.0f)
11785                                         delta_speed = 5.0f;
11786
11787                         float scale = dot_to_f2;
11788                         if (scale < 0.1f)
11789                                 scale = 0.0f;
11790                         else
11791                                 scale *= scale;
11792
11793                         set_accel_for_target_speed(Pl_objp, scale * (leader_speed + delta_speed));
11794                 } else {
11795                         //nprintf(("AI", "Dot = %7.3f\n", dot_to_goal));
11796
11797                         if (leader_speed < 5.0f) {
11798                                 //      Leader very slow.  If not close to goal point, get very close.  Note, keep trying to get close unless
11799                                 //      moving very slowly, else momentum can carry far away from goal.
11800
11801                                 if ((dist_to_goal > 10.0f) || ((Pl_objp->phys_info.speed > leader_speed + 2.5f) && (dot_to_goal > 0.5f))) {
11802                                         //nprintf(("MK", "(1) "));
11803                                         turn_towards_point(Pl_objp, &goal_point, NULL, 0.0f);
11804                                         set_accel_for_target_speed(Pl_objp, leader_speed + dist_to_goal/10.0f);
11805                                 } else {
11806                                         if (Pl_objp->phys_info.speed < 0.5f) {
11807                                                 //nprintf(("MK", "(2) "));
11808                                                 turn_towards_point(Pl_objp, &future_goal_point_1000x, NULL, 0.0f);
11809                                         } else {
11810                                                 //nprintf(("MK", "(3) "));
11811                                         }
11812                                         set_accel_for_target_speed(Pl_objp, leader_speed);
11813                                 }
11814                                 //nprintf(("MK", "dist: %7.3f, dot: %6.3f, speed: %7.3f\n", dist_to_goal, dot_to_goal, Pl_objp->phys_info.speed));
11815                         } else if (dist_to_goal > 10.0f) {
11816                                 float   dv;
11817
11818                                 //future_goal_point_2;
11819
11820                                 turn_towards_point(Pl_objp, &future_goal_point_2, NULL, 0.0f);
11821
11822                                 if (dist_to_goal > 25.0f) {
11823                                         if (dot_to_goal < 0.3f)
11824                                                 dv = -0.1f;
11825                                         else
11826                                                 dv = dot_to_goal - 0.2f;
11827
11828                                         set_accel_for_target_speed(Pl_objp, leader_speed + dist_to_goal/5.0f * dv);
11829                                 } else {
11830                                         set_accel_for_target_speed(Pl_objp, leader_speed + 1.5f * dot_to_goal - 1.0f);
11831                                 }
11832                         } else {
11833                                 if (Pl_objp->phys_info.speed < 0.1f)
11834                                         turn_towards_point(Pl_objp, &future_goal_point_1000x, NULL, 0.0f);
11835                                 else
11836                                         turn_towards_point(Pl_objp, &future_goal_point_x, NULL, 0.0f);
11837                                 set_accel_for_target_speed(Pl_objp, 0.0f);
11838                         }
11839                 }
11840
11841         }
11842
11843         //      See how different this ship's bank is relative to wing leader
11844         float   up_dot = vm_vec_dot(&leader_objp->orient.v.uvec, &Pl_objp->orient.v.uvec);
11845         if (up_dot < 0.996f) {
11846                 vector  w_out;
11847                 matrix  new_orient;
11848                 vector  angular_accel;
11849
11850                 vm_vec_copy_scale(&angular_accel, &Pl_objp->phys_info.max_rotvel, 0.2f);
11851                 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);
11852
11853         //      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)));
11854                 Pl_objp->orient = new_orient;
11855                 Pl_objp->phys_info.rotvel = w_out;
11856         //      Pl_objp->phys_info.desired_rotvel = w_out;
11857         } else {
11858                 Pl_objp->phys_info.rotvel.xyz.z = 0.0f;
11859         }
11860
11861         return 0;
11862 }
11863
11864 //      Return index of object repairing object objnum.
11865 int find_repairing_objnum(int objnum)
11866 {
11867         object          *objp;
11868         ship                    *shipp;
11869         ship_info       *sip;
11870         ship_obj                *so;
11871
11872         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
11873                 objp = &Objects[so->objnum];
11874
11875                 SDL_assert((objp->instance >= 0) && (objp->instance < MAX_SHIPS));
11876
11877                 shipp = &Ships[objp->instance];
11878                 sip = &Ship_info[shipp->ship_info_index];
11879
11880                 if (sip->flags & SIF_SUPPORT) {
11881                         ai_info *aip;
11882
11883                         aip = &Ai_info[shipp->ai_index];
11884
11885                         if (aip->goal_objnum == objnum) {
11886                                 return objp-Objects;
11887                         }
11888                 }
11889         }
11890
11891         return -1;
11892 }
11893
11894 //      If object *objp is being repaired, deal with it!
11895 void ai_do_repair_frame(object *objp, ai_info *aip, float frametime)
11896 {
11897         if (Ships[objp->instance].team == TEAM_TRAITOR) {
11898                 ai_abort_rearm_request(objp);
11899                 return;
11900         }
11901
11902         if (aip->ai_flags & (AIF_BEING_REPAIRED | AIF_AWAITING_REPAIR)) {
11903                 int     dock_objnum;
11904                 ai_info *repair_aip;
11905
11906                 dock_objnum = aip->dock_objnum; // find_repairing_objnum(objp-Objects);
11907                 //SDL_assert(dock_objnum != -1);
11908                 if (dock_objnum == -1)
11909                         return;
11910                 if (Objects[dock_objnum].signature != aip->dock_signature) {
11911                         Int3();         //      Curious -- object numbers match, but signatures do not.
11912                                                         //      Must mean original repair ship died and was replaced by current ship.
11913                         return;
11914                 }
11915         
11916                 repair_aip = &Ai_info[Ships[Objects[dock_objnum].instance].ai_index];
11917                 //SDL_assert(repair_aip->mode == AIM_DOCK);
11918
11919                 if (aip->ai_flags & AIF_BEING_REPAIRED) {
11920                         // SDL_assert(repair_aip->submode == AIS_DOCK_4);
11921
11922                         //      Wait awhile into the mode to synchronize with sound effect.
11923                         if (Missiontime - repair_aip->submode_start_time > REARM_SOUND_DELAY) {
11924                                 int repaired;
11925
11926                                 repaired = ship_do_rearm_frame( objp, frametime );              // hook to do missile rearming
11927
11928                                 //      See if fully repaired.  If so, cause process to stop.
11929                                 if ( repaired && (repair_aip->submode == AIS_DOCK_4)) {
11930
11931                                         repair_aip->submode = AIS_UNDOCK_0;
11932                                         repair_aip->submode_start_time = Missiontime;
11933
11934                                         // if repairing player object -- tell him done with repair
11935                                         if ( !MULTIPLAYER_CLIENT ){
11936                                                 ai_do_objects_repairing_stuff( objp, &Objects[dock_objnum], REPAIR_INFO_COMPLETE );
11937                                         }
11938                                 }
11939                         }
11940                 } else if (aip->ai_flags & AIF_AWAITING_REPAIR) {
11941                         //      If this ship has been awaiting repair for 90+ seconds, abort.
11942                         if ( !MULTIPLAYER_CLIENT ) {
11943                                 if ((Game_mode & GM_MULTIPLAYER) || (objp != Player_obj)) {
11944                                         if ((repair_aip->goal_objnum == OBJ_INDEX(objp)) && (timestamp_elapsed(aip->abort_rearm_timestamp))) {
11945                                                 ai_abort_rearm_request(objp);
11946                                                 aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP);
11947                                         }
11948                                 }
11949                         }
11950                 }
11951         } else {
11952                 // AL 11-24-97: If this is the player ship, ensure the repair sound isn't playing.  We need to
11953                 //              do this check, since this is a looping sound, and may continue on if rearm/repair
11954                 //              finishes abnormally once sound begins looping.
11955                 if ( objp == Player_obj ) {
11956                         player_stop_repair_sound();
11957                 }
11958         }
11959 }
11960
11961 //      Shell around dock_orient_and_approach to detect whether dock process should be aborted.
11962 //      obj1 is the ship performing the repair.
11963 //      obj2 is the ship being repaired.
11964 void call_doa(object *obj1, object *obj2, ship_info *sip1)
11965 {
11966         if (sip1->flags & SIF_SUPPORT) {
11967                 if (obj2->phys_info.speed > MAX_REPAIR_SPEED) {
11968
11969                         // call the ai_abort rearm request code
11970                         ai_abort_rearm_request( obj2 );
11971                 } else
11972                         dock_orient_and_approach(obj1, obj2, DOA_DOCK_STAY);
11973         } else {
11974                 if (Ship_info[Ships[obj1->instance].ship_info_index].flags & SIF_CARGO)
11975                         dock_orient_and_approach(obj1, obj2, DOA_DOCK_STAY);
11976                 else if (Ship_info[Ships[obj2->instance].ship_info_index].flags & SIF_CARGO)
11977                         dock_orient_and_approach(obj2, obj1, DOA_DOCK_STAY);
11978                 else {
11979                         //mprintf(("Warning: Not sure, but making %s [%s] move to stay docked with %s [%s]\n",
11980                         //      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));
11981                         dock_orient_and_approach(obj1, obj2, DOA_DOCK_STAY);
11982
11983                 }
11984         }
11985
11986 }
11987
11988 //      Maybe launch a countermeasure.
11989 //      Also, detect a supposed homing missile that no longer exists.
11990 void ai_maybe_launch_cmeasure(object *objp, ai_info *aip)
11991 {
11992         float                   dist;
11993         ship_info       *sip;
11994         ship                    *shipp;
11995
11996         shipp = &Ships[objp->instance];
11997         sip = &Ship_info[shipp->ship_info_index];
11998
11999         if (!(sip->flags & (SIF_SMALL_SHIP | SIF_TRANSPORT)))
12000                 return;
12001
12002         if (!shipp->cmeasure_count)
12003                 return;
12004
12005         if ( !timestamp_elapsed(shipp->cmeasure_fire_stamp) )
12006                 return;
12007
12008         //      If not on player's team and Skill_level + ai_class is low, never fire a countermeasure.  The ship is too dumb.
12009         if (shipp->team != Player_ship->team) {
12010                 if (Game_skill_level + aip->ai_class < 4){
12011                         return;
12012                 }
12013         }
12014
12015         if ((aip->nearest_locked_object != -1) && (Objects[aip->nearest_locked_object].type == OBJ_WEAPON)) {
12016                 object  *weapon_objp;
12017
12018                 weapon_objp = &Objects[aip->nearest_locked_object];
12019
12020                 if ((dist = vm_vec_dist_quick(&objp->pos, &weapon_objp->pos)) < weapon_objp->phys_info.speed*2.0f) {
12021         
12022                         aip->nearest_locked_distance = dist;
12023                         //      Verify that this object is really homing on us.
12024                         object  *weapon_objp;
12025
12026                         weapon_objp = &Objects[aip->nearest_locked_object];
12027
12028                         float   fire_chance;
12029
12030                         //      For ships on player's team, have constant, average chance to fire.
12031                         //      For enemies, increasing chance with higher skill level.
12032                         if (shipp->team == Player_ship->team)
12033                                 fire_chance = Cmeasure_fire_chance[NUM_SKILL_LEVELS/2];
12034                         else
12035                                 fire_chance = Cmeasure_fire_chance[Game_skill_level];
12036
12037                         //      Decrease chance to fire at lower ai class.
12038                         fire_chance *= (float) aip->ai_class/Num_ai_classes;
12039
12040                         float r = frand();
12041                         if (fire_chance < r) {
12042                                 //nprintf(("AI", "Not firing countermeasure due to skill level: %7.3f < %7.3f\n", fire_chance, r));
12043                                 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.
12044                                 return;
12045                         }
12046
12047                         if (weapon_objp->type == OBJ_WEAPON) {
12048                                 if (weapon_objp->instance >= 0) {
12049                                         //nprintf(("AI", "Firing countermeasure at time t=%7.3f\n", f2fl(Missiontime)));
12050                                         ship_launch_countermeasure(objp);
12051                                         shipp->cmeasure_fire_stamp = timestamp(2*CMEASURE_WAIT);
12052                                         return;
12053                                 }
12054                         }
12055         
12056                 }
12057         }
12058
12059         return;
12060 }
12061
12062 //      --------------------------------------------------------------------------
12063 void ai_preprocess_ignore_objnum(object *objp, ai_info *aip)
12064 {
12065 //      if (aip->ignore_objnum == UNUSED_OBJNUM)
12066 //              return;
12067
12068         if (aip->ai_flags & AIF_TEMPORARY_IGNORE) {
12069                 if (timestamp_elapsed(aip->ignore_expire_timestamp)) {
12070                         aip->ignore_objnum = UNUSED_OBJNUM;
12071                 }
12072         }
12073
12074         if (is_ignore_object(aip, aip->goal_objnum)) {
12075                 aip->goal_objnum = -1;
12076                 // AL 12-11-97: If in STRAFE mode, we need to ensure that target_objnum is also
12077                 //              set to -1
12078                 if ( aip->mode == AIM_STRAFE ) {
12079                         aip->target_objnum = -1;
12080                 }
12081         }
12082
12083         if (is_ignore_object(aip, aip->target_objnum))
12084                 aip->target_objnum = -1;
12085 }
12086
12087 /*
12088 void ai_safety_circle_spot()
12089 {
12090         vector  goal_point;
12091         ship_info       *sip;
12092
12093         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
12094
12095         goal_point = Ai_info[Ships[Pl_objp->instance].ai_index].goal_point;
12096         turn_towards_tangent(Pl_objp, &goal_point, 50.0f);
12097
12098         set_accel_for_target_speed(Pl_objp, sip->max_speed/4.0f);
12099
12100 //      float dist = vm_vec_dist_quick(&goal_point, &Pl_objp->pos);
12101 //      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));
12102
12103 }
12104 */
12105
12106 #define CHASE_CIRCLE_DIST               100.0f
12107
12108 void ai_chase_circle(object *objp)
12109 {
12110         float           dist_to_goal;
12111         float           target_speed;
12112         vector  goal_point;
12113         ship_info       *sip;
12114         ai_info         *aip;
12115
12116         sip = &Ship_info[Ships[Pl_objp->instance].ship_info_index];
12117
12118         target_speed = sip->max_speed/4.0f;
12119         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
12120
12121         SDL_assert(vm_vec_mag(&aip->goal_point) >= 0.0f);               //      Supposedly detects bogus vector
12122
12123         goal_point = aip->goal_point;
12124
12125         if (aip->ignore_objnum == UNUSED_OBJNUM) {
12126                 dist_to_goal = vm_vec_dist_quick(&aip->goal_point, &objp->pos);
12127
12128                 if (dist_to_goal > 2*CHASE_CIRCLE_DIST) {
12129                         vector  vec_to_goal;
12130                         //      Too far from circle goal, create a new goal point.
12131                         vm_vec_normalized_dir(&vec_to_goal, &aip->goal_point, &objp->pos);
12132                         vm_vec_scale_add(&aip->goal_point, &objp->pos, &vec_to_goal, CHASE_CIRCLE_DIST);
12133                 }
12134
12135                 goal_point = aip->goal_point;
12136         } else if (is_ignore_object(aip, aip->ignore_objnum)) {
12137                 object  *ignore_objp = &Objects[aip->ignore_objnum];
12138
12139                 vector  tvec1;
12140                 float           dist;
12141
12142                 dist = vm_vec_normalized_dir(&tvec1, &Pl_objp->pos, &ignore_objp->pos);
12143
12144                 if (dist < ignore_objp->radius*2 + 1500.0f) {
12145                         vm_vec_scale_add(&goal_point, &Pl_objp->pos, &tvec1, ignore_objp->radius*2 + 1400.0f);
12146                         if (dist < ignore_objp->radius*2 + 1300.0f)
12147                                 target_speed = sip->max_speed * (1.25f - dist/(ignore_objp->radius*2 + 1500.0f));
12148                 }
12149         }
12150
12151         SDL_assert(vm_vec_mag(&aip->goal_point) >= 0.0f);               //      Supposedly detects bogus vector
12152
12153         turn_towards_tangent(Pl_objp, &goal_point, 10*objp->radius + 200.0f);
12154
12155         set_accel_for_target_speed(Pl_objp, target_speed);
12156
12157 }
12158
12159 #define SHIELD_BALANCE_RATE     0.2f            //      0.1f -> takes 10 seconds to equalize shield.
12160
12161 //      Transfer shield energy to most recently hit section from others.
12162 void ai_transfer_shield(object *objp, int quadrant_num)
12163 {
12164         int     i;
12165         float   transfer_amount;
12166         float   transfer_delta;
12167         ship_info       *sip;
12168         float   max_quadrant_strength;
12169
12170         sip = &Ship_info[Ships[objp->instance].ship_info_index];
12171         max_quadrant_strength = sip->shields/MAX_SHIELD_SECTIONS;
12172
12173         transfer_amount = 0.0f;
12174         transfer_delta = (SHIELD_BALANCE_RATE/2) * max_quadrant_strength;
12175
12176         if (objp->shields[quadrant_num] + (MAX_SHIELD_SECTIONS-1)*transfer_delta > max_quadrant_strength)
12177                 transfer_delta = (max_quadrant_strength - objp->shields[quadrant_num])/(MAX_SHIELD_SECTIONS-1);
12178
12179         for (i=0; i<MAX_SHIELD_SECTIONS; i++)
12180                 if (i != quadrant_num) {
12181                         if (objp->shields[i] >= transfer_delta) {
12182                                 objp->shields[i] -= transfer_delta;
12183                                 transfer_amount += transfer_delta;
12184                         } else {
12185                                 transfer_amount += objp->shields[i];
12186                                 objp->shields[i] = 0.0f;
12187                         }
12188                 }
12189
12190         objp->shields[quadrant_num] += transfer_amount;
12191 }
12192
12193 void ai_balance_shield(object *objp)
12194 {
12195         int     i;
12196         float   shield_strength_avg;
12197         float   delta;
12198
12199
12200         shield_strength_avg = get_shield_strength(objp)/MAX_SHIELD_SECTIONS;
12201
12202         delta = SHIELD_BALANCE_RATE * shield_strength_avg;
12203
12204         for (i=0; i<MAX_SHIELD_SECTIONS; i++)
12205                 if (objp->shields[i] < shield_strength_avg) {
12206                         add_shield_strength(objp, delta);
12207                         if (objp->shields[i] > shield_strength_avg)
12208                                 objp->shields[i] = shield_strength_avg;
12209                 } else {
12210                         add_shield_strength(objp, -delta);
12211                         if (objp->shields[i] < shield_strength_avg)
12212                                 objp->shields[i] = shield_strength_avg;
12213                 }
12214 }
12215
12216 //      Manage the shield for this ship.
12217 //      Try to max out the side that was most recently hit.
12218 void ai_manage_shield(object *objp, ai_info *aip)
12219 {
12220         ship_info *sip;
12221
12222         sip = &Ship_info[Ships[objp->instance].ship_info_index];
12223
12224         if (timestamp_elapsed(aip->shield_manage_timestamp)) {
12225                 float           delay;
12226
12227                 //      Scale time until next manage shield based on Skill_level.
12228                 //      Ships on player's team are treated as if Skill_level is average.
12229                 if (Ships[objp->instance].team != Player_ship->team){
12230                         delay = Shield_manage_delays[Game_skill_level];
12231                 } else {
12232                         delay = Shield_manage_delays[NUM_SKILL_LEVELS/2];
12233                 }
12234
12235                 //      Scale between 1x and 3x based on ai_class
12236                 delay = delay + delay * (float) (3*(Num_ai_classes - aip->ai_class - 1) / (Num_ai_classes - 1));
12237                 aip->shield_manage_timestamp = timestamp((int) (delay * 1000.0f));
12238
12239                 if (sip->flags & SIF_SMALL_SHIP) {
12240                         if (Missiontime - aip->last_hit_time < F1_0*10)
12241                                 ai_transfer_shield(objp, aip->last_hit_quadrant);
12242                         else
12243                                 ai_balance_shield(objp);
12244                 }
12245
12246                 // 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]));
12247         }
12248 }
12249
12250 //      See if object *objp should evade an incoming missile.
12251 //      *aip is the ai_info pointer within *objp.
12252 void ai_maybe_evade_locked_missile(object *objp, ai_info *aip)
12253 {
12254         ship                    *shipp;
12255
12256         shipp = &Ships[objp->instance];
12257
12258         //      Only small ships evade an incoming missile.  Why would a capital ship try to swerve?
12259         if (!(Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
12260                 return;
12261         }
12262
12263         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
12264                 return;
12265         }
12266
12267         if (aip->nearest_locked_object != -1) {
12268                 object  *missile_objp;
12269
12270                 missile_objp = &Objects[aip->nearest_locked_object];
12271
12272                 if (Weapons[missile_objp->instance].homing_object != objp) {
12273                         //nprintf(("AI", "\nMissile lost home!"));
12274                         aip->nearest_locked_object = -1;
12275                         return;
12276                 }
12277
12278                 if ((missile_objp->type == OBJ_WEAPON) && (Weapon_info[Weapons[missile_objp->instance].weapon_info_index].wi_flags & WIF_HOMING)) {
12279                         float dist = vm_vec_dist_quick(&missile_objp->pos, &objp->pos);
12280                         float dist2 = 4.0f  * vm_vec_mag_quick(&missile_objp->phys_info.vel);                   
12281                         if (dist < dist2) {
12282                                 switch (aip->mode) {
12283                                 //      If in AIM_STRAFE mode, don't evade if parent of weapon is targeted ship.
12284                                 case AIM_STRAFE:
12285                                         if ((missile_objp->parent != -1) && (missile_objp->parent == aip->target_objnum)) {
12286                                                 ;
12287                                         } else {
12288                                                 ;               //      Alan -- If you want to handle incoming weapons from someone other than the ship
12289                                                                 //      the strafing ship is attacking, do it here.
12290                                         }
12291                                         break;
12292                                 case AIM_CHASE:
12293                                         //      Don't always go into evade weapon mode.  Usually, a countermeasure gets launched.
12294                                         // If low on countermeasures, more likely to try to evade.  If 8+, never evade due to low cmeasures.
12295                                         if (((((Missiontime >> 18) ^ OBJ_INDEX(objp)) & 3) == 0) || 
12296                                                 (objp->phys_info.speed < 40.0f) ||
12297                                                 (frand() < 1.0f - (float) shipp->cmeasure_count/8.0f)) {
12298                                                 if (aip->submode != SM_ATTACK_FOREVER) {        //      SM_ATTACK_FOREVER means engines blown.
12299                                                         aip->submode = SM_EVADE_WEAPON;
12300                                                         aip->submode_start_time = Missiontime;
12301                                                 }
12302                                         }
12303                                         break;
12304                                 case AIM_DOCK:  //      Ships in dock mode can evade iif they are not currently repairing or docked.
12305                                         if (aip->ai_flags & (AIF_REPAIRING | AIF_DOCKED))
12306                                                 break;
12307                                 case AIM_GUARD:
12308                                         //      If in guard mode and far away from guard object, don't pursue guy that hit me.
12309                                         if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
12310                                                 if (vm_vec_dist_quick(&objp->pos, &Objects[aip->guard_objnum].pos) > 500.0f) {
12311                                                         return;
12312                                                 }
12313                                         }
12314                                 case AIM_EVADE:
12315                                 case AIM_GET_BEHIND:
12316                                 case AIM_STAY_NEAR:
12317                                 case AIM_STILL:
12318                                 case AIM_AVOID:
12319                                 case AIM_WAYPOINTS:
12320                                 case AIM_NONE:
12321                                 case AIM_BIGSHIP:
12322                                 case AIM_PATH:
12323                                 case AIM_BE_REARMED:
12324                                 case AIM_SAFETY:
12325                                 case AIM_BAY_EMERGE:
12326                                         aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
12327                                         aip->previous_mode = aip->mode;
12328                                         aip->previous_submode = aip->submode;
12329                                         aip->mode = AIM_EVADE_WEAPON;
12330                                         aip->submode = -1;
12331                                         aip->submode_start_time = Missiontime;
12332                                         aip->mode_time = timestamp(MAX_EVADE_TIME);     //      Max time to evade.
12333                                         //nprintf(("AI", "%s Evade weapon in frame #%i\n", Ships[objp->instance].ship_name, AI_FrameCount));
12334                                         break;
12335                                 case AIM_EVADE_WEAPON:          //      Note: We don't want to change mode on another evasion, or previous_mode will get bashed.
12336                                 case AIM_PLAY_DEAD:
12337                                 case AIM_BAY_DEPART:
12338                                 case AIM_SENTRYGUN:
12339                                         break;
12340                                 case AIM_WARP_OUT:
12341                                         break;
12342                                 default:
12343                                         Int3();                 //      Hey, what mode is it?
12344                                         break;
12345                                 }
12346                         }
12347                 } else {
12348                         aip->nearest_locked_object = -1;
12349                 }
12350         }
12351 }
12352
12353 //      Maybe evade a dumbfire weapon that was fired when Pl_objp was targeted.
12354 //      Have an 80% chance of evading in a second
12355 void maybe_evade_dumbfire_weapon(ai_info *aip)
12356 {
12357         //      Only small ships evade an incoming missile.  Why would a capital ship try to swerve?
12358         if (!(Ship_info[Ships[Pl_objp->instance].ship_info_index].flags & SIF_SMALL_SHIP)) {
12359                 return;
12360         }
12361
12362         //      Make sure in a mode in which we evade dumbfire weapons.
12363         switch (aip->mode) {
12364         case AIM_CHASE:
12365                 if (aip->submode == SM_ATTACK_FOREVER) {
12366                         return;
12367                 }
12368         case AIM_GUARD:
12369                 //      If in guard mode and far away from guard object, don't pursue guy that hit me.
12370                 if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
12371                         if (vm_vec_dist_quick(&Objects[Ships[aip->shipnum].objnum].pos, &Objects[aip->guard_objnum].pos) > 500.0f) {
12372                                 return;
12373                         }
12374                 }
12375         case AIM_STILL:
12376         case AIM_STAY_NEAR:
12377         case AIM_EVADE:
12378         case AIM_GET_BEHIND:
12379         case AIM_AVOID:
12380         case AIM_PATH:
12381         case AIM_NONE:
12382         case AIM_WAYPOINTS:
12383         case AIM_SAFETY:
12384                 break;
12385         case AIM_STRAFE:
12386         case AIM_BIGSHIP:
12387         case AIM_DOCK:
12388         case AIM_PLAY_DEAD:
12389         case AIM_EVADE_WEAPON:
12390         case AIM_BAY_EMERGE:
12391         case AIM_BAY_DEPART:
12392         case AIM_SENTRYGUN:
12393         case AIM_WARP_OUT:
12394                 return;
12395         default:
12396                 Int3(); //      Bogus mode!
12397                 return;
12398         }
12399
12400         if (is_instructor(&Objects[Ships[aip->shipnum].objnum]))
12401                 return; //      Instructor doesn't evade.
12402
12403         float t = ai_endangered_by_weapon(aip);
12404         if ((t > 0.0f) && (t < 1.0f)) {
12405         // Check if this weapon is from a large ship Pl_objp is attacking... if so, enter strafe mode
12406                 if ( ai_big_maybe_enter_strafe_mode(Pl_objp, aip->danger_weapon_objnum) ) {
12407                         return;
12408                 }
12409
12410                 switch (aip->mode) {
12411                 case AIM_CHASE:
12412                         switch (aip->submode) {
12413                         case SM_EVADE:
12414                         case SM_ATTACK_FOREVER:
12415                         case SM_AVOID:
12416                         case SM_GET_AWAY:
12417                         case SM_EVADE_WEAPON:
12418                                 break;
12419                         default:
12420                                 if (ai_near_full_strength(Pl_objp, &Ship_info[Ships[Pl_objp->instance].ship_info_index])) {
12421                                         //mprintf(("Ship %s entered super mode at %7.3f\n", Ships[Pl_objp->instance].ship_name, 1.0f * Missiontime / (1<<16)));
12422                                         aip->submode = SM_SUPER_ATTACK;
12423                                         aip->submode_start_time = Missiontime;
12424                                         aip->last_attack_time = Missiontime;
12425                                 } else {
12426                                         //mprintf(("Ship %s entered dumbfire evade mode at %7.3f\n", Ships[Pl_objp->instance].ship_name, 1.0f * Missiontime / (1<<16)));
12427                                         aip->submode = SM_EVADE_WEAPON;
12428                                         aip->submode_start_time = Missiontime;
12429                                 }
12430                                 break;
12431                         }
12432                         break;
12433                 case AIM_GUARD:
12434                 case AIM_STILL:
12435                 case AIM_STAY_NEAR:
12436                 case AIM_EVADE:
12437                 case AIM_GET_BEHIND:
12438                 case AIM_AVOID:
12439                 case AIM_PATH:
12440                 case AIM_NONE:
12441                 case AIM_WAYPOINTS:
12442                 case AIM_SAFETY:
12443                         if (!(aip->ai_flags & (AIF_NO_DYNAMIC | AIF_KAMIKAZE)) && (Ship_info[Ships[aip->shipnum].ship_info_index].flags & SIF_SMALL_SHIP)) {
12444                                 aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
12445                                 aip->previous_mode = aip->mode;
12446                                 aip->previous_submode = aip->submode;
12447                                 aip->mode = AIM_EVADE_WEAPON;
12448                                 aip->submode = -1;
12449                                 aip->submode_start_time = Missiontime;
12450                                 aip->mode_time = timestamp(MAX_EVADE_TIME);     //      Evade for up to five seconds.
12451                         }
12452                         break;
12453                 case AIM_STRAFE:
12454                 case AIM_BIGSHIP:
12455                 case AIM_DOCK:
12456                 case AIM_PLAY_DEAD:
12457                 case AIM_EVADE_WEAPON:
12458                 case AIM_BAY_EMERGE:
12459                 case AIM_BAY_DEPART:
12460                 case AIM_SENTRYGUN:
12461                         break;
12462                 default:
12463                         Int3(); //      Bogus mode!
12464                 }
12465         }
12466 }
12467
12468 // determine what path to use when emerging from a fighter bay
12469 // input:       pl_objp =>      pointer to object for ship that is arriving
12470 //                              pos             =>      output parameter, it is the starting world pos for path choosen
12471 //                              v.fvec          =>      output parameter, this is the forward vector that ship has when arriving
12472 //
12473 // exit:                -1              =>      path could not be located
12474 //                               0              => success
12475 int ai_acquire_emerge_path(object *pl_objp, int parent_objnum, vector *pos, vector *fvec)
12476 {
12477         int                     path_index, sb_path_index;
12478         ship                    *parent_sp = NULL;
12479         polymodel       *pm;
12480         ai_info         *aip;
12481         ship_bay                *sb;
12482         pnode                   *pnp;
12483         vector          *next_point;
12484
12485         aip = &Ai_info[Ships[pl_objp->instance].ai_index];
12486
12487         if ( parent_objnum == -1 ) {
12488                 Int3();
12489                 return -1;
12490         }
12491
12492         parent_sp = &Ships[Objects[parent_objnum].instance];
12493
12494         SDL_assert(parent_sp != NULL);
12495         pm = model_get( parent_sp->modelnum );
12496         sb = pm->ship_bay;
12497
12498         if ( sb == NULL ) 
12499                 return -1;
12500
12501         if ( sb->num_paths <= 0 ) 
12502                 return -1;
12503
12504         // try to find a bay path that is not taken
12505         path_index = -1;
12506         sb_path_index = Ai_last_arrive_path++;
12507
12508         if ( sb_path_index >= sb->num_paths ) {
12509                 sb_path_index=0;
12510                 Ai_last_arrive_path=0;
12511         }
12512
12513         path_index = sb->paths[sb_path_index];
12514         if ( path_index == -1 ) 
12515                 return -1;
12516
12517         // create the path for pl_objp to follow
12518         create_model_exit_path(pl_objp, &Objects[parent_objnum], path_index, pm->paths[path_index].nverts);
12519         
12520         // Set this flag, so we don't bother recreating the path... we won't need to update the path
12521         // that has just been created.
12522 //      aip->ai_flags |= AIF_USE_STATIC_PATH;
12523
12524         // now return to the caller what the starting world pos and starting fvec for the ship will be
12525         SDL_assert((aip->path_start >= 0) && (aip->path_start < MAX_PATH_POINTS));
12526         pnp = &Path_points[aip->path_start];
12527         *pos = pnp->pos;
12528
12529         // calc the forward vector using the starting two points of the path
12530         pnp = &Path_points[aip->path_start+1];
12531         next_point = &pnp->pos;
12532         vm_vec_normalized_dir(fvec, next_point, pos);
12533
12534         // record the parent objnum, since we'll need it once we're done with following the path
12535         aip->goal_objnum = parent_objnum;
12536         aip->goal_signature = Objects[parent_objnum].signature;
12537         aip->mode = AIM_BAY_EMERGE;
12538         aip->submode_start_time = Missiontime;
12539
12540         // set up starting vel
12541         vector vel;
12542         float speed;
12543         speed = Ship_info[Ships[pl_objp->instance].ship_info_index].max_speed;
12544         vel = *fvec;
12545         vm_vec_scale( &vel, speed );
12546         pl_objp->phys_info.vel = vel;
12547         pl_objp->phys_info.desired_vel = vel;
12548         pl_objp->phys_info.prev_ramp_vel.xyz.x = 0.0f;
12549         pl_objp->phys_info.prev_ramp_vel.xyz.y = 0.0f;
12550         pl_objp->phys_info.prev_ramp_vel.xyz.z = speed;
12551         pl_objp->phys_info.forward_thrust = 0.0f;               // How much the forward thruster is applied.  0-1.
12552
12553         return 0;       
12554 }
12555
12556 // clean up path data used for emerging from a fighter bay
12557 void ai_emerge_bay_path_cleanup(ai_info *aip)
12558 {
12559         aip->path_start = -1;
12560         aip->path_cur = -1;
12561         aip->path_length = 0;
12562         aip->mode = AIM_NONE;
12563 }
12564
12565 // handler for AIM_BAY_EMERGE
12566 void ai_bay_emerge()
12567 {
12568         ai_info *aip;
12569         int             parent_died=0;
12570
12571         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
12572
12573         // if no path to follow, leave this mode
12574         if ( aip->path_start < 0 ) {
12575                 aip->mode = AIM_NONE;
12576                 return;
12577         }
12578
12579         // ensure parent ship is still alive
12580         if ( aip->goal_objnum < 0 ) {
12581                 parent_died=1;
12582         } 
12583         if ( !parent_died ) {
12584                 if ( Objects[aip->goal_objnum].signature != aip->goal_signature ) {
12585                         parent_died=1;
12586                 }
12587         }
12588
12589         if ( !parent_died ) {
12590                 SDL_assert(Objects[aip->goal_objnum].type == OBJ_SHIP);
12591                 if ( Ships[Objects[aip->goal_objnum].instance].flags & SF_DYING ) {
12592                         parent_died = 1;
12593                 }
12594         }
12595
12596         if ( parent_died ) {
12597                 ai_emerge_bay_path_cleanup(aip);
12598                 return;
12599         }
12600
12601         // follow the path to the final point
12602         ai_path();
12603
12604         // New test: must have been in AI_EMERGE mode for at least 10 seconds, and be a minimum distance from the start point
12605         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)) {
12606                 // erase path
12607                 ai_emerge_bay_path_cleanup(aip);
12608         }
12609
12610         // 2-25-99: Need this check to fix an assert for supercap ships... maybe we'll only do this check for supercaps 
12611         if (aip->path_cur > (aip->path_start+aip->path_length-1)) {
12612                 ai_emerge_bay_path_cleanup(aip);
12613         }       
12614 }
12615
12616 // Select the closest depart path
12617 //
12618 //      input:  aip     =>              ai info pointer to ship seeking to depart
12619 //                              pm              =>              pointer to polymodel for the ship contining the ship bay/depart paths
12620 //
12621 // exit:                >=0     =>              ship bay path index for depart path (ie index into sb->paths[])
12622 //                              -1              =>              no path could be found
12623 //
12624 // NOTE: this function should only be used for calculating closest depart paths for ai mode
12625 //                      AI_BAY_DEPART.  It tries to find the closest path that isn't already in use
12626 int ai_find_closest_depart_path(ai_info *aip, polymodel *pm)
12627 {
12628         int                     i, j, best_path, best_free_path;
12629         float                   dist, min_dist, min_free_dist;
12630         vector          *source;
12631         model_path      *mp;
12632         ship_bay                *sb;
12633
12634         sb = pm->ship_bay;
12635
12636         best_free_path = best_path = -1;
12637         min_free_dist = min_dist = 1e20f;
12638         SDL_assert(aip->shipnum >= 0);
12639         source = &Objects[Ships[aip->shipnum].objnum].pos;
12640
12641         for ( i = 0; i < sb->num_paths; i++ ) {
12642
12643
12644                 mp = &pm->paths[sb->paths[i]];
12645                 for ( j = 0; j < mp->nverts; j++ ) {
12646                         dist = vm_vec_dist_squared(source, &mp->verts[j].pos);
12647
12648                         if ( dist < min_dist ) {
12649                                 min_dist = dist;
12650                                 best_path = i;
12651                         }
12652
12653                         // If this is a free path
12654                         if ( !(sb->depart_flags & (1<<i)) ) {
12655                                 if ( dist < min_free_dist ) {
12656                                         min_free_dist = dist;
12657                                         best_free_path = i;
12658                                 }
12659                         }
12660                 }
12661         }
12662
12663         if ( best_free_path >= 0 ) {
12664                 return best_free_path;          
12665         }
12666
12667         return best_path;
12668 }
12669
12670 // determine what path to use when trying to depart to a fighter bay
12671 // NOTE: this should be called when AIM_BAY_DEPART mode is set
12672 //
12673 // input:       pl_objp =>      pointer to object for ship that is departing
12674 //
12675 // exit:                -1      =>      could not find depart path
12676 //                              0       => found depart path
12677 int ai_acquire_depart_path(object *pl_objp, int parent_objnum)
12678 {
12679         int                     objnum, path_index;
12680         polymodel       *pm;
12681         ai_info         *aip;
12682         ship                    *sp;
12683         ship_bay                *sb;
12684
12685         aip = &Ai_info[Ships[pl_objp->instance].ai_index];
12686
12687         if ( parent_objnum == -1 ) {
12688                 ship_obj        *so;
12689
12690                 // for now just locate a captial ship on the same team:
12691                 so = GET_FIRST(&Ship_obj_list);
12692                 objnum = -1;
12693                 while(so != END_OF_LIST(&Ship_obj_list)){
12694                         sp = &Ships[Objects[so->objnum].instance];
12695                         if ( (Ship_info[sp->ship_info_index].flags & (SIF_HUGE_SHIP)) && (sp->team == Ships[pl_objp->instance].team) ) {
12696                                 objnum = so->objnum;
12697                                 break;
12698                         }
12699                         so = GET_NEXT(so);
12700                 } 
12701         } else {
12702                 objnum = parent_objnum;
12703         }
12704
12705         aip->path_start = -1;
12706
12707         if ( objnum == -1 )
12708                 return -1;
12709
12710         pm = model_get( Ships[Objects[objnum].instance].modelnum );
12711         sb = pm->ship_bay;
12712
12713         if ( sb == NULL ) 
12714                 return -1;
12715         if ( sb->num_paths <= 0 ) 
12716                 return -1;
12717
12718 /*
12719         
12720         path_index = -1;
12721         for ( i = 0; i < sb->num_paths; i++ ) {
12722                 if ( !(sb->depart_flags & (1<<i)) ) {
12723                         sb->depart_flags |= (1<<i);
12724                         path_index = sb->paths[i];
12725                         aip->submode_parm0 = i;                 // use mode-specific parameter to record ship bay path index
12726                         break;
12727                 }
12728         }
12729 */
12730         
12731         // take the closest path we can find
12732         int ship_bay_path;
12733         ship_bay_path = ai_find_closest_depart_path(aip, pm);
12734
12735         if (ship_bay_path == -1) {
12736                 return -1;
12737         }
12738
12739         path_index = sb->paths[ship_bay_path];
12740         aip->submode_parm0 = ship_bay_path;
12741         sb->depart_flags |= (1<<ship_bay_path);
12742
12743         if ( path_index == -1 ) {
12744                 return -1;
12745         }
12746
12747         SDL_assert(pm->n_paths > path_index);
12748         ai_find_path(pl_objp, objnum, path_index, 0);
12749
12750         // Set this flag, so we don't bother recreating the path... we won't need to update the path
12751         // that has just been created.
12752         aip->ai_flags &= ~AIF_USE_STATIC_PATH;
12753
12754         aip->goal_objnum = objnum;
12755         aip->goal_signature = Objects[objnum].signature;
12756         aip->mode = AIM_BAY_DEPART;
12757
12758         Ships[pl_objp->instance].flags |= SF_DEPART_DOCKBAY;
12759         return 0;
12760 }
12761
12762 // handler for AIM_BAY_DEPART
12763 void ai_bay_depart()
12764 {
12765         ai_info *aip;
12766
12767         aip = &Ai_info[Ships[Pl_objp->instance].ai_index];
12768
12769         // if no path to follow, leave this mode
12770         if ( aip->path_start < 0 ) {
12771                 aip->mode = AIM_NONE;
12772                 return;
12773         }
12774
12775         // check if parent ship still exists, if not abort depart 
12776         if ( aip->goal_signature != Objects[aip->goal_objnum].signature ) {
12777                 aip->mode = AIM_NONE;
12778                 return;
12779         }
12780
12781         // follow the path to the final point
12782         ai_path();
12783
12784         // if the final point is reached, let default AI take over
12785         if ( aip->path_cur >= (aip->path_start+aip->path_length) ) {
12786                 polymodel       *pm;
12787                 ship_bay                *sb;
12788
12789                 pm = model_get( Ships[Objects[aip->goal_objnum].instance].modelnum );
12790                 sb = pm->ship_bay;
12791                 if ( sb != NULL ) {
12792                         sb->depart_flags &= ~(1<<aip->submode_parm0);
12793                 }
12794
12795                 // make ship disappear
12796                 Pl_objp->flags |= OF_SHOULD_BE_DEAD;
12797                 ship_departed( Pl_objp->instance );
12798
12799                 // clean up path stuff
12800                 aip->path_start = -1;
12801                 aip->path_cur = -1;
12802                 aip->path_length = 0;
12803                 aip->mode = AIM_NONE;
12804         }
12805 }
12806
12807 // Handler for AIM_SENTRYGUN.  This AI mode is for sentry guns only (ie floating turrets).
12808 void ai_sentrygun()
12809 {
12810         // Nothing to do here.  Turret firing is handled via process_subobjects().
12811         // If you want the sentry guns to do anything beyond firing their turrets at enemies, add it here!
12812 }
12813
12814 //      --------------------------------------------------------------------------
12815 //      Execute behavior given by aip->mode.
12816 void ai_execute_behavior(ai_info *aip)
12817 {
12818         switch (aip->mode) {
12819         case AIM_CHASE:
12820                 if (En_objp) {
12821                         ai_chase();
12822                 } else if (aip->submode == SM_EVADE_WEAPON) {
12823                         evade_weapon();
12824                         // maybe reset submode
12825                         if (aip->danger_weapon_objnum == -1) {
12826                                 aip->submode = SM_ATTACK;
12827                                 aip->submode_start_time = Missiontime;
12828                                 aip->last_attack_time = Missiontime;
12829                         }
12830                 } else {
12831                         //      Don't circle if this is the instructor.
12832                         ship    *shipp = &Ships[aip->shipnum];
12833                         ship_info       *sip = &Ship_info[shipp->ship_info_index];
12834
12835                         if (SDL_strncasecmp(shipp->ship_name, INSTRUCTOR_SHIP_NAME, strlen(INSTRUCTOR_SHIP_NAME))) {
12836                                 if (sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
12837                                         aip->mode = AIM_NONE;
12838                                 } else {
12839                                         ai_chase_circle(Pl_objp);
12840                                 }
12841                         }
12842                 }
12843                 break;
12844         case AIM_EVADE:
12845                 if (En_objp) {
12846                         ai_evade();
12847                 } else {
12848                         vector  tvec;
12849                         vm_vec_scale_add(&tvec, &Pl_objp->pos, &Pl_objp->orient.v.rvec, 100.0f);
12850                         turn_towards_point(Pl_objp, &tvec, NULL, 0.0f);
12851                         accelerate_ship(aip, 0.5f);
12852                 }
12853                 break;
12854         case AIM_STILL:
12855                 ai_still();
12856                 break;
12857         case AIM_STAY_NEAR:
12858                 ai_stay_near();
12859                 break;
12860         case AIM_GUARD:
12861                 ai_guard();
12862                 break;
12863         case AIM_WAYPOINTS:
12864                 ai_waypoints();
12865                 break;
12866         case AIM_DOCK:
12867                 ai_dock();
12868                 break;
12869         case AIM_NONE:
12870                 // ai_formation();
12871                 break;
12872         case AIM_BIGSHIP:
12873                 ai_big_ship(Pl_objp);
12874                 break;
12875         case AIM_PATH: {
12876                 int path_num;
12877                 path_num = ai_return_path_num_from_dockbay(&Objects[aip->goal_objnum], 0);
12878                 ai_find_path(Pl_objp, aip->goal_objnum, path_num, 0);
12879                 ai_path();
12880                 break;
12881         }
12882         case AIM_SAFETY:
12883                 ai_safety();
12884                 break;
12885         case AIM_EVADE_WEAPON:
12886                 evade_weapon();
12887                 break;
12888         case AIM_STRAFE:
12889                 if (En_objp) {
12890                         SDL_assert(En_objp->type == OBJ_SHIP);
12891                         ai_big_strafe();        // strafe a big ship
12892                 } else {
12893                         aip->mode = AIM_NONE;
12894                 }
12895                 break;
12896         case AIM_BAY_EMERGE:
12897                 ai_bay_emerge();
12898                 break;
12899         case AIM_BAY_DEPART:
12900                 ai_bay_depart();
12901                 break;
12902         case AIM_SENTRYGUN:
12903                 ai_sentrygun();
12904                 break;
12905         case AIM_WARP_OUT:
12906                 break;          //      Note, handled directly from ai_frame().
12907         default:
12908                 Int3();         //      This should never happen -- MK, 5/12/97 
12909                 break;
12910         }
12911
12912         if ( !(ship_get_SIF(aip->shipnum) & SIF_NOT_FLYABLE) ) {
12913                 maybe_evade_dumbfire_weapon(aip);
12914         }
12915 }
12916
12917 //      Auxiliary function for maybe_request_support.
12918 //      Return 1 if subsystem "type" is worthy of repair, else return 0.
12919 //      Since subsystems cannot be repaired if they are at 0 strength, don't return 1 if subsystem is dead.
12920 int mrs_subsystem(ship *shipp, int type)
12921 {
12922         float   t;
12923
12924         t = ship_get_subsystem_strength(shipp, type);
12925
12926         if (t > 0.0f) {
12927                 return (int) ((1.0f - t) * 3);
12928         } else {
12929                 return 3;
12930         }
12931 }
12932
12933 //      Return number of ships on *objp's team that are currently rearming.
12934 int num_allies_rearming(object *objp)
12935 {
12936         ship_obj        *so;
12937         int             team;
12938         int             count = 0;
12939
12940         team = Ships[objp->instance].team;
12941
12942         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
12943                 object  *A;
12944                 
12945                 SDL_assert (so->objnum != -1);
12946                 A = &Objects[so->objnum];
12947
12948                 if (Ships[A->instance].team == team) {
12949                         if (Ai_info[Ships[A->instance].ai_index].ai_flags & (AIF_REPAIRING | AIF_AWAITING_REPAIR)) {
12950                                 count++;
12951                         }
12952                 }
12953         }
12954
12955         return count;
12956 }
12957
12958
12959 //      Maybe ship *objp should request support (rearm/repair).
12960 //      If it does, return TRUE, else return FALSE.
12961 int maybe_request_support(object *objp)
12962 {
12963         ship_info       *sip;
12964         ship                    *shipp;
12965         ai_info         *aip;
12966         int                     desire;
12967
12968         SDL_assert(objp->type == OBJ_SHIP);
12969         shipp = &Ships[objp->instance];
12970         aip = &Ai_info[shipp->ai_index];
12971         sip = &Ship_info[shipp->ship_info_index];
12972
12973         if (!timestamp_elapsed(aip->next_rearm_request_timestamp))
12974                 return 0;
12975
12976         //      Only fighters and bombers request support.
12977         if (!(sip->flags & (SIF_FIGHTER | SIF_BOMBER)))
12978                 return 0;
12979
12980         //      A ship that is currently awaiting does not need support!
12981         if (aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED))
12982                 return 0;
12983
12984         if (!is_support_allowed(objp))
12985                 return 0;
12986
12987         //if (shipp->team != TEAM_FRIENDLY)
12988         //      return 0;
12989
12990         //      Compute a desire value.
12991         //      Desire of 0 means no reason to request support.
12992         //      1 is slight, 2 more, etc.  Maximum is around 20.  Anything larger than 3 is pretty strong.
12993         desire = 0;
12994
12995         //      Set desire based on hull strength.
12996         //      No: We no longer repair hull, so this would cause repeated repair requests.
12997         //desire += 6 - (int) ((objp->hull_strength/sip->initial_hull_strength) * 6.0f);
12998
12999         //      Set desire based on key subsystems.
13000         desire += 2*mrs_subsystem(shipp, SUBSYSTEM_ENGINE);     //      Note, disabled engine forces repair request, regardless of nearby enemies.
13001         desire += mrs_subsystem(shipp, SUBSYSTEM_COMMUNICATION);
13002         desire += mrs_subsystem(shipp, SUBSYSTEM_WEAPONS);
13003         desire += mrs_subsystem(shipp, SUBSYSTEM_SENSORS);
13004
13005         //      Set desire based on percentage of secondary weapons.
13006         ship_weapon *swp = &shipp->weapons;
13007
13008         for ( int i = 0; i < swp->num_secondary_banks; i++ ) {
13009                 if (swp->secondary_bank_start_ammo[i] > 0) {
13010 //                      float r = (float) swp->secondary_bank_ammo[i]*Weapon_info[swp->secondary_bank_weapons[i]].cargo_size/swp->secondary_bank_capacity[i];
13011                         float r = (float) swp->secondary_bank_ammo[i]/swp->secondary_bank_start_ammo[i];
13012                         desire += (int) ((1.0f - r) * 3.0f);
13013                 }
13014         }
13015
13016         //      If no reason to repair, don't bother to see if it's safe to repair.
13017         if (desire == 0){
13018                 return 0;
13019         }
13020
13021         //      Compute danger threshold.
13022         //      Balance this with desire and maybe request support.
13023         if (ai_good_time_to_rearm( objp )) {
13024                 ai_issue_rearm_request(objp);
13025                 return 1;
13026         } else if (num_allies_rearming(objp) < 2) {
13027                 if (desire >= 8) {      //      guarantees disabled will cause repair request
13028                         ai_issue_rearm_request(objp);
13029                 } else if (desire >= 3) {               //      >= 3 means having a single subsystem fully blown will cause repair.
13030                         int     count;
13031                         int objnum = find_nearby_hostile(OBJ_INDEX(objp), get_enemy_team_mask(OBJ_INDEX(objp)), 2000.0f, &count);
13032
13033                         if ((objnum == -1) || (count < 2) || (vm_vec_dist_quick(&objp->pos, &Objects[objnum].pos) > 3000.0f*count/desire)) {
13034                                 ai_issue_rearm_request(objp);
13035                                 return 1;
13036                         } else {
13037                                 //nprintf(("AI", "Would like to rearm, but enemy only %7.3f units away.\n", vm_vec_dist_quick(&objp->pos, &Objects[objnum].pos)));
13038                         }
13039                 }
13040         }
13041
13042         return 0;
13043
13044 }
13045
13046 void ai_set_mode_warp_out(object *objp, ai_info *aip)
13047 {
13048         ai_abort_rearm_request(objp);
13049         if (aip->mode != AIM_WARP_OUT) {
13050                 aip->mode = AIM_WARP_OUT;
13051                 aip->submode = AIS_WARP_1;
13052         }
13053 }
13054
13055 //      Maybe warp ship out.
13056 //      Shivan and HoL fighter/bomber warp out if their weapons subsystems have been destroyed.
13057 void ai_maybe_warp_out(object *objp)
13058 {
13059         ship    *shipp;
13060
13061         // don't do anything if in a training mission.
13062         if ( The_mission.game_type & MISSION_TYPE_TRAINING )
13063                 return;
13064
13065         SDL_assert(objp->type == OBJ_SHIP);
13066
13067         shipp = &Ships[objp->instance];
13068         ai_info *aip = &Ai_info[shipp->ai_index];
13069
13070         if (aip->mode == AIM_WARP_OUT)
13071                 return;
13072
13073         //      If a support ship with no goals and low hull, warp out.  Be sure that there are no pending goals
13074         // in the support ships ai_goal array.  Just process this ships goals.
13075         ship_info       *sip = &Ship_info[shipp->ship_info_index];
13076         if (sip->flags & SIF_SUPPORT) {
13077                 if ( timestamp_elapsed(aip->warp_out_timestamp) ) {
13078                         ai_process_mission_orders( OBJ_INDEX(objp), aip );
13079                         if ( (aip->dock_objnum == -1) && (objp->hull_strength/sip->initial_hull_strength < 0.25f) ) {
13080                                 ai_set_mode_warp_out(objp, aip);
13081                         }
13082                 }
13083         }
13084
13085         //      Friendly don't warp out, they'll eventually request support.
13086         if (shipp->team == TEAM_FRIENDLY)
13087                 return;
13088
13089         if (!(shipp->flags & SF_DEPARTING)) {
13090                 ship_info       *sip;
13091
13092                 sip = &Ship_info[shipp->ship_info_index];
13093                 if (sip->flags & (SIF_FIGHTER | SIF_BOMBER)) {
13094                         if (aip->warp_out_timestamp == 0) {
13095                                 //if (ship_get_subsystem_strength(shipp, SUBSYSTEM_WEAPONS) == 0.0f) {
13096                                 //      aip->warp_out_timestamp = timestamp(((myrand() % 10) + 10) * 1000);
13097                                 //}
13098                         } else if (timestamp_elapsed(aip->warp_out_timestamp)) {
13099                                 ai_set_mode_warp_out(objp, aip);
13100                         }
13101                 }
13102         }
13103 }
13104
13105 //      Warp this ship out.
13106 void ai_warp_out(object *objp)
13107 {
13108         // if dying, don't warp out.
13109         if (Ships[objp->instance].flags & SF_DYING) {
13110                 return;
13111         }
13112
13113         ai_info *aip;
13114
13115         aip = &Ai_info[Ships[objp->instance].ai_index];
13116
13117         switch (aip->submode) {
13118         case AIS_WARP_1:
13119                 aip->force_warp_time = timestamp(10*1000);      //      Try to avoid a collision for up to ten seconds.
13120                 aip->submode = AIS_WARP_2;
13121                 break;
13122         case AIS_WARP_2:                        //      Make sure won't collide with any object.
13123                 if (timestamp_elapsed(aip->force_warp_time) || !collide_predict_large_ship(objp, objp->radius*2.0f + 100.0f)) {
13124                         aip->submode = AIS_WARP_3;
13125
13126                         // maybe recalculate collision pairs.
13127                         if (ship_get_warp_speed(objp) > ship_get_max_speed(&Ships[objp->instance])) {
13128                                 // recalculate collision pairs
13129                                 OBJ_RECALC_PAIRS(objp); 
13130                         }
13131
13132                         aip->force_warp_time = timestamp(4*1000);               //      Try to attain target speed for up to 4 seconds.
13133                 } else {
13134                         vector  goal_point;
13135                         vm_vec_scale_add(&goal_point, &objp->pos, &objp->orient.v.uvec, 100.0f);
13136                         turn_towards_point(objp, &goal_point, NULL, 0.0f);
13137                         accelerate_ship(aip, 0.0f);
13138                 }
13139                 break;
13140         case AIS_WARP_3:
13141                 //      Rampup desired_vel in here from current to desired velocity and set PF_USE_VEL. (not sure this is the right flag)
13142                 //      desired velocity is computed in shipfx_calculate_warp_time().  See shipfx#572 for sample code.
13143                 float   speed, goal_speed;
13144                 float shipfx_calculate_warp_speed(object*);
13145                 goal_speed = shipfx_calculate_warp_speed(objp);
13146
13147                 // HUGE ships go immediately to AIS_WARP_4
13148                 if (Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_HUGE_SHIP) {
13149                         aip->submode = AIS_WARP_4;
13150                         break;
13151                 }
13152                 //compute_warpout_stuff(objp, &goal_speed, &warp_time, &warp_pos);
13153                 //goal_speed = 80.0f;
13154                 //set_accel_for_target_speed(objp, 40.0f);
13155                 // 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
13156                 speed = goal_speed * flFrametime + objp->phys_info.speed * (1.0f - flFrametime);
13157                 vm_vec_copy_scale(&objp->phys_info.vel, &objp->orient.v.fvec, speed);
13158                 objp->phys_info.desired_vel = objp->phys_info.vel;
13159                 // nprintf(("AI", "Frame %i, speed = %7.3f, goal = %7.3f\n", Framecount, vm_vec_mag_quick(&objp->phys_info.vel), goal_speed));
13160                 if (timestamp_elapsed(aip->force_warp_time) || (fl_abs(objp->phys_info.speed - goal_speed) < 2.0f))
13161                         aip->submode = AIS_WARP_4;
13162                 break;
13163         case AIS_WARP_4: {
13164                 shipfx_warpout_start(objp);
13165                 aip->submode = AIS_WARP_5;
13166                 break;
13167         }
13168         case AIS_WARP_5:
13169                 break;
13170         default:
13171                 Int3();         //      Illegal submode for warping out.
13172         }
13173 }
13174
13175 //      Return object index of weapon that could produce a shockwave that should be known about to *objp.
13176 //      Return nearest one.
13177 int ai_find_shockwave_weapon(object *objp, ai_info *aip)
13178 {
13179         missile_obj     *mo;
13180         float   nearest_dist = 999999.9f;
13181         int     nearest_index = -1;
13182
13183         for ( mo = GET_NEXT(&Missile_obj_list); mo != END_OF_LIST(&Missile_obj_list); mo = GET_NEXT(mo) ) {
13184                 object          *A;
13185                 weapon          *wp;
13186                 weapon_info     *wip;
13187         
13188                 SDL_assert(mo->objnum >= 0 && mo->objnum < MAX_OBJECTS);
13189                 A = &Objects[mo->objnum];
13190
13191                 SDL_assert(A->type == OBJ_WEAPON);
13192                 SDL_assert((A->instance >= 0) && (A->instance < MAX_WEAPONS));
13193                 wp = &Weapons[A->instance];
13194                 wip = &Weapon_info[wp->weapon_info_index];
13195                 SDL_assert( wip->subtype == WP_MISSILE );
13196
13197                 if (wip->shockwave_speed > 0.0f) {
13198                         float   dist;
13199
13200                         dist = vm_vec_dist_quick(&objp->pos, &A->pos);
13201                         if (dist < nearest_dist) {
13202                                 nearest_dist = dist;
13203                                 nearest_index = mo->objnum;
13204                         }
13205                 }
13206         }
13207
13208         return nearest_index;
13209
13210 }
13211
13212 #define EVADE_SHOCKWAVE_DAMAGE_THRESHOLD                100.0f
13213
13214 //      Tell all ships to avoid a big ship that is blowing up.
13215 //      Only avoid if shockwave is fairly large.
13216 //      OK to tell everyone to avoid.  If they're too far away, that gets cleaned up in the frame interval.
13217 void ai_announce_ship_dying(object *dying_objp)
13218 {
13219         float damage = ship_get_exp_damage(dying_objp);
13220         if (damage >= EVADE_SHOCKWAVE_DAMAGE_THRESHOLD) {
13221                 ship_obj        *so;
13222
13223                 for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
13224                         if (Ship_info[Ships[Objects[so->objnum].instance].ship_info_index].flags & (SIF_SMALL_SHIP | SIF_FREIGHTER)) {
13225                                 ai_info *aip;
13226
13227                                 aip = &Ai_info[Ships[Objects[so->objnum].instance].ai_index];
13228
13229                                 if ( !(aip->ai_flags & (AIF_DOCKED|AIF_BEING_REPAIRED)) ) {
13230                                         aip->ai_flags |= AIF_AVOID_SHOCKWAVE_SHIP;
13231                                 }
13232                         }
13233                 }
13234         }
13235 }
13236
13237
13238 //      Return object index of weapon that could produce a shockwave that should be known about to *objp.
13239 //      Return nearest one.
13240 int ai_find_shockwave_ship(object *objp, ai_info *aip)
13241 {
13242         ship_obj        *so;
13243         float   nearest_dist = 999999.9f;
13244         int     nearest_index = -1;
13245
13246         for ( so = GET_NEXT(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
13247                 object          *A;
13248                 ship                    *shipp;
13249         
13250                 SDL_assert(so->objnum >= 0 && so->objnum < MAX_OBJECTS);
13251                 A = &Objects[so->objnum];
13252
13253                 SDL_assert(A->type == OBJ_SHIP);
13254                 SDL_assert((A->instance >= 0) && (A->instance < MAX_SHIPS));
13255                 shipp = &Ships[A->instance];
13256                 //      Only look at objects in the process of dying.
13257                 if (shipp->flags & SF_DYING) {
13258                         float damage = ship_get_exp_damage(objp);
13259
13260                         if (damage >= EVADE_SHOCKWAVE_DAMAGE_THRESHOLD) {               //      Only evade quite large blasts
13261                                 float   dist;
13262
13263                                 dist = vm_vec_dist_quick(&objp->pos, &A->pos);
13264                                 if (dist < nearest_dist) {
13265                                         nearest_dist = dist;
13266                                         nearest_index = so->objnum;
13267                                 }
13268                         }
13269                 }
13270         }
13271
13272         return nearest_index;
13273
13274 }
13275
13276 int aas_1(object *objp, ai_info *aip, vector *safe_pos)
13277 {
13278         // MAKE SURE safe_pos DOES NOT TAKE US TOWARD THE A SHIP WE'RE ATTACKING.
13279         if (aip->ai_flags & AIF_AVOID_SHOCKWAVE_WEAPON) {
13280                 //      If we don't currently know of a weapon to avoid, try to find one.
13281                 //      If we can't find one, then clear the bit so we don't keep coming here.
13282                 if (aip->shockwave_object == -1) {
13283                         int shockwave_weapon = ai_find_shockwave_weapon(objp, aip);
13284                         if (shockwave_weapon == -1) {
13285                                 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13286                                 return 0;
13287                         } else {
13288                                 aip->shockwave_object = shockwave_weapon;
13289                         }
13290                 }
13291
13292                 //      OK, we have reason to believe we should avoid aip->shockwave_object.
13293                 SDL_assert(aip->shockwave_object > -1);
13294                 object  *weapon_objp = &Objects[aip->shockwave_object];
13295                 if (weapon_objp->type != OBJ_WEAPON) {
13296                         aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13297                         aip->shockwave_object = -1;
13298                         return 0;
13299                 }
13300
13301                 weapon  *weaponp = &Weapons[weapon_objp->instance];
13302                 weapon_info     *wip = &Weapon_info[weaponp->weapon_info_index];
13303                 object *target_ship_obj = NULL;
13304
13305                 if (wip->shockwave_speed == 0.0f) {
13306                         aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13307                         aip->shockwave_object = -1;
13308                         return 0;
13309                 }
13310
13311                 float   danger_dist;
13312                 vector  expected_pos;           //      Position at which we expect the weapon to detonate.
13313                 int             pos_set = 0;
13314
13315                 danger_dist = wip->outer_radius;
13316                 //      Set predicted position of detonation.
13317                 //      If an aspect locked missile, assume it will detonate at the homing position.
13318                 //      If not, which is not possible in a default FreeSpace weapon, then predict it will detonate at some
13319                 //      time in the future, this time based on max lifetime and life left.
13320                 if (wip->wi_flags & WIF_HOMING_ASPECT) {
13321                         expected_pos = weaponp->homing_pos;
13322                         if (weaponp->homing_object && weaponp->homing_object->type == OBJ_SHIP) {
13323                                 target_ship_obj = weaponp->homing_object;
13324                         }
13325                         pos_set = 1;
13326                         if (IS_VEC_NULL(&weaponp->homing_pos)) {
13327                                 pos_set = 0;
13328                                 if (weaponp->target_num != -1) {
13329                                         if (Objects[weaponp->target_num].type == OBJ_SHIP) {
13330                                                 target_ship_obj = &Objects[weaponp->target_num];
13331                                                 expected_pos = target_ship_obj->pos;
13332                                                 pos_set = 1;
13333                                         }
13334                                 }
13335                         }
13336                 }
13337
13338                 if (!pos_set) {
13339                         float   time_scale;
13340
13341                         if (wip->lifetime - weaponp->lifeleft > 5.0f) {
13342                                 time_scale = 1.0f;
13343                         } else {
13344                                 time_scale = weaponp->lifeleft/2.0f;
13345                         }
13346
13347                         vm_vec_scale_add(&expected_pos, &weapon_objp->pos, &weapon_objp->orient.v.fvec, time_scale);
13348                 }
13349
13350                 //      See if too far away to care about shockwave.
13351                 if (vm_vec_dist_quick(&objp->pos, &expected_pos) > danger_dist*2.0f) {
13352                         //aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13353                         return 0;
13354                 } else {
13355                         // try to find a safe position
13356                         vector vec_from_exp;
13357                         float dir = 1.0f;
13358                         vm_vec_sub(&vec_from_exp, &objp->pos, &expected_pos);
13359                         float dot = vm_vec_dotprod(&vec_from_exp, &weapon_objp->orient.v.fvec);
13360                         if (dot > -30) {
13361                                 // if we're already on the other side of the explosion, don't try to fly behind it
13362                                 dir = -1.0f;
13363                         }
13364
13365                         //      Fly towards a point behind the weapon.
13366                         vm_vec_scale_add(safe_pos, &weapon_objp->pos, &weapon_objp->orient.v.fvec, -50000.0f*dir);
13367
13368                         // verify safe_pos will not make us collide with our target objnum, else try 2 other vecs
13369                         // don't bang your head, else go
13370 //                      int go_safe = FALSE;
13371                         int go_safe = TRUE;
13372 /*                      if (target_ship_obj) {
13373                                 if (pp_collide(&objp->pos, safe_pos, target_ship_obj, objp->radius)) {
13374                                         // try up to 2 other random directions
13375                                         vector dir_vec, rand_vec;
13376                                         int idx;
13377                                         for (idx=0; idx<2; idx++) {
13378                                                 vm_vec_rand_vec_quick(&rand_vec);
13379                                                 vm_vec_scale_add(&dir_vec, &weapon_objp->orient.v.fvec, &rand_vec, 0.5f);
13380                                                 vm_vec_scale_add(safe_pos, &weapon_objp->pos, &dir_vec, -50000.0f*dir);
13381                                                 if ( !pp_collide(&objp->pos, safe_pos, target_ship_obj, objp->radius) ) {
13382                                                         go_safe = TRUE;
13383                                                         break;
13384                                                 }
13385                                         }
13386                                 } else { // direct path is safe
13387                                         go_safe = TRUE;
13388                                 }
13389                         } else { // no target_obj_ship
13390                                 go_safe = TRUE;
13391                         } */
13392
13393                         if (go_safe) {
13394                                 return 1;
13395                         } else {
13396                                 // can't figure out a good way to go
13397                                 return 0;
13398                         }
13399                 }
13400         } else if (aip->ai_flags & AIF_AVOID_SHOCKWAVE_SHIP) {
13401                 if (aip->shockwave_object == -1) {
13402                         int shockwave_ship = ai_find_shockwave_ship(objp, aip);
13403                         if (shockwave_ship == -1) {
13404                                 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_SHIP;
13405                                 return 0;
13406                         } else {
13407                                 aip->shockwave_object = shockwave_ship;
13408                         }
13409                 }
13410
13411                 SDL_assert(aip->shockwave_object > -1);
13412                 object  *ship_objp = &Objects[aip->shockwave_object];
13413                 if (ship_objp == objp) {
13414                         aip->shockwave_object = -1;
13415                         return 0;
13416                 }
13417
13418                 if (ship_objp->type != OBJ_SHIP) {
13419                         aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_SHIP;
13420                         return 0;
13421                 }
13422
13423                 //      Optimize note! Don't really have to normalize.  We only need a point away from the blowing-up ship.
13424                 vector safe_vec;
13425
13426                 vm_vec_normalized_dir(&safe_vec, &objp->pos, &ship_objp->pos);
13427                 vm_vec_scale_add(safe_pos, &ship_objp->pos, &safe_vec, 50000.0f);       //      Fly away from the ship.
13428
13429                 float outer_rad = ship_get_exp_outer_rad(ship_objp);
13430
13431                 if (vm_vec_dist_quick(&objp->pos, &ship_objp->pos) > outer_rad*1.5f) {
13432                         aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_WEAPON;
13433                         return 0;
13434                 }
13435
13436                 return 1;
13437
13438         } else {
13439                 Int3(); //      Illegal -- supposedly avoiding a shockwave, but neither ship nor weapon.  What is it!?
13440         }
13441
13442         return 0;
13443 }
13444
13445 /*
13446 int rct_done = 0;
13447
13448 void rand_chance_test()
13449 {
13450         int     i;
13451         float   frametime;
13452
13453         if (rct_done)
13454                 return;
13455
13456         rct_done = 1;
13457
13458         for (frametime=0.02f; frametime<0.25f; frametime *= 1.25f) {
13459                 float   chance;
13460
13461                 nprintf(("AI", "%6.4f: ", frametime));
13462                 for (chance=0.25f; chance<2.5f; chance += 0.25f) {
13463                         int count = 0;
13464
13465                         for (i=0; i<100.0f/frametime; i++) {
13466                                 if (rand_chance(frametime, chance))
13467                                         count++;
13468                         }
13469                         nprintf(("AI", "%3i ", count));
13470                 }
13471                 nprintf(("AI", "\n"));
13472         }
13473 }
13474 */
13475
13476 //      --------------------------------------------------------------------------
13477 //      Make object *objp avoid the nearest dangerous shockwave-producing weapon.
13478 //      If it looks like there is no valid shockwave-producing weapon then clear the AIF_AVOID_SHOCKWAVE_WEAPON bit in ai_flags and return.
13479 //      Return 1 if avoiding a shockwave, else return 0.
13480 int ai_avoid_shockwave(object *objp, ai_info *aip)
13481 {
13482         vector  safe_pos;
13483
13484         //rand_chance_test();
13485         // BIG|HUGE do not respond to shockwaves
13486         if (Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) {
13487                 // don't come here again
13488                 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE;
13489                 return 0;
13490         }
13491
13492         //      Don't all react right away.
13493         if (!(aip->ai_flags & AIF_AVOID_SHOCKWAVE_STARTED))
13494                 if (!rand_chance(flFrametime, (float) aip->ai_class/4.0f + 0.25f))      //      Chance to avoid in 1 second is 0.25 + ai_class/4
13495                         return 0;
13496
13497         if (!aas_1(objp, aip, &safe_pos)) {
13498                 aip->ai_flags |= AIF_AVOID_SHOCKWAVE_STARTED;
13499                 return 0;
13500         }
13501
13502         aip->ai_flags |= AIF_AVOID_SHOCKWAVE_STARTED;
13503
13504         //      OK, evade the shockwave!
13505         turn_towards_point(objp, &safe_pos, NULL, 0.0f);
13506         vector  vec_to_safe_pos;
13507         float           dot_to_goal;
13508
13509         vm_vec_normalized_dir(&vec_to_safe_pos, &safe_pos, &objp->pos);
13510
13511         dot_to_goal = vm_vec_dot(&objp->orient.v.fvec, &vec_to_safe_pos);
13512         if (dot_to_goal < -0.5f)
13513                 accelerate_ship(aip, 0.3f);
13514         else {
13515                 accelerate_ship(aip, 1.0f + dot_to_goal);
13516                 if (dot_to_goal > 0.2f) {
13517                         if (!(objp->phys_info.flags & PF_AFTERBURNER_ON )) {
13518                                 afterburners_start(objp);
13519                                 aip->afterburner_stop_time = Missiontime + 2*F1_0;
13520                         }
13521                 }
13522         }
13523
13524         return 1;
13525 }
13526
13527 //      Awaiting repair.  Be useful.
13528 //      Probably fly towards incoming repair ship.
13529 //      Return true if this ship is close to being repaired, else return false.
13530 int ai_await_repair_frame(object *objp, ai_info *aip)
13531 {
13532         if (!(aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED)))
13533                 return 0;
13534
13535         if (aip->dock_objnum == -1)
13536                 return 0;
13537
13538         ship    *shipp;
13539         ship_info       *sip;
13540
13541         shipp = &Ships[Objects[aip->dock_objnum].instance];
13542         sip = &Ship_info[shipp->ship_info_index];
13543
13544         aip->ai_flags &= ~AIF_FORMATION_OBJECT; //      Prevents endless rotation.
13545
13546         if (!(sip->flags & SIF_SUPPORT))
13547                 return 0;
13548
13549         vector  goal_point;
13550         object  *repair_objp;
13551
13552         repair_objp = &Objects[aip->dock_objnum];
13553
13554         if (Ships[repair_objp->instance].team == TEAM_TRAITOR) {
13555                 ai_abort_rearm_request(repair_objp);
13556                 return 0;
13557         }
13558
13559         vm_vec_scale_add(&goal_point, &repair_objp->pos, &repair_objp->orient.v.uvec, -50.0f);  //      Fly towards point below repair ship.
13560
13561         vector  vtr;
13562         float dist = vm_vec_normalized_dir(&vtr, &goal_point, &objp->pos);
13563         float dot = vm_vec_dot(&vtr, &objp->orient.v.fvec);
13564
13565         if (dist > 200.0f) {
13566                 //nprintf(("AI", "%s flying towards %s for repair, dist = %7.3f\n", Ships[objp->instance].ship_name, &Ships[repair_objp->instance].ship_name, dist));
13567                 accelerate_ship(aip, (0.9f + dot) * dist/1500.0f);
13568                 turn_towards_point(objp, &goal_point, NULL, 0.0f);
13569         } else {
13570                 accelerate_ship(aip, 0.0f);
13571                 //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));
13572         }
13573
13574         return 1;
13575 }
13576
13577 //      Maybe cause this ship to self-destruct.
13578 //      Currently, any small ship (SIF_SMALL_SHIP) that has been disabled will self-destruct after awhile.
13579 //      Maybe should only do this if they are preventing their wing from re-entering.
13580 void ai_maybe_self_destruct(object *objp, ai_info *aip)
13581 {
13582         //      Friendly ships can be repaired, so no self-destruct.
13583         //      In multiplayer, just don't self-destruct.  I figured there would be a problem. -- MK, 3/19/98.
13584         if ((Ships[objp->instance].team == TEAM_FRIENDLY) || (Game_mode & GM_MULTIPLAYER))
13585                 return;
13586
13587         //      Small ships in a wing blow themselves up after awhile if engine or weapons system has been destroyed.
13588         //      Reason: Don't want them to prevent a re-emergence of the wing.
13589         //      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
13590         //      mission would be broken.
13591         if ((Ship_info[Ships[objp->instance].ship_info_index].flags & SIF_SMALL_SHIP) && (Ships[objp->instance].wingnum != -1)) {
13592                 if ((ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_ENGINE) <= 0.0f) ||
13593                         (ship_get_subsystem_strength(&Ships[objp->instance], SUBSYSTEM_WEAPONS) <= 0.0f)) {
13594                         if (aip->self_destruct_timestamp < 0)
13595                                 aip->self_destruct_timestamp = timestamp(90 * 1000);    //      seconds until self-destruct
13596                 } else {
13597                         aip->self_destruct_timestamp = -1;
13598                 }
13599
13600                 if (aip->self_destruct_timestamp < 0) {
13601                         return;
13602                 }
13603
13604                 if (timestamp_elapsed(aip->self_destruct_timestamp)) {
13605                         ship_apply_local_damage( objp, objp, &objp->pos, objp->hull_strength*flFrametime + 1.0f, MISS_SHIELDS);
13606                 }
13607         }
13608 }
13609
13610 // Determine if pl_objp needs a new target, called from ai_frame()
13611 int ai_need_new_target(object *pl_objp, int target_objnum)
13612 {
13613         object *objp;
13614
13615         if ( target_objnum < 0 ) {
13616                 return 1;
13617         }
13618
13619         objp = &Objects[target_objnum];
13620
13621         if ( (objp->type != OBJ_SHIP) && (objp->type != OBJ_ASTEROID) && (objp->type != OBJ_WEAPON) ) {
13622                 return 1;
13623         }
13624
13625         if ( objp->type == OBJ_SHIP ) {
13626                 if ( Ships[objp->instance].flags & SF_DYING ) {
13627                         return 1;
13628                 } else if (Ships[objp->instance].team == Ships[pl_objp->instance].team)
13629                         return 1;
13630         }
13631
13632         return 0;
13633 }
13634
13635 //      If *objp is recovering from a collision with a big ship, handle it.
13636 //      Return true if recovering.
13637 int maybe_big_ship_collide_recover_frame(object *objp, ai_info *aip)
13638 {
13639         float   dot, dist;
13640         vector  v2g;
13641         
13642         if (aip->ai_flags & AIF_BIG_SHIP_COLLIDE_RECOVER_1) {
13643                 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);
13644                 dist = vm_vec_normalized_dir(&v2g, &aip->big_recover_pos_1, &objp->pos);
13645                 dot = vm_vec_dot(&objp->orient.v.fvec, &v2g);
13646                 accelerate_ship(aip, dot);
13647
13648                 //      If close to desired point, or 15+ seconds since entered this mode, continue to next mode.
13649                 if ((timestamp_until(aip->big_recover_timestamp) < -15*1000) || (dist < (0.5f + flFrametime) * objp->phys_info.speed)) {
13650                         aip->ai_flags &= ~AIF_BIG_SHIP_COLLIDE_RECOVER_1;
13651                         aip->ai_flags |= AIF_BIG_SHIP_COLLIDE_RECOVER_2;
13652                 }
13653
13654                 return 1;
13655
13656         } else if (aip->ai_flags & AIF_BIG_SHIP_COLLIDE_RECOVER_2) {
13657                 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);
13658                 dist = vm_vec_normalized_dir(&v2g, &aip->big_recover_pos_2, &objp->pos);
13659                 dot = vm_vec_dot(&objp->orient.v.fvec, &v2g);
13660                 accelerate_ship(aip, dot);
13661
13662                 //      If close to desired point, or 30+ seconds since started avoiding collision, done avoiding.
13663                 if ((timestamp_until(aip->big_recover_timestamp) < -30*1000) || (dist < (0.5f + flFrametime) * objp->phys_info.speed)) {
13664                         aip->ai_flags &= ~AIF_BIG_SHIP_COLLIDE_RECOVER_2;
13665                         aip->ai_flags &= ~AIF_TARGET_COLLISION;
13666                 }
13667
13668                 return 1;
13669         }
13670
13671         if (aip->ai_flags & AIF_TARGET_COLLISION) {
13672                 aip->ai_flags &= ~AIF_TARGET_COLLISION;
13673         }
13674         return 0;
13675 }
13676
13677 void validate_mode_submode(ai_info *aip)
13678 {
13679         switch (aip->mode) {
13680         case AIM_CHASE:
13681                 // check valid submode
13682                 switch (aip->submode) {
13683                 case SM_CONTINUOUS_TURN:
13684                 case SM_ATTACK:
13685                 case SM_EVADE_SQUIGGLE:
13686                 case SM_EVADE_BRAKE:    
13687                 case SM_EVADE:          
13688                 case SM_SUPER_ATTACK:
13689                 case SM_AVOID:  
13690                 case SM_GET_BEHIND:
13691                 case SM_GET_AWAY:               
13692                 case SM_EVADE_WEAPON:
13693                 case SM_FLY_AWAY:       
13694                 case SM_ATTACK_FOREVER:
13695                         break;
13696                 default:
13697                         Int3();
13698                 }
13699                 break;
13700
13701         case AIM_STRAFE:
13702                 // check valid submode
13703                 switch(aip->submode) {
13704                 case AIS_STRAFE_ATTACK:
13705                 case AIS_STRAFE_AVOID:
13706                 case AIS_STRAFE_RETREAT1:
13707                 case AIS_STRAFE_RETREAT2:
13708                 case AIS_STRAFE_POSITION:
13709                         break;
13710                 default:
13711                         Int3();
13712                 }
13713                 break;
13714         }
13715 }
13716
13717 //      --------------------------------------------------------------------------
13718 // Process AI object "objnum".
13719 void ai_frame(int objnum)
13720 {
13721         ship            *shipp = &Ships[Objects[objnum].instance];
13722         ai_info *aip = &Ai_info[shipp->ai_index];
13723         int             target_objnum;
13724
13725 //      validate_mode_submode(aip);
13726
13727         SDL_assert((aip->mode != AIM_WAYPOINTS) || (aip->active_goal != AI_ACTIVE_GOAL_DYNAMIC));
13728
13729         // Set globals defining the current object and its enemy object.
13730         Pl_objp = &Objects[objnum];
13731
13732         if (aip->mode == AIM_WARP_OUT) {
13733                 ai_warp_out(Pl_objp);
13734                 return;
13735         }
13736
13737 /*      //      HACK! TEST! REMOVE ME!
13738         if (Ship_info[shipp->ship_info_index].flags & SIF_BIG_SHIP)
13739                 if (shipp->team == Player_ship->team)
13740                         aip->mode = AIM_CHASE;
13741 */
13742
13743 //      if (!SDL_strncasecmp(Ships[Pl_objp->instance].ship_name, "cancer", 6))
13744 //              nprintf(("AI", "Ship %s: mode = %s, submode = %i\n", Ships[Pl_objp->instance].ship_name, Mode_text[aip->mode], aip->submode));
13745
13746         ai_maybe_self_destruct(Pl_objp, aip);
13747
13748 //      if ( timestamp_elapsed(aip->goal_check_time) ) {
13749                 ai_process_mission_orders( objnum, aip );
13750 //              aip->goal_check_time = timestamp_rand(1000,2000);
13751 //      }
13752
13753         //      Avoid a shockwave, if necessary.  If a shockwave and rearming, stop rearming.
13754         if (aip->ai_flags & AIF_AVOID_SHOCKWAVE) {
13755                 if (ai_avoid_shockwave(Pl_objp, aip)) {
13756                         aip->ai_flags &= ~(AIF_BIG_SHIP_COLLIDE_RECOVER_1 | AIF_BIG_SHIP_COLLIDE_RECOVER_2);
13757                         if (aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED))
13758                                 ai_abort_rearm_request(Pl_objp);
13759                         return;
13760                 }
13761         } else {
13762                 aip->ai_flags &= ~AIF_AVOID_SHOCKWAVE_STARTED;
13763         }
13764
13765         // moved call to ai_do_repair frame here from below because of the subsequent if statment returning
13766         // if the ship is getting repaired
13767         //      If waiting to be repaired, just stop and sit.
13768         ai_do_repair_frame(Pl_objp, aip, flFrametime);
13769         if ((aip->ai_flags & AIF_AWAITING_REPAIR) || (aip->ai_flags & AIF_BEING_REPAIRED)) {
13770                 if (ai_await_repair_frame(Pl_objp, aip))
13771                         return;
13772         }
13773
13774         if (aip->mode == AIM_PLAY_DEAD)
13775                 return;
13776
13777         //      If recovering from a collision with a big ship, don't continue.
13778         if (maybe_big_ship_collide_recover_frame(Pl_objp, aip))
13779                 return;
13780
13781         ai_preprocess_ignore_objnum(Pl_objp, aip);
13782         target_objnum = set_target_objnum(aip, aip->target_objnum);
13783
13784         // 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));
13785
13786         SDL_assert(objnum != target_objnum);
13787
13788         ai_manage_shield(Pl_objp, aip);
13789         
13790         if ( maybe_request_support(Pl_objp) ) {
13791                 if ( Ships[Pl_objp->instance].flags & SF_FROM_PLAYER_WING ) {
13792                         ship_maybe_tell_about_rearm(shipp);
13793                 }
13794         }
13795
13796         ai_maybe_warp_out(Pl_objp);
13797
13798 /*
13799         //      If this ship is attacking an object's subsystems and someone else destroyed
13800         //      the subsystem, it could continue attacking the ship.  Need to invalidate the objnum.
13801         if (target_objnum >= 0)
13802                 if (Objects[target_objnum].flags & OF_PROTECTED) {
13803                         // if (aip->targeted_subsys != NULL)
13804                         //      ; //nprintf(("AI", "subsys hits = %7.3f\n", aip->targeted_subsys->current_hits));
13805
13806                         if ((aip->targeted_subsys == NULL) || (aip->targeted_subsys->current_hits <= 0.0f)) {
13807                                 target_objnum = -1;
13808                                 aip->target_objnum = -1;
13809                         }
13810                 }
13811 */
13812
13813
13814         //      Find an enemy if don't already have one.
13815         En_objp = NULL;
13816         if ( ai_need_new_target(Pl_objp, target_objnum) ) {
13817                 if ((aip->mode != AIM_EVADE_WEAPON) && (aip->active_goal == AI_ACTIVE_GOAL_DYNAMIC)) {
13818                         aip->resume_goal_time = -1;
13819                         aip->active_goal = AI_GOAL_NONE;
13820                 } else if (aip->resume_goal_time == -1) {
13821                         // AL 12-9-97: Don't allow cargo and navbuoys to set their aip->target_objnum
13822                         if ( !(Ship_info[shipp->ship_info_index].flags & SIF_HARMLESS) ) {
13823                                 target_objnum = find_enemy(objnum, MAX_ENEMY_DISTANCE, Skill_level_max_attackers[Game_skill_level]);            //      Attack up to 25K units away.
13824                                 if (target_objnum != -1) {
13825                                         if (aip->target_objnum != target_objnum)
13826                                                 aip->aspect_locked_time = 0.0f;
13827                                         set_target_objnum(aip, target_objnum);
13828                                         En_objp = &Objects[target_objnum];
13829                                 }
13830                         }
13831                 }
13832         } else if (target_objnum >= 0) {
13833                 En_objp = &Objects[target_objnum];
13834         }
13835
13836         // set base stealth info each frame
13837         aip->ai_flags &= ~AIF_STEALTH_PURSIUT;
13838         if (En_objp && En_objp->type == OBJ_SHIP) {
13839                 if (Ship_info[Ships[En_objp->instance].ship_info_index].flags & SIF_STEALTH) {
13840                         int stealth_state = ai_is_stealth_visible(Pl_objp, En_objp);
13841                         float dist = vm_vec_dist_quick(&En_objp->pos, &Pl_objp->pos);
13842
13843                         if (stealth_state != STEALTH_FULLY_TARGETABLE) {
13844                                 aip->ai_flags |= AIF_STEALTH_PURSIUT;
13845                         }
13846
13847                         if ( (stealth_state == STEALTH_FULLY_TARGETABLE) || (stealth_state == STEALTH_VISIBLE) ) {
13848                                 aip->stealth_last_visible_stamp = timestamp();
13849                                 aip->stealth_last_cheat_visible_stamp = aip->stealth_last_visible_stamp;
13850                                 aip->stealth_last_pos = En_objp->pos;
13851                                 aip->stealth_velocity = En_objp->phys_info.vel;
13852                         } else if (dist < 100) {
13853                                 // get cheat timestamp
13854                                 aip->stealth_last_cheat_visible_stamp = timestamp();
13855
13856                                 // set approximate pos and vel, with increasing error as time from last_visible_stamp increases
13857                                 update_ai_stealth_info_with_error(aip/*, 0*/);
13858                         }
13859                 }
13860         }
13861
13862         /*      if ((Pl_objp != NULL) && (En_objp != NULL)) {
13863                 slide_face_ship();
13864                 return;
13865         }
13866 */
13867         // AL 12-10-97: ensure that cargo and navbuoys aip->target_objnum is always -1.
13868         if ( Ship_info[shipp->ship_info_index].flags & SIF_HARMLESS ) {
13869                 aip->target_objnum = -1;
13870         }
13871
13872         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)) {
13873                 mprintf(("Warning: Object and its enemy have same position.  Object #%i\n", Pl_objp-Objects));
13874                 En_objp = NULL;
13875         }
13876
13877         if (aip->mode == AIM_CHASE) {
13878                 if (En_objp == NULL) {
13879                         aip->active_goal = -1;
13880                 }
13881         }
13882
13883         //      If there is a goal to resume and enough time has elapsed, resume the goal.
13884         if ((aip->resume_goal_time > 0) && (aip->resume_goal_time < Missiontime)) {
13885                 aip->active_goal = AI_GOAL_NONE;
13886                 aip->resume_goal_time = -1;
13887                 target_objnum = find_enemy(objnum, 2000.0f, Skill_level_max_attackers[Game_skill_level]);
13888                 if (target_objnum != -1) {
13889                         if (aip->target_objnum != target_objnum) {
13890                                 aip->aspect_locked_time = 0.0f;
13891                         }
13892                         set_target_objnum(aip, target_objnum);
13893                 }
13894         }
13895
13896         // check if targeted subsystem has been destroyed, if so, move onto another subsystem
13897         // if trying to disable or disarm the target
13898         if ((En_objp != NULL) && ( aip->targeted_subsys != NULL )) {
13899                 SDL_assert(En_objp->type == OBJ_SHIP);
13900                 if ( aip->targeted_subsys->current_hits <= 0.0f ) {
13901                         int subsys_type;
13902
13903                         if ( aip->goals[0].ai_mode == AI_GOAL_DISABLE_SHIP ) {
13904                                 subsys_type = SUBSYSTEM_ENGINE;
13905                         } else if ( aip->goals[0].ai_mode == AI_GOAL_DISARM_SHIP ) {
13906                                 subsys_type = SUBSYSTEM_TURRET;
13907                         } else {
13908                                 subsys_type = -1;
13909                         }
13910
13911                         if ( subsys_type != -1 ) {
13912                                 ship_subsys *new_subsys;
13913                                 new_subsys = ship_return_next_subsys(&Ships[En_objp->instance], subsys_type, &Pl_objp->pos);
13914                                 if ( new_subsys != NULL ) {
13915                                         set_targeted_subsys(aip, new_subsys, aip->target_objnum);
13916                                 } else {
13917                                         // AL 12-16-97: no more subsystems to attack... reset targeting info
13918                                         aip->target_objnum = -1;
13919                                         set_targeted_subsys(aip, NULL, -1);
13920                                 }
13921                         } else {
13922                                 // targeted subsys is destroyed, so stop attacking it
13923                                 set_targeted_subsys(aip, NULL, -1);
13924                         }
13925                 }
13926         }
13927
13928         ai_maybe_launch_cmeasure(Pl_objp, aip);
13929         ai_maybe_evade_locked_missile(Pl_objp, aip);
13930
13931         aip->target_time += flFrametime;
13932
13933         int in_formation = 0;
13934         if (aip->ai_flags & AIF_FORMATION) {
13935                 in_formation = !ai_formation();
13936         }
13937
13938         if ( !in_formation ) {
13939                 ai_execute_behavior(aip);
13940         }
13941
13942         process_subobjects(objnum);
13943         maybe_resume_previous_mode(Pl_objp, aip);
13944         
13945         if (Pl_objp->phys_info.flags & PF_AFTERBURNER_ON ) {
13946                 if (Missiontime > aip->afterburner_stop_time) {
13947                         //nprintf(("AI", "Frame %i, turning off afterburner.\n", AI_FrameCount));
13948                         afterburners_stop(Pl_objp);
13949                 }
13950         }
13951 //      validate_mode_submode(aip);
13952 }
13953
13954 int Waypoints_created = 0;
13955
13956 //      Find the ship with the name *name in the Ship_info array.
13957 int find_ship_name(char *name)
13958 {
13959         int     i;
13960
13961         for (i=0; i<Num_ship_types; i++)
13962                 if (!strcmp(Ship_info[i].name, name))
13963                         return i;
13964
13965         return -1;
13966 }
13967
13968 void create_waypoints()
13969 {
13970         int     i, j;
13971
13972         // Waypoints_created = 1;
13973
13974         if (Waypoints_created)
13975                 return;
13976
13977         for (j=0; j<Num_waypoint_lists; j++)
13978                 for (i=0; i<Waypoint_lists[j].count; i++) {
13979                         obj_create(OBJ_WAYPOINT, 0, j * 65536 + i, NULL,
13980                                 &Waypoint_lists[j].waypoints[i], 0.0f, OF_RENDERS);
13981                 }
13982
13983         Waypoints_created = 1;
13984 }
13985
13986 int Last_ai_obj = -1;
13987
13988 void ai_process( object * obj, int ai_index, float frametime )
13989 {
13990 //      if (Ships[obj->instance].flags & SF_DYING)
13991 //              nprintf(("AI", "Frame: %i Ship %s is dying!\n", Framecount, Ships[obj->instance].ship_name));
13992
13993         if (obj->flags & OF_SHOULD_BE_DEAD)
13994                 return;
13995
13996         // 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.
13997         if ((Ships[obj->instance].flags & SF_DYING ) && !(Ship_info[Ships[obj->instance].ship_info_index].flags & (SIF_HUGE_SHIP | SIF_BIG_SHIP))){
13998                 return;
13999         }
14000
14001         int rfc = 1;            //      Assume will be Reading Flying Controls.
14002
14003         SDL_assert( obj->type == OBJ_SHIP );
14004         SDL_assert( ai_index >= 0 );
14005
14006         init_ship_info();
14007
14008         create_waypoints();
14009
14010         AI_frametime = frametime;
14011         if (obj-Objects <= Last_ai_obj) {
14012                 AI_FrameCount++;
14013         }
14014
14015         memset( &AI_ci, 0, sizeof(AI_ci) );
14016
14017         ai_frame(obj-Objects);
14018
14019         AI_ci.pitch = 0.0f;
14020         AI_ci.bank = 0.0f;
14021         AI_ci.heading = 0.0f;
14022
14023         // the ships maximum velocity now depends on the energy flowing to engines
14024         obj->phys_info.max_vel.xyz.z = Ships[obj->instance].current_max_speed;
14025         ai_info *aip = &Ai_info[Ships[obj->instance].ai_index];
14026
14027         //      In certain circumstances, the AI says don't fly in the normal way.
14028         //      One circumstance is in docking and undocking, when the ship is moving
14029         //      under thruster control.
14030         switch (aip->mode) {
14031         case AIM_DOCK:
14032                 if ((aip->submode >= AIS_DOCK_2) && (aip->submode != AIS_UNDOCK_3))
14033                         rfc = 0;
14034                 break;
14035         case AIM_WARP_OUT:
14036                 if (aip->submode >= AIS_WARP_3)
14037                         rfc = 0;
14038                 break;
14039 //      case AIM_NONE:
14040 //              if (aip->submode == AIS_NONE_FORMATION)
14041 //                      rfc = 0;
14042 //              break;
14043         default:
14044                 break;
14045         }
14046
14047         if (rfc == 1) {
14048                 vector copy_desired_rotvel = obj->phys_info.rotvel;
14049                 physics_read_flying_controls( &obj->orient, &obj->phys_info, &AI_ci, frametime);
14050                 // if obj is in formation and not flight leader, don't update rotvel
14051                 if (aip->ai_flags & AIF_FORMATION) {
14052                         if (&Objects[aip->goal_objnum] != obj) {
14053                                 obj->phys_info.desired_rotvel = copy_desired_rotvel;
14054                                 obj->phys_info.rotvel = copy_desired_rotvel;
14055                         }
14056                 }
14057         }
14058
14059         Last_ai_obj = obj-Objects;
14060 }
14061
14062 //      Initialize ai_info struct of object objnum.
14063 void init_ai_object(int objnum)
14064 {
14065         int     ship_index, ai_index;
14066         ai_info *aip;
14067         int ship_type;
14068         object  *objp;
14069         vector  near_vec;                       //      A vector nearby and mainly in front of this object.
14070
14071         objp = &Objects[objnum];
14072         ship_index = objp->instance;
14073         ai_index = Ships[ship_index].ai_index;
14074         SDL_assert((ai_index >= 0) && (ai_index < MAX_AI_INFO));
14075
14076         aip = &Ai_info[ai_index];
14077
14078         ship_type = Ships[ship_index].ship_info_index;
14079
14080         vm_vec_scale_add(&near_vec, &objp->pos, &objp->orient.v.fvec, 100.0f);
14081         vm_vec_scale_add2(&near_vec, &objp->orient.v.rvec, 10.0f);
14082
14083         // Things that shouldn't have to get initialized, but initialize them just in case!
14084         aip->ai_flags = 0;
14085         aip->previous_mode = AIM_NONE;
14086         aip->mode_time = -1;
14087         aip->target_objnum = -1;
14088         aip->target_signature = -1;
14089         aip->previous_target_objnum = -1;
14090         aip->target_time = 0.0f;
14091         aip->enemy_wing = -1;
14092         aip->attacker_objnum = -1;
14093         aip->goal_objnum = -1;
14094         aip->goal_signature = -1;
14095         aip->guard_objnum = -1;
14096         aip->guard_signature = -1;
14097         aip->guard_wingnum = -1;
14098         aip->dock_signature = -1;
14099         aip->submode = 0;
14100         aip->previous_submode = 0;
14101         aip->best_dot_to_enemy = -1.0f;
14102         aip->best_dot_from_enemy = -1.0f;
14103         aip->best_dot_to_time = 0;
14104         aip->best_dot_from_time = 0;
14105         aip->submode_start_time = 0;
14106         aip->submode_parm0 = 0;
14107         aip->active_goal = -1;
14108         aip->goal_check_time = timestamp(0);
14109         aip->last_predicted_enemy_pos = near_vec;
14110         aip->prev_goal_point = near_vec;
14111         aip->goal_point = near_vec;
14112         aip->time_enemy_in_range = 0.0f;
14113         aip->last_attack_time = 0;
14114         aip->last_hit_time = 0;
14115         aip->last_hit_quadrant = 0;
14116         aip->hitter_objnum = -1;
14117         aip->hitter_signature = -1;
14118         aip->resume_goal_time = -1;
14119         aip->prev_accel = 0.0f;
14120         aip->prev_dot_to_goal = 0.0f;
14121
14122         aip->ignore_objnum = UNUSED_OBJNUM;
14123         aip->ignore_signature = -1;
14124
14125         // aip->mode = AIM_NONE;
14126
14127         // End of Things that shouldn't have to get initialized, but initialize them just in case!
14128
14129         aip->ai_courage = Ai_classes[Ship_info[ship_type].ai_class].ai_courage[Game_skill_level];
14130         aip->ai_patience = Ai_classes[Ship_info[ship_type].ai_class].ai_patience[Game_skill_level];
14131         aip->ai_evasion = Ai_classes[Ship_info[ship_type].ai_class].ai_evasion[Game_skill_level];
14132         aip->ai_accuracy = Ai_classes[Ship_info[ship_type].ai_class].ai_accuracy[Game_skill_level];
14133
14134         if (Num_waypoint_lists > 0) {
14135                 aip->wp_index = -1;
14136                 aip->wp_list = -1;
14137         } else {
14138                 aip->wp_index = -1;
14139                 aip->wp_list = -1;
14140         }
14141
14142         aip->attacker_objnum = -1;
14143         aip->goal_signature = -1;
14144
14145         Objects[objnum].phys_info.prev_fvec = Objects[objnum].orient.v.fvec;
14146
14147         aip->last_predicted_enemy_pos.xyz.x = 0.0f;     //      Says this value needs to be recomputed!
14148         aip->time_enemy_in_range = 0.0f;
14149
14150         aip->resume_goal_time = -1;                                     //      Say there is no goal to resume.
14151
14152         aip->active_goal = -1;
14153         aip->path_start = -1;
14154         aip->path_goal_dist = -1;
14155         aip->path_length = 0;
14156         aip->path_subsystem_next_check = 1;
14157         aip->dock_path_index = -1;
14158         aip->dock_index = -1;
14159         aip->dock_objnum = -1;
14160
14161         aip->danger_weapon_objnum = -1;
14162         aip->danger_weapon_signature = -1;
14163
14164         aip->lead_scale = 0.0f;
14165         aip->last_hit_target_time = Missiontime;
14166
14167         aip->nearest_locked_object = -1;
14168         aip->nearest_locked_distance = 99999.0f;
14169
14170         aip->targeted_subsys = NULL;
14171         aip->last_subsys_target = NULL;
14172         aip->targeted_subsys_parent = -1;
14173
14174         // The next two fields are used to time the rearming to allow useful sound effects for missile rearming
14175         aip->rearm_first_missile = TRUE;                //      flag to indicate that next missile to load is the first missile
14176         aip->rearm_release_delay = 0;                   //      timestamp to delay the separation of docked ships after rearm
14177
14178         aip->next_predict_pos_time = 0;
14179
14180         aip->afterburner_stop_time = 0;
14181         aip->last_objsig_hit = -1;                              // object signature of the ship most recently hit by aip
14182
14183         aip->path_next_create_time = timestamp(1);
14184         aip->path_create_pos = Objects[objnum].pos;
14185         aip->path_create_orient = Objects[objnum].orient;
14186
14187         aip->ignore_expire_timestamp = timestamp(1);
14188         aip->warp_out_timestamp = 0;
14189         aip->next_rearm_request_timestamp = timestamp(1);
14190         aip->primary_select_timestamp = timestamp(1);
14191         aip->secondary_select_timestamp = timestamp(1);
14192         aip->scan_for_enemy_timestamp = timestamp(1);
14193
14194         aip->choose_enemy_timestamp = timestamp(3*(NUM_SKILL_LEVELS-Game_skill_level) * ((rand_alt() % 500) + 500));
14195
14196         aip->shockwave_object = -1;
14197         aip->shield_manage_timestamp = timestamp(1);
14198         aip->self_destruct_timestamp = -1;      //      This is a flag that we have not yet set this.
14199         aip->ok_to_target_timestamp = timestamp(1);
14200         aip->pick_big_attack_point_timestamp = timestamp(1);
14201         vm_vec_zero(&aip->big_attack_point);
14202
14203         aip->avoid_check_timestamp = timestamp(1);
14204
14205         aip->abort_rearm_timestamp = -1;
14206
14207         // artillery stuff
14208         aip->artillery_objnum = -1;
14209         aip->artillery_sig = -1;        
14210
14211         // waypoint speed cap
14212         aip->waypoint_speed_cap = -1;
14213
14214         // set lethality to enemy team
14215         aip->lethality = 0.0f;
14216 }
14217
14218 void init_ai_objects()
14219 {
14220         int     i;
14221
14222         for (i=0; i<num_objects; i++){
14223                 if (Objects[i].type == OBJ_SHIP){
14224                         init_ai_object(i);
14225                 }
14226         }
14227 }
14228
14229 void init_ai_system()
14230 {
14231         // MWA -- removed next line of code on 11/12/97.  When a ship is created
14232         // it calls init_ai_object() on it's objnum.  Doing this init at the point where
14233         // this function gets called messes things up.
14234         //init_ai_objects();
14235
14236         Ppfp = Path_points;
14237         Waypoints_created = 0;
14238
14239         Dock_path_warning_given = 0;
14240
14241 /*      for (int i=0; i<MAX_IGNORE_OBJECTS; i++) {
14242                 Ignore_objects[i].objnum = -1;
14243                 Ignore_objects[i].signature = -1;
14244         }
14245 */
14246
14247 }
14248
14249 void ai_set_default_behavior(object *obj, int classnum)
14250 {
14251         ai_info *aip;
14252
14253         SDL_assert(obj != NULL);
14254         SDL_assert(obj->instance != -1);
14255         SDL_assert(Ships[obj->instance].ai_index != -1);
14256
14257         aip = &Ai_info[Ships[obj->instance].ai_index];
14258
14259         aip->behavior = classnum;
14260
14261 }
14262
14263 void ai_do_default_behavior(object *obj)
14264 {
14265         ai_info *aip;
14266         int             ship_flags;
14267
14268         SDL_assert(obj != NULL);
14269         SDL_assert(obj->instance != -1);
14270         SDL_assert(Ships[obj->instance].ai_index != -1);
14271
14272         aip = &Ai_info[Ships[obj->instance].ai_index];
14273
14274         ship_flags = Ship_info[Ships[obj->instance].ship_info_index].flags;
14275         if (!is_instructor(obj) && (ship_flags & (SIF_FIGHTER | SIF_BOMBER))) {
14276                 int enemy_objnum = find_enemy(OBJ_INDEX(obj), 1000.0f, Skill_level_max_attackers[Game_skill_level]);
14277                 set_target_objnum(aip, enemy_objnum);
14278                 aip->mode = AIM_CHASE;
14279                 aip->submode = SM_ATTACK;
14280         } else if (ship_flags & (SIF_SUPPORT)) {
14281                 aip->mode = AIM_SAFETY;
14282                 aip->submode = AISS_1;
14283                 aip->ai_flags &= ~(AIF_REPAIRING);
14284         } else if ( ship_flags & SIF_SENTRYGUN ) {
14285                 aip->mode = AIM_SENTRYGUN;
14286         } else {
14287                 aip->mode = AIM_NONE;
14288         }
14289         
14290         aip->submode_start_time = Missiontime;
14291         aip->active_goal = AI_GOAL_NONE;
14292 }
14293
14294 #define FRIENDLY_DAMAGE_THRESHOLD       50.0f           //      Display a message at this threshold.  Note, this gets scaled by Skill_level
14295
14296 // send the given message from objp.  called from the maybe_process_friendly_hit
14297 // code below when a message must get send to the player when he fires on friendlies
14298 void process_friendly_hit_message( int message, object *objp )
14299 {
14300         int index;
14301
14302         // no traitor in multiplayer
14303         if(Game_mode & GM_MULTIPLAYER){
14304                 return;
14305         }
14306
14307         // don't send this message if a player ship was hit.
14308         if ( objp->flags & OF_PLAYER_SHIP ){
14309                 return;
14310         }
14311
14312         // check if objp is a cargo contianer -- if so, then find a new ship to send the message
14313         index = objp->instance;
14314         if ( !(Ship_info[Ships[objp->instance].ship_info_index].flags & (SIF_FIGHTER|SIF_BOMBER)) ){
14315                 index = -1;
14316         }
14317
14318         // if the message is "oops" (the don't hit me message), always make come from Terran command
14319         if ( message == MESSAGE_OOPS ){
14320                 index = -1;
14321         }
14322
14323         if ( index >= 0){
14324                 message_send_builtin_to_player( message, &Ships[index], MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_ANYTIME, 0, 0, -1, -1 );
14325         } else {
14326                 message_send_builtin_to_player( message, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_ANYTIME, 0, 0, -1, -1 );
14327         }
14328 }
14329
14330 extern  void ship_set_subsystem_strength( ship *shipp, int type, float strength );
14331
14332 //      Object *objp_weapon, fired by *objp_hitter, hit object *objp_ship.
14333 void maybe_process_friendly_hit(object *objp_hitter, object *objp_hit, object *objp_weapon)
14334 {
14335         // no turning traitor in multiplayer
14336         if ( Game_mode & GM_MULTIPLAYER ) {
14337                 return;
14338         }
14339
14340         // ditto if mission says no traitors allowed
14341         if (The_mission.flags & MISSION_FLAG_NO_TRAITOR) {
14342                 return;
14343         }
14344
14345         if ((objp_hitter == Player_obj) && (Player_ship->team == TEAM_FRIENDLY)) {
14346
14347                 // AL 12-4-97: It is possible the Player is a OBJ_GHOST at this point.  If so, bail out.
14348                 if ( objp_hitter->type != OBJ_SHIP ) {
14349                         return;
14350                 }
14351
14352                 SDL_assert(objp_hitter->type == OBJ_SHIP);
14353                 SDL_assert(objp_hit->type == OBJ_SHIP);
14354                 SDL_assert(objp_weapon->type == OBJ_WEAPON);
14355
14356                 ship    *shipp_hitter = &Ships[objp_hitter->instance];
14357                 ship    *shipp_hit = &Ships[objp_hit->instance];
14358
14359                 if (shipp_hitter->team != shipp_hit->team) {
14360                         return;
14361                 }
14362
14363                 // get the player
14364                 player *pp = &Players[Player_num];
14365
14366                 // wacky stuff here
14367                 if (pp->friendly_hits != 0) {
14368                         float   time_since_last_hit = f2fl(Missiontime - pp->friendly_last_hit_time);
14369                         if ((time_since_last_hit >= 0.0f) && (time_since_last_hit < 10000.0f)) {
14370                                 if (time_since_last_hit > 60.0f) {
14371                                         pp->friendly_hits = 0;
14372                                         pp->friendly_damage = 0.0f;
14373                                 } else if (time_since_last_hit > 2.0f) {
14374                                         pp->friendly_hits -= (int) time_since_last_hit/2;
14375                                         pp->friendly_damage -= time_since_last_hit;
14376                                 }
14377
14378                                 if (pp->friendly_damage < 0.0f) {
14379                                         pp->friendly_damage = 0.0f;
14380                                 }
14381
14382                                 if (pp->friendly_hits < 0) {
14383                                         pp->friendly_hits = 0;
14384                                 }
14385                         }
14386                 }
14387
14388                 float   damage;         //      Damage done by weapon.  Gets scaled down based on size of ship.
14389
14390                 damage = Weapon_info[Weapons[objp_weapon->instance].weapon_info_index].damage;
14391                 
14392                 // wacky stuff here
14393                 ship_info *sip = &Ship_info[Ships[objp_hit->instance].ship_info_index];
14394                 if (sip->initial_hull_strength > 1000.0f) {
14395                         float factor = sip->initial_hull_strength / 1000.0f;
14396                         factor = min(100.0f, factor);
14397                         damage /= factor;
14398                 }
14399
14400                 //      Don't penalize much at all for hitting cargo
14401                 if (sip->flags & (SIF_CARGO | SIF_SENTRYGUN)) {
14402                         damage /= 10.0f;
14403                 }
14404
14405                 //      Hit ship, but not targeting it, so it's not so heinous, maybe an accident.
14406                 if (Ai_info[shipp_hitter->ai_index].target_objnum != OBJ_INDEX(objp_hit)) {
14407                         damage /= 5.0f;
14408                 }
14409
14410                 pp->friendly_last_hit_time = Missiontime;
14411                 pp->friendly_hits++;
14412
14413                 // cap damage and number of hits done this frame
14414                 float accredited_damage = min(MAX_BURST_DAMAGE, pp->damage_this_burst + damage) - pp->damage_this_burst;
14415                 pp->friendly_damage += accredited_damage;
14416                 pp->damage_this_burst += accredited_damage;
14417
14418                 // Done with adjustments to damage.  Evaluate based on current friendly_damage
14419                 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 ));
14420                 
14421                 if (is_instructor(objp_hit)) {
14422                         // it's not nice to hit your instructor
14423                         if (pp->friendly_damage > FRIENDLY_DAMAGE_THRESHOLD) {
14424                                 message_send_builtin_to_player( MESSAGE_INSTRUCTOR_ATTACK, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_IMMEDIATE, 0, 0, -1, -1);
14425                                 pp->last_warning_message_time = Missiontime;
14426                                 ship_set_subsystem_strength( Player_ship, SUBSYSTEM_WEAPONS, 0.0f);
14427
14428                                 training_fail();
14429
14430                                 //      Instructor warp out.
14431                                 ai_set_mode_warp_out(objp_hit, &Ai_info[Ships[objp_hit->instance].ai_index]);
14432                                 gameseq_post_event( GS_EVENT_PLAYER_WARPOUT_START_FORCED );     //      Force player to warp out.
14433
14434                                 //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) );
14435                                 //ship_apply_global_damage( objp_hitter, objp_hit, NULL, 1.0f );
14436                         } else if (Missiontime - pp->last_warning_message_time > F1_0*4) {
14437                                 // warning every 4 sec
14438                                 // use NULL as the message sender here since it is the Terran Command persona
14439                                 message_send_builtin_to_player( MESSAGE_INSTRUCTOR_HIT, NULL, MESSAGE_PRIORITY_HIGH, MESSAGE_TIME_IMMEDIATE, 0, 0, -1, -1);
14440                                 pp->last_warning_message_time = Missiontime;
14441                         }
14442
14443                 // not nice to hit your friends
14444                 } else if (pp->friendly_damage > FRIENDLY_DAMAGE_THRESHOLD * (1.0f + (float) (NUM_SKILL_LEVELS + 1 - Game_skill_level)/3.0f)) {
14445                         process_friendly_hit_message( MESSAGE_HAMMER_SWINE, objp_hit );
14446                         mission_goal_fail_all();
14447                         ai_abort_rearm_request( Player_obj );
14448
14449                         Player_ship->team = TEAM_TRAITOR;
14450
14451                 } else if ((damage > frand()) && (Missiontime - pp->last_warning_message_time > F1_0*4) && (pp->friendly_damage > FRIENDLY_DAMAGE_THRESHOLD)) {
14452                         // no closer than 4 sec intervals
14453                         //      Note: (damage > frand()) added on 12/9/97 by MK.  Since damage is now scaled down for big ships, we could get too
14454                         //      many warnings.  Kind of tedious.  frand() returns a value in 0..1, so this won't affect legit hits.
14455                         process_friendly_hit_message( MESSAGE_OOPS, objp_hit );
14456                         pp->last_warning_message_time = Missiontime;
14457                 }
14458         }
14459 }
14460
14461 //      Maybe make ship with ai_info *aip attack hitter_objnum as a dynamic goal
14462 void maybe_set_dynamic_chase(ai_info *aip, int hitter_objnum)
14463 {
14464         SDL_assert(Ship_info[Ships[aip->shipnum].ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER));
14465
14466         // limit the number of ships attacking hitter_objnum (for now, only if hitter_objnum is player)
14467         if ( ai_maybe_limit_attackers(hitter_objnum) == 1 ) {
14468                 return;
14469         }
14470
14471         // only set as target if can be targeted.
14472         if (awacs_get_level(&Objects[hitter_objnum], &Ships[aip->shipnum], 1) < 1) {
14473                 return;
14474         }
14475
14476         if (aip->target_objnum != hitter_objnum)
14477                 aip->aspect_locked_time = 0.0f;
14478         set_target_objnum(aip, hitter_objnum);
14479         aip->resume_goal_time = Missiontime + i2f(20);  //      Only chase up to 20 seconds.
14480         aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
14481
14482         set_targeted_subsys(aip, NULL, -1);             //      Say not attacking any particular subsystem.
14483
14484         aip->previous_submode = aip->mode;
14485         aip->mode = AIM_CHASE;
14486         aip->submode = SM_ATTACK;
14487 }
14488
14489
14490 //      Return true if *objp has armed an aspect seeking bomb.
14491 //      This function written so a ship with an important bomb to fire will willingly take hits in the face to fire its bomb.
14492 int firing_aspect_seeking_bomb(object *objp)
14493 {
14494         ship    *shipp;
14495         int     bank_index;
14496         ship_weapon     *swp;
14497
14498         shipp = &Ships[objp->instance];
14499
14500         swp = &shipp->weapons;
14501
14502         bank_index = swp->current_secondary_bank;
14503
14504         if (bank_index != -1)
14505                 if (swp->secondary_bank_ammo[bank_index] > 0) {
14506                         if (Weapon_info[swp->secondary_bank_weapons[bank_index]].wi_flags & WIF_BOMB) {
14507                                 if (Weapon_info[swp->secondary_bank_weapons[bank_index]].wi_flags & WIF_HOMING_ASPECT) {
14508                                         return 1;
14509                                 }
14510                         }
14511                 }
14512
14513         return 0;
14514 }
14515
14516 //      *objp collided with big ship *big_objp at global point *collide_pos
14517 //      Make it fly away from the collision point.
14518 // collision_normal is NULL, when a collision is imminent and we just want to bug out.
14519 void big_ship_collide_recover_start(object *objp, object *big_objp, vector *collide_pos, vector *collision_normal)
14520 {
14521         ai_info *aip;
14522
14523         SDL_assert(objp->type == OBJ_SHIP);
14524
14525         aip = &Ai_info[Ships[objp->instance].ai_index];
14526
14527         if (!timestamp_elapsed(aip->big_recover_timestamp) && (aip->ai_flags & AIF_BIG_SHIP_COLLIDE_RECOVER_1))
14528                 return;
14529
14530         //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)));
14531         if (collision_normal) {
14532                 aip->big_recover_timestamp = timestamp(2000);
14533                 aip->big_collision_normal = *collision_normal;
14534         //      nprintf(("AI", " normal\n"));
14535         } else {
14536                 aip->big_recover_timestamp = timestamp(500);
14537         //      nprintf(("AI", " no normal\n"));
14538         }
14539
14540
14541         aip->ai_flags &= ~AIF_BIG_SHIP_COLLIDE_RECOVER_2;
14542         aip->ai_flags |= AIF_BIG_SHIP_COLLIDE_RECOVER_1;
14543
14544 //      vector  out_vec;
14545 //      vm_vec_normalized_dir(&out_vec, &objp->pos, collide_pos);
14546
14547         // big_recover_pos_1 is 100 m out along normal
14548         vector direction;
14549         if (collision_normal) {
14550                 direction = *collision_normal;
14551         } else {
14552                 vm_vec_copy_scale(&direction, &objp->orient.v.fvec, -1.0f);
14553         }
14554         vm_vec_scale_add(&aip->big_recover_pos_1, &objp->pos, &direction, 100.0f);
14555
14556         // go out 200 m from box closest box point
14557         get_world_closest_box_point_with_delta(&aip->big_recover_pos_2, big_objp, &aip->big_recover_pos_1, NULL, 300.0f);
14558
14559         accelerate_ship(aip, 0.0f);
14560 /*
14561         if (vm_vec_dot(collision_normal, &objp->orient.v.fvec) > 0.5f) {
14562 //              vm_vec_scale_add(&aip->big_recover_pos_1, &objp->pos, &out_vec, big_objp->radius/2.0f);
14563 //              vm_vec_scale_add(&aip->big_recover_pos_2, &aip->big_recover_pos_1, &objp->orient.v.uvec, big_objp->radius/2.0f);
14564 //              vm_vec_scale_add(&aip->big_recover_pos_2, &objp->pos, &out_vec, big_objp->radius*2.0f);
14565                 accelerate_ship(aip, 2.0f);
14566         } else {
14567 //              vm_vec_scale_add(&aip->big_recover_pos_1, &objp->pos, &out_vec, big_objp->radius/2.0f);
14568 //              vm_vec_scale_add(&aip->big_recover_pos_2, &aip->big_recover_pos_1, &objp->orient.v.uvec, big_objp->radius/2.0f);
14569                 accelerate_ship(aip, 0.0f);
14570         } */
14571 }
14572
14573 float max_lethality = 0.0f;
14574
14575 void ai_update_lethality(object *ship_obj, object *other_obj, float damage)
14576 {
14577         SDL_assert(ship_obj->type == OBJ_SHIP);
14578         SDL_assert(other_obj->type == OBJ_WEAPON || other_obj->type == OBJ_SHOCKWAVE);
14579         int dont_count = FALSE;
14580
14581         int parent = other_obj->parent;
14582         if (Objects[parent].type == OBJ_SHIP) {
14583                 if (Objects[parent].signature == other_obj->parent_sig) {
14584
14585                         // check damage done to enemy team
14586                         if (Ships[ship_obj->instance].team != Ships[Objects[parent].instance].team) {
14587
14588                                 // other is weapon
14589                                 if (other_obj->type == OBJ_WEAPON) {
14590                                         weapon *wp = &Weapons[other_obj->instance];
14591                                         weapon_info *wif = &Weapon_info[wp->weapon_info_index];
14592
14593                                         // if parent is BIG|HUGE, don't count beam
14594                                         if (Ship_info[Ships[Objects[parent].instance].ship_info_index].flags & (SIF_BIG_SHIP|SIF_HUGE_SHIP)) {
14595                                                 if (wif->wi_flags & WIF_BEAM) {
14596                                                         dont_count = TRUE;
14597                                                 }
14598                                         }
14599                                 }
14600
14601                                 if (!dont_count) {
14602                                         float lethality = 0.025f * damage;      // 2 cyclops (@2000) put you at 100 lethality
14603
14604                                         // increase lethality weapon's parent ship
14605                                         ai_info *aip = &Ai_info[Ships[Objects[parent].instance].ai_index];
14606                                         aip->lethality += lethality;
14607                                         aip->lethality = min(110.0f, aip->lethality);
14608                                         // if you hit, don;t be less than 0
14609                                         aip->lethality = max(0.0f, aip->lethality);
14610
14611 //                                      if (aip->lethality > max_lethality) {
14612 //                                              max_lethality = aip->lethality;
14613 //                                              mprintf(("new lethalilty high: %.1f\n", max_lethality));
14614 //                                      }
14615
14616                                         // if parent is player, show his lethality
14617 //                                      if (Objects[parent].flags & OF_PLAYER_SHIP) {
14618 //                                              mprintf(("Player lethality: %.1f\n", aip->lethality));
14619 //                                      }
14620                                 }
14621                         }
14622                 }
14623         }
14624 }
14625
14626
14627 //      Object *objp_ship was hit by either weapon *objp_weapon or collided into by ship hit_objp at point *hitpos.
14628 void ai_ship_hit(object *objp_ship, object *hit_objp, vector *hitpos, int shield_quadrant, vector *hit_normal)
14629 {
14630         int             hitter_objnum = -2;
14631         object  *objp_hitter = NULL;
14632         ship            *shipp;
14633         ai_info *aip, *hitter_aip;
14634
14635         shipp = &Ships[objp_ship->instance];
14636         aip = &Ai_info[shipp->ai_index];
14637
14638         if (objp_ship->flags & OF_PLAYER_SHIP)
14639                 return;
14640
14641         if ((aip->mode == AIM_WARP_OUT) || (aip->mode == AIM_PLAY_DEAD))
14642                 return;
14643
14644         if (hit_objp->type == OBJ_SHIP) {
14645                 //      If the object that this ship collided with is a big ship
14646                 if (Ship_info[Ships[hit_objp->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)) {
14647                         //      And the current object is _not_ a big ship
14648                         if (!(Ship_info[Ships[objp_ship->instance].ship_info_index].flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP))) {
14649                                 //      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.
14650                                 big_ship_collide_recover_start(objp_ship, hit_objp, hitpos, hit_normal);
14651                         }
14652                 }
14653         }
14654
14655         if (hit_objp->type == OBJ_WEAPON) {
14656                 //      Make sure the object that fired this weapon is still alive.  If not, abort.
14657                 // SDL_assert(hit_objp->parent >= 0);
14658                 if(hit_objp->parent < 0){
14659                         return;
14660                 }
14661                 if ( hit_objp->parent_sig != Objects[hit_objp->parent].signature ){
14662                         return;
14663                 }
14664
14665                 //      Hit by a protected ship, don't attack it.
14666                 if (Objects[hit_objp->parent].flags & OF_PROTECTED) {
14667                         if ((Ship_info[shipp->ship_info_index].flags & (SIF_FIGHTER | SIF_BOMBER)) && (aip->target_objnum == -1)) {
14668                                 if (aip->mode == AIM_CHASE) {
14669                                         if (aip->submode != SM_EVADE_WEAPON) {
14670                                                 aip->mode = AIM_CHASE;
14671                                                 aip->submode = SM_EVADE_WEAPON;
14672                                                 aip->submode_start_time = Missiontime;
14673                                         }
14674                                 } else if (aip->mode != AIM_EVADE_WEAPON) {
14675                                         aip->active_goal = AI_ACTIVE_GOAL_DYNAMIC;
14676                                         aip->previous_mode = aip->mode;
14677                                         aip->previous_submode = aip->submode;
14678                                         aip->mode = AIM_EVADE_WEAPON;
14679                                         aip->submode = -1;
14680                                         aip->submode_start_time = Missiontime;
14681                                         aip->mode_time = timestamp(MAX_EVADE_TIME);     //      Evade for up to five seconds.
14682                                 }
14683
14684                         }
14685                         return;
14686                 }
14687
14688                 hitter_objnum = hit_objp->parent;
14689                 SDL_assert((hitter_objnum >= 0) && (hitter_objnum < MAX_OBJECTS));
14690                 objp_hitter = &Objects[hitter_objnum];
14691                 maybe_process_friendly_hit(objp_hitter, objp_ship, hit_objp);           //      Deal with player's friendly fire.
14692
14693                 if ( (shipp->team & TEAM_FRIENDLY) && !(Game_mode & GM_MULTIPLAYER) ) {
14694                         ship_maybe_ask_for_help(shipp);
14695                 }
14696         } else if (hit_objp->type == OBJ_SHIP) {
14697                 if (shipp->team == Ships[hit_objp->instance].team)              //      Don't have AI react to collisions between teammates.
14698                         return;
14699                 objp_hitter = hit_objp;
14700                 hitter_objnum = hit_objp-Objects;
14701         } else {
14702                 Int3(); //      Hmm, what kind of object hit this if not weapon or ship?  Get MikeK.
14703                 return;
14704         }
14705
14706         //      Collided into a protected ship, don't attack it.
14707         if (hit_objp->flags & OF_PROTECTED)
14708                 return;
14709
14710         SDL_assert(objp_hitter != NULL);
14711         hitter_aip = &Ai_info[Ships[objp_hitter->instance].ai_index];
14712         hitter_aip->last_hit_target_time = Missiontime;
14713         
14714         // store the object signature of objp_ship into ai_info, since we want to track the last ship hit by 'hitter_objnum'
14715         hitter_aip->last_objsig_hit = objp_ship->signature; 
14716
14717         aip->last_hit_time = Missiontime;
14718
14719         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
14720                 return;
14721
14722         //      If this ship is awaiting repair, abort!
14723         if (aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED)) {
14724                 ship_info       *sip = &Ship_info[shipp->ship_info_index];
14725
14726                 if (objp_ship->hull_strength/sip->initial_hull_strength < 0.3f) {
14727                         //      No, only abort if hull below a certain level.
14728                         aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP/2);  //      Might request again after 15 seconds.
14729                         if ( !(objp_ship->flags & OF_PLAYER_SHIP) )                                             // mwa -- don't abort rearm for a player
14730                                 ai_abort_rearm_request(objp_ship);
14731                 }
14732         }
14733
14734         //      If firing a bomb, ignore enemy fire so we can gain lock drop the bomb.
14735         //      Only ignore fire if aspect_locked_time > 0.5f, as this means we're in range.
14736         if (firing_aspect_seeking_bomb(objp_ship)) {
14737                 if ((aip->ai_flags & AIF_SEEK_LOCK) && (aip->aspect_locked_time > 0.1f))
14738                         return;
14739         }
14740
14741         //      If in AIM_STRAFE mode and got hit by target, maybe attack turret if appropriate
14742         if (aip->mode == AIM_STRAFE) {
14743                 SDL_assert(hitter_objnum != -2);
14744                 if (aip->target_objnum == hitter_objnum) {
14745                         if ( hit_objp->type == OBJ_WEAPON ) {
14746                                 ai_big_strafe_maybe_attack_turret(objp_ship, hit_objp);
14747                         }
14748                         return;
14749                 }
14750                 else {
14751                                 // AL 11-10-97:
14752                         ;       // do nothing here, we'll attack this hitter if it is a fighter or bomber (this is handled
14753                                 // in code later in this function
14754                 }
14755         }
14756
14757         if (objp_ship == Player_obj)
14758                 return;         //      We don't do AI for the player.
14759
14760         maybe_update_guard_object(objp_ship, objp_hitter);
14761
14762         //      Big ships don't go any further.
14763         if (!(Ship_info[shipp->ship_info_index].flags & SIF_SMALL_SHIP))
14764                 return;
14765
14766         //      If the hitter object is the ignore object, don't attack it.
14767         ship_info       *sip = &Ship_info[shipp->ship_info_index];
14768         if ((is_ignore_object(aip, objp_hitter-Objects)) && (sip->flags & (SIF_BOMBER | SIF_FIGHTER))) {
14769                 if (aip->mode == AIM_NONE) {
14770                         aip->mode = AIM_CHASE;  //      This will cause the ship to move, if not attack.
14771                         aip->submode = SM_EVADE;
14772                 }
14773                 return;
14774         }
14775
14776         //      Maybe abort based on mode.
14777         switch (aip->mode) {
14778         case AIM_CHASE:
14779                 if (aip->submode == SM_ATTACK_FOREVER)
14780                         return;
14781
14782                 if ( hit_objp->type == OBJ_WEAPON ) {
14783                         if ( ai_big_maybe_enter_strafe_mode(objp_ship, OBJ_INDEX(hit_objp), 1) )
14784                                 return;
14785                 }
14786
14787         case AIM_GUARD:
14788                 //      If in guard mode and far away from guard object, don't pursue guy that hit me.
14789                         if ((aip->guard_objnum != -1) && (aip->guard_signature == Objects[aip->guard_objnum].signature)) {
14790                                 if (vm_vec_dist_quick(&objp_ship->pos, &Objects[aip->guard_objnum].pos) > 500.0f) {
14791                                         return;
14792                                 }
14793                         }
14794         case AIM_STILL:
14795         case AIM_STAY_NEAR:
14796                 // Note: Dealt with above, at very top.  case AIM_PLAY_DEAD:
14797         case AIM_STRAFE:
14798                 break;
14799         case AIM_EVADE_WEAPON:
14800         case AIM_EVADE:
14801         case AIM_GET_BEHIND:
14802         case AIM_AVOID:
14803         case AIM_DOCK:
14804         case AIM_BIGSHIP:
14805         case AIM_PATH:
14806         case AIM_NONE:
14807         case AIM_BAY_DEPART:
14808         case AIM_SENTRYGUN:
14809                 return;
14810         case AIM_BAY_EMERGE:
14811                 // If just leaving the docking bay, don't react to enemy fire... just keep flying away from docking bay
14812                 if ( (Missiontime - aip->submode_start_time) < 5*F1_0 ) {
14813                         return;
14814                 }
14815                 break;
14816         case AIM_WAYPOINTS:
14817                 if (sip->flags & (SIF_FIGHTER | SIF_BOMBER))
14818                         break;
14819                 else
14820                         return;
14821                 break;
14822         case AIM_SAFETY:
14823                 if ((aip->submode != AISS_1) || (Missiontime - aip->submode_start_time > i2f(1))) {
14824                         aip->submode = AISS_1;
14825                         aip->submode_start_time = Missiontime;
14826                 }
14827                 return;
14828                 break;
14829         case AIM_WARP_OUT:
14830                 return;
14831                 break;
14832         default:
14833                 Int3(); //      Bogus mode!
14834         }
14835
14836         if (timestamp_elapsed(aip->ok_to_target_timestamp))
14837                 aip->ai_flags &= ~AIF_FORMATION;                        //      If flying in formation, bug out!
14838
14839         aip->hitter_objnum = hitter_objnum;
14840         aip->hitter_signature = Objects[hitter_objnum].signature;
14841
14842         //      If the hitter is not on the same team as the hittee, do some stuff.
14843         if (shipp->team != Ships[objp_hitter->instance].team) {
14844                 //nprintf(("AI", "Object %i attacking %i, who just hit him!\n", objp_ship-Objects, hitter_objnum));
14845
14846                 if ((hitter_objnum != aip->target_objnum) && (sip->flags & (SIF_FIGHTER | SIF_BOMBER))) {
14847                         maybe_set_dynamic_chase(aip, hitter_objnum);
14848                         maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14849                 } else {
14850                         if ((aip->mode == AIM_CHASE) && ((objp_ship->hull_strength/sip->initial_hull_strength > 0.9f) || (get_shield_strength(objp_ship)/sip->shields > 0.8f))) {
14851                                 switch (aip->submode) {
14852                                 case SM_ATTACK:
14853                                 case SM_SUPER_ATTACK:
14854                                 case SM_GET_AWAY:
14855                                         break;
14856                                 default:
14857                                         if (sip->flags & (SIF_FIGHTER | SIF_BOMBER)) {
14858                                                 maybe_set_dynamic_chase(aip, hitter_objnum);
14859                                         }
14860                                         maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14861                                         break;
14862                                 }
14863                         } else if (aip->mode == AIM_CHASE) {
14864                                 switch (aip->submode) {
14865                                 case SM_ATTACK:
14866                                         aip->submode = SM_EVADE;
14867                                         aip->submode_start_time = Missiontime;
14868                                         break;
14869                                 case SM_SUPER_ATTACK:
14870                                         if (Missiontime - aip->submode_start_time > i2f(1)) {
14871                                                 aip->submode = SM_EVADE;
14872                                                 aip->submode_start_time = Missiontime;
14873                                         }
14874                                         break;
14875                                 case SM_EVADE_BRAKE:
14876                                         break;
14877                                 case SM_EVADE_SQUIGGLE:
14878                                         aip->submode = SM_EVADE;
14879                                         aip->submode_start_time = Missiontime;
14880                                         break;
14881                                 default:
14882                                         if (sip->flags & (SIF_BOMBER | SIF_FIGHTER)) {
14883                                                 maybe_set_dynamic_chase(aip, hitter_objnum);
14884                                                 maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14885                                         }
14886
14887                                         break;
14888                                 }
14889                         } else {
14890                                 // AL 3-15-98: Prevent escape pods from entering chase mode
14891                                 if ( (sip->flags & (SIF_BOMBER | SIF_FIGHTER)) ) {
14892                                         maybe_set_dynamic_chase(aip, hitter_objnum);
14893                                 }
14894                                 maybe_afterburner_after_ship_hit(objp_ship, aip, &Objects[hitter_objnum]);
14895                         }
14896                 }
14897         }
14898 }
14899
14900 //      Ship shipnum has been destroyed.
14901 //      Cleanup.
14902 // the parameter 'method' is used to tell is this ship was destroyed or it departed normally.
14903 // This function will get called in either case, and there are things that should be done if
14904 // the ship actually gets destroyed which shouldn't get done if it departed.
14905 void ai_ship_destroy(int shipnum, int method)
14906 {
14907         int             objnum;
14908         object  *other_objp;
14909         ship            *shipp;
14910         ship_obj        *so;
14911         ai_info *dead_aip;
14912
14913         SDL_assert((shipnum >= 0) && (shipnum < MAX_SHIPS));
14914         objnum = Ships[shipnum].objnum;
14915         dead_aip = &Ai_info[Ships[shipnum].ai_index];
14916
14917         // if I was getting repaired, or awaiting repair, then cleanup the repair mode.  When awaiting repair, the dock_objnum
14918         // is -1.  When the support ship is on the way, the dock_objnum >= 0 (points to support ship).
14919         if ( dead_aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED) ) {
14920                 if ( dead_aip->dock_objnum >= 0 )
14921                         ai_do_objects_repairing_stuff( &Objects[objnum], &Objects[dead_aip->dock_objnum], REPAIR_INFO_END);
14922                 else
14923                         ai_do_objects_repairing_stuff( &Objects[objnum], NULL, REPAIR_INFO_END );
14924         }
14925
14926         //      For all objects that had this ship as a target, wipe it out, forcing find of a new enemy.
14927         for ( so = GET_FIRST(&Ship_obj_list); so != END_OF_LIST(&Ship_obj_list); so = GET_NEXT(so) ) {
14928                 other_objp = &Objects[so->objnum];
14929                 SDL_assert(other_objp->instance != -1);
14930
14931                 shipp = &Ships[other_objp->instance];
14932                 SDL_assert(shipp->ai_index != -1);
14933
14934                 ai_info *aip = &Ai_info[shipp->ai_index];
14935
14936                 // MWA 2/11/98
14937                 // code commented out below is taken care of in ai_cleanup_dock_mode when gets called when the
14938                 // support ship starts it's death roll.
14939
14940                 //      If the destroyed ship was on its way to repair the current ship
14941                 if (aip->dock_objnum == objnum) {
14942
14943                         // clean up the flags for any kind of docking mode.  If aip was part of a goal of dock/undock
14944                         // then it will get cleaned up by the goal code.
14945                         ai_do_objects_undocked_stuff( other_objp, NULL );
14946
14947                         if ( aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED) ) {
14948                                 int abort_reason;
14949                                 if ( method == SEF_DEPARTED ) {
14950                                         abort_reason = REPAIR_INFO_ABORT;
14951                                 } else {
14952                                         abort_reason = REPAIR_INFO_KILLED;
14953                                 }
14954                                 ai_do_objects_repairing_stuff( other_objp, NULL, abort_reason );
14955                         }
14956                 }
14957
14958                 if (aip->target_objnum == objnum) {
14959                         set_target_objnum(aip, -1);
14960                         //      If this ship had a dynamic goal of chasing the dead ship, clear the dynamic goal.
14961                         if (aip->resume_goal_time != -1)
14962                                 aip->active_goal = AI_GOAL_NONE;
14963                 }
14964
14965                 if (aip->goal_objnum == objnum) {
14966                         aip->goal_objnum = -1;
14967                         aip->goal_signature = -1;
14968                 }
14969
14970                 if (aip->guard_objnum == objnum) {
14971                         aip->guard_objnum = -1;
14972                         aip->guard_signature = -1;
14973                 }
14974
14975                 if ((aip->guard_wingnum != -1) && (aip->guard_wingnum == Ai_info[Ships[Objects[objnum].instance].ai_index].wing)) {
14976                         if (aip->guard_wingnum != aip->wing)
14977                                 ai_set_guard_wing(other_objp, aip->guard_wingnum);
14978                 }
14979
14980                 if (aip->hitter_objnum == objnum)
14981                         aip->hitter_objnum = -1;
14982
14983         }
14984
14985 }
14986
14987 /*
14988 //      Interface function to goals code.
14989 //      Make object *objp fly to point *vp and warp out.
14990 void ai_warp_out(object *objp, vector *vp)
14991 {
14992         ai_info *aip;
14993
14994         aip = &Ai_info[Ships[objp->instance].ai_index];
14995
14996         if (aip->mode != AIM_WARP_OUT) {
14997                 ai_set_mode_warp_out(objp, aip);
14998         }
14999         float   dist;
15000         float   dot;
15001         vector  v2v;
15002         ai_info *aip;
15003
15004         dist = vm_vec_normalized_dir(&v2v, vp, &objp->pos);
15005
15006         if (dist < objp->radius + 5.0f) {
15007
15008                 // Start the warp out effect 
15009                 shipfx_warpout_start(objp);
15010
15011         } else {
15012                 dot = vm_vec_dot(&objp->orient.v.fvec, &v2v);
15013
15014                 aip = &Ai_info[Ships[objp->instance].ai_index];
15015
15016                 if (dist > 500.0f)
15017                         accelerate_ship(aip, 1.0f);
15018                 else
15019                         accelerate_ship(aip, (3*dot + 1.0f)/4.0f);
15020
15021                 turn_towards_point(objp, vp, NULL, 0.0f);
15022         }
15023 }
15024 */
15025
15026
15027 //      Do stuff at start of deathroll.
15028 void ai_deathroll_start(object *ship_obj)
15029 {
15030         ai_info *aip;
15031         ship            *shipp, *other_ship;
15032
15033         shipp = &Ships[ship_obj->instance];
15034         aip = &Ai_info[shipp->ai_index];
15035
15036         // mark object we are docked with so we can do damage and separate during deathroll
15037         // keep dock_objnum_when_dead from being changed if already set (only allow to be set when -1)
15038         if (Ships[ship_obj->instance].dock_objnum_when_dead == -1) {
15039                 Ships[ship_obj->instance].dock_objnum_when_dead = aip->dock_objnum;
15040                 // set other_ship dock_objnum_when_dead, if other_ship exits.
15041                 if (Ships[ship_obj->instance].dock_objnum_when_dead != -1) {
15042                         other_ship = &Ships[Objects[aip->dock_objnum].instance];
15043                         other_ship->dock_objnum_when_dead = shipp->objnum;
15044                 }
15045         }
15046
15047         ai_cleanup_dock_mode(aip, shipp);
15048
15049         aip->mode = AIM_NONE;
15050 }
15051
15052 //      Object *requester_objp tells rearm ship to abort rearm.
15053 //      Returns true if it succeeded, else false.
15054 //      To succeed means you were previously rearming.
15055 int ai_abort_rearm_request(object *requester_objp)
15056 {
15057         ship            *requester_shipp;
15058         ai_info *requester_aip;
15059
15060         SDL_assert(requester_objp->type == OBJ_SHIP);
15061         if(requester_objp->type != OBJ_SHIP){
15062                 return 0;
15063         }
15064         SDL_assert((requester_objp->instance >= 0) && (requester_objp->instance < MAX_SHIPS));  
15065         if((requester_objp->instance < 0) || (requester_objp->instance >= MAX_SHIPS)){
15066                 return 0;
15067         }
15068         requester_shipp = &Ships[requester_objp->instance];
15069         SDL_assert((requester_shipp->ai_index >= 0) && (requester_shipp->ai_index < MAX_AI_INFO));              
15070         if((requester_shipp->ai_index < 0) || (requester_shipp->ai_index >= MAX_AI_INFO)){
15071                 return 0;
15072         }       
15073         requester_aip = &Ai_info[requester_shipp->ai_index];
15074         
15075         if (requester_aip->ai_flags & (AIF_AWAITING_REPAIR | AIF_BEING_REPAIRED)){
15076
15077                 // dock_objnum is always valid once a rearm repair has been requested.  It points to the
15078                 // ship that is coming to repair me.
15079                 if (requester_aip->dock_objnum != -1) {
15080                         object  *repair_objp;
15081                         ai_info *repair_aip;
15082
15083                         repair_objp = &Objects[requester_aip->dock_objnum];
15084                         repair_aip = &Ai_info[Ships[repair_objp->instance].ai_index];
15085
15086                         //      Make sure signatures match.  This prevents nasty bugs in which an object
15087                         //      that was repairing another is destroyed and is replaced by another ship
15088                         //      before this code comes around.
15089                         if (repair_objp->signature == requester_aip->dock_signature) {
15090
15091                                 SDL_assert( repair_objp->type == OBJ_SHIP );
15092
15093                                 // if support ship is in the process of undocking, don't do anything.
15094                                 if ( repair_aip->submode < AIS_UNDOCK_0 ) {
15095                                         ai_do_objects_repairing_stuff( requester_objp, repair_objp, REPAIR_INFO_ABORT );
15096
15097                                         if ( repair_aip->submode == AIS_DOCK_4 )
15098                                                 repair_aip->submode = AIS_UNDOCK_0;
15099                                         else
15100                                                 repair_aip->submode = AIS_UNDOCK_3;
15101
15102                                         repair_aip->submode_start_time = Missiontime;
15103                                 } else {
15104                                         nprintf(("AI", "Not aborting rearm since already undocking\n"));
15105                                 }
15106                         }
15107                 } else {
15108                         // setting these flags is the safe things to do.  There may not be a corresponding repair
15109                         // ship for this guys since a repair ship may be currently repairing someone else.
15110                         ai_do_objects_repairing_stuff( requester_objp, NULL, REPAIR_INFO_ABORT );
15111
15112                         // try and remove this guy from an arriving support ship.
15113                         mission_remove_scheduled_repair(requester_objp);
15114                 }
15115
15116                 return 1;
15117         } else if ( requester_aip->ai_flags & AIF_REPAIRING ) {
15118                 // a support ship can request to abort when he is told to do something else (like warp out).
15119                 // see if this support ships goal_objnum is valid.  If so, then issue this ai_abort comment
15120                 // for the ship that he is enroute to repair
15121                 if ( requester_aip->goal_objnum != -1 ) {
15122                         int val;
15123
15124                         val = ai_abort_rearm_request( &Objects[requester_aip->goal_objnum] );
15125                         return val;
15126                 }
15127         }
15128
15129         return 0;
15130 }
15131
15132 // function which gets called from ai-issue_rearm_request and from code in missionparse.cpp
15133 // to actually issue the rearm goal (support_obj to rearm requester_obj);
15134 void ai_add_rearm_goal( object *requester_objp, object *support_objp )
15135 {
15136         ship *support_shipp, *requester_shipp;
15137         ai_info *support_aip, *requester_aip;
15138
15139         support_shipp = &Ships[support_objp->instance];
15140         requester_shipp = &Ships[requester_objp->instance];
15141         requester_aip = &Ai_info[requester_shipp->ai_index];
15142
15143         SDL_assert( support_shipp->ai_index != -1 );
15144         support_aip = &Ai_info[support_shipp->ai_index];
15145
15146         // if the requester is a player object, issue the order as the squadmate messaging code does.  Doing so
15147         // ensures that the player get a higher priority!
15148         requester_aip->ai_flags |= AIF_AWAITING_REPAIR; //      Tell that I'm awaiting repair.
15149         if ( requester_objp->flags & OF_PLAYER_SHIP )
15150                 ai_add_ship_goal_player( AIG_TYPE_PLAYER_SHIP, AI_GOAL_REARM_REPAIR, -1, requester_shipp->ship_name, support_aip );
15151         else
15152                 ai_add_goal_ship_internal( support_aip, AI_GOAL_REARM_REPAIR, requester_shipp->ship_name, -1, -1 );
15153
15154 }
15155
15156 //      Object *requester_objp requests rearming.
15157 //      Returns objnum of ship coming to repair requester on success
15158 //      Success means you found someone to rearm you and you weren't previously rearming.
15159 int ai_issue_rearm_request(object *requester_objp)
15160 {
15161         object  *objp;
15162         ship            *requester_shipp;
15163         ai_info *requester_aip;
15164
15165         SDL_assert(requester_objp->type == OBJ_SHIP);
15166         SDL_assert((requester_objp->instance >= 0) && (requester_objp->instance < MAX_SHIPS));
15167         requester_shipp = &Ships[requester_objp->instance];
15168         SDL_assert((requester_shipp->ai_index >= 0) && (requester_shipp->ai_index < MAX_AI_INFO));
15169         requester_aip = &Ai_info[requester_shipp->ai_index];
15170         
15171         //      Make sure not already awaiting repair.
15172         if (requester_aip->ai_flags & AIF_AWAITING_REPAIR) {
15173                 nprintf(("AI", "Ship %s already awaiting rearm by ship %s.\n", requester_shipp->ship_name, &Ships[Objects[requester_aip->dock_objnum].instance].ship_name));    
15174                 return -1;
15175         }
15176
15177         if ( !is_support_allowed(requester_objp) )
15178                 return -1;
15179
15180         //nprintf(("AI", "Ship %s requesting rearming.\n", requester_shipp->ship_name));
15181         requester_aip->next_rearm_request_timestamp = timestamp(NEXT_REARM_TIMESTAMP);  //      Might request again after this much time.
15182
15183         // call ship_find_repair_ship to get a support ship.  If none is found, then we will warp one in.  This
15184         // function will return the next available ship which can repair requester
15185         objp = ship_find_repair_ship( requester_objp );
15186         ai_do_objects_repairing_stuff( requester_objp, objp, REPAIR_INFO_QUEUE );
15187         if ( objp ) {
15188
15189                 // MWA 5/14/98 -- moved next item into the ai_do_objects_repairing_stuff function so that clients
15190                 // would properly update their hud support view
15191                 //ai_add_rearm_goal( requester_objp, objp );
15192                 return OBJ_INDEX(objp);
15193
15194         } else {
15195                 // call to warp in repair ship!!!!  for now, warp in any number of ships needed.  Should cap it to
15196                 // some reasonable max (or let support ships warp out).  We should assume here that ship_find_repair_ship()
15197                 // would have returned a valid object if there are too many support ships already in the mission
15198                 mission_warp_in_support_ship( requester_objp );
15199
15200                 return -1;
15201         }
15202
15203 }
15204
15205 // make objp rearm and repair goal_objp
15206 void ai_rearm_repair( object *objp, object  *goal_objp, int priority, int docker_index, int dockee_index )
15207 {
15208         ai_info *aip, *goal_aip;
15209
15210         aip = &Ai_info[Ships[objp->instance].ai_index];
15211         aip->goal_objnum = goal_objp-Objects;
15212
15213         // nprintf(("AI", "Ship %s preparing to rearm ship %s.\n", shipp->ship_name, requester_shipp->ship_name));
15214
15215         ai_dock_with_object(objp, goal_objp, priority, AIDO_DOCK, docker_index, dockee_index);
15216         aip->ai_flags |= AIF_REPAIRING;                                         //      Tell that repair guy is busy trying to repair someone.
15217
15218         goal_aip = &Ai_info[Ships[goal_objp->instance].ai_index];
15219         goal_aip->dock_objnum = objp-Objects;           //      Tell which object is coming to repair.
15220         goal_aip->dock_signature = objp->signature;
15221
15222         ai_do_objects_repairing_stuff( goal_objp, objp, REPAIR_INFO_ONWAY );
15223
15224         goal_aip->abort_rearm_timestamp = timestamp(NEXT_REARM_TIMESTAMP*3/2);
15225 }
15226
15227 // Given a dockee object and the index of the dockbay for that object (ie the dockbay index
15228 // into polymodel->dockbays[] for the model associated with the object), return the index
15229 // of a path_num associated with than dockbay (this is an index into polymodel->paths[])
15230 int ai_return_path_num_from_dockbay(object *dockee_objp, int dockbay_index)
15231 {
15232         if ( dockbay_index < 0 || dockee_objp == NULL ) {
15233                 Int3();         // should never happen
15234                 return -1;
15235         }
15236
15237         if ( dockee_objp->type == OBJ_SHIP ) {
15238                 int                     path_num;
15239                 polymodel       *pm;
15240
15241                 pm = model_get( Ships[dockee_objp->instance].modelnum );
15242
15243                 // sanity checks
15244                 SDL_assert(pm->n_docks > dockbay_index);
15245                 SDL_assert(pm->docking_bays[dockbay_index].num_spline_paths > 0);
15246                 SDL_assert(pm->docking_bays[dockbay_index].splines != NULL);
15247                 if(pm->n_docks <= dockbay_index){
15248                         return -1;
15249                 }
15250                 if(pm->docking_bays[dockbay_index].num_spline_paths <= 0){
15251                         return -1;
15252                 }
15253                 if(pm->docking_bays[dockbay_index].splines == NULL){
15254                         return -1;
15255                 }
15256
15257                 // We only need to return one path for the dockbay, so return the first
15258                 path_num = pm->docking_bays[dockbay_index].splines[0];
15259                 return path_num;
15260         } else {
15261                 return -1;
15262         }
15263 }
15264
15265 //      Actually go ahead and fire the synaptics.
15266 void cheat_fire_synaptic(object *objp, ship *shipp, ai_info *aip)
15267 {
15268         ship_weapon     *swp;
15269         swp = &shipp->weapons;
15270         int     current_bank = swp->current_secondary_bank;
15271
15272         ai_select_secondary_weapon(objp, swp, WIF_SPAWN, 0);
15273         if (timestamp_elapsed(swp->next_secondary_fire_stamp[current_bank])) {
15274                 if (ship_fire_secondary(objp)) {
15275                         nprintf(("AI", "ship %s cheat fired synaptic!\n", shipp->ship_name));
15276                         swp->next_secondary_fire_stamp[current_bank] = timestamp(2500);
15277                 }
15278         }
15279 }
15280
15281 //      For the subspace mission (sm3-09a)
15282 //              for delta wing
15283 //                      if they're sufficiently far into the mission
15284 //                              if they're near one or more enemies
15285 //                                      every so often
15286 //                                              fire a synaptic if they have one.
15287 void maybe_cheat_fire_synaptic(object *objp, ai_info *aip)
15288 {
15289         //      Only do in subspace missions.
15290         if ( The_mission.flags & MISSION_FLAG_SUBSPACE )        {
15291                 ship    *shipp;
15292                 int     num, time;
15293
15294                 shipp = &Ships[objp->instance];
15295
15296                 if (!(SDL_strncasecmp(shipp->ship_name, NOX("delta"), 5))) {
15297                         num = shipp->ship_name[6] - '1';
15298
15299                         if ((num >= 0) && (num <= 3)) {
15300                                 time = Missiontime >> 16;       //      Convert to seconds.
15301
15302                                 time -= 2*60;   //      Subtract off two minutes.
15303
15304                                 if (time > 0) {
15305                                         int modulus = 17 + num*3;
15306
15307                                         if ((time % modulus) < 2) {
15308                                                 int count = num_nearby_fighters(get_enemy_team_mask(OBJ_INDEX(objp)), &objp->pos, 1500.0f);
15309
15310                                                 if (count > 0) {
15311                                                         cheat_fire_synaptic(objp, shipp, aip);
15312                                                 }
15313                                         }
15314                                 }
15315                         }
15316                 }
15317         }
15318
15319 }
15320