Debian Codegraph @

similar/main/ai.cpp

raw
1 /*
2 * Portions of this file are copyright Rebirth contributors and licensed as
3 * described in COPYING.txt.
4 * Portions of this file are copyright Parallax Software and licensed
5 * according to the Parallax license below.
6 * See COPYING.txt for license details.
7
8 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
9 SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
10 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
11 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
12 IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
13 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
14 FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
15 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
16 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
17 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
18 */
19
20 /*
21 *
22 * Autonomous Individual movement.
23 *
24 */
25
26 #include <algorithm>
27 #include <cstdlib>
28 #include <stdio.h>
29 #include <time.h>
30 #include <optional>
31
32 #include "inferno.h"
33 #include "game.h"
34 #include "console.h"
35 #include "3d.h"
36
37 #include "object.h"
38 #include "dxxerror.h"
39 #include "ai.h"
40 #include "escort.h"
41 #include "laser.h"
42 #include "fvi.h"
43 #include "physfsx.h"
44 #include "physfs-serial.h"
45 #include "robot.h"
46 #include "bm.h"
47 #include "weapon.h"
48 #include "physics.h"
49 #include "collide.h"
50 #include "player.h"
51 #include "wall.h"
52 #include "vclip.h"
53 #include "fireball.h"
54 #include "morph.h"
55 #include "effects.h"
56 #include "sounds.h"
57 #include "gameseg.h"
58 #include "cntrlcen.h"
59 #include "mission.h"
60 #include "multibot.h"
61 #include "multi.h"
62 #include "gameseq.h"
63 #include "powerup.h"
64 #include "args.h"
65 #include "fuelcen.h"
66 #include "controls.h"
67 #include "kconfig.h"
68
69 #if DXX_USE_EDITOR
70 #include "editor/editor.h"
71 #include "editor/esegment.h"
72 #endif
73
74 //added 05/17/99 Matt Mueller
75 #include "u_mem.h"
76 //end addition -MM
77
78 #include "compiler-range_for.h"
79 #include "partial_range.h"
80 #include "segiter.h"
81 #include "d_construct.h"
82 #include "d_enumerate.h"
83 #include "d_levelstate.h"
84 #include <utility>
85
86 using std::min;
87
88 namespace dsx {
89
90 const object *Ai_last_missile_camera;
91
92 namespace {
93 static void init_boss_segments(const segment_array &segments, const object &boss_objnum, d_level_shared_boss_state::special_segment_array_t &a, int size_check, int one_wall_hack);
94 static void ai_multi_send_robot_position(object &objnum, int force);
95
96 /* Computing the robot gun point is moderately expensive. Defer computing it
97 * until needed, and store the computed value in a std::optional. When the
98 * optional is valueless, the gun point has not yet been computed.
99 */
100 class robot_gun_point : std::optional<vms_vector>
101 {
102 using base_type = std::optional<vms_vector>;
103 public:
104 using base_type::has_value;
105 const vms_vector &build(const robot_info &robptr, const object_base &obj, robot_gun_number gun_num);
106 };
107
108 /* If the gun point was previously computed, return a reference to the
109 * previously computed value.
110 *
111 * If the gun point was not yet computed, compute it here, and return a
112 * reference to the computed value.
113 */
114 const vms_vector &robot_gun_point::build(const robot_info &robptr, const object_base &obj, const robot_gun_number gun_num)
115 {
116 if (!has_value())
117 {
118 vms_vector gun_point;
119 calc_gun_point(robptr, gun_point, obj, gun_num);
120 emplace(gun_point);
121 }
122 return **this;
123 }
124
125 #if DXX_BUILD_DESCENT == 1
126 constexpr fix BOSS_DEATH_SOUND_DURATION{0x2ae14}; // 2.68 seconds
127
128 #elif DXX_BUILD_DESCENT == 2
129 constexpr fix FIRE_AT_NEARBY_PLAYER_THRESHOLD{F1_0 * 40};
130 constexpr int FIRE_K{8}; // Controls average accuracy of robot firing. Smaller numbers make firing worse. Being power of 2 doesn't matter.
131
132 // ====================================================================================================================
133
134 constexpr fix MIN_LEAD_SPEED{F1_0 * 4};
135 constexpr fix MAX_LEAD_DISTANCE{F1_0 * 200};
136 constexpr fix LEAD_RANGE{F1_0 / 2};
137
138 /* Invalid robot ID numbers in Spew_bots must be at the end of their row. The
139 * corresponding count in Max_spew_bots will prevent the game from rolling a
140 * random index that loads the invalid robot ID number.
141 */
142 constexpr enumerated_array<std::array<robot_id, 3>, NUM_D2_BOSSES, boss_robot_index> Spew_bots{{{
143 {{robot_id{38}, robot_id{40}, robot_id{UINT8_MAX}}},
144 {{robot_id{37}, robot_id{UINT8_MAX}, robot_id{UINT8_MAX}}},
145 {{robot_id{43}, robot_id{57}, robot_id{UINT8_MAX}}},
146 {{robot_id{26}, robot_id{27}, robot_id{58}}},
147 {{robot_id{59}, robot_id{58}, robot_id{54}}},
148 {{robot_id{60}, robot_id{61}, robot_id{54}}},
149
150 {{robot_id{69}, robot_id{29}, robot_id{24}}},
151 {{robot_id{72}, robot_id{60}, robot_id{73}}}
152 }}};
153
154 constexpr enumerated_array<uint8_t, NUM_D2_BOSSES, boss_robot_index> Max_spew_bots{{{2, 1, 2, 3, 3, 3, 3, 3}}};
155 static fix Dist_to_last_fired_upon_player_pos;
156 #endif
157
158 static bool robot_gun_number_valid(const robot_info &robptr, const robot_gun_number current_gun)
159 {
160 return static_cast<uint8_t>(current_gun) < robptr.n_guns;
161 }
162
163 static robot_gun_number robot_advance_current_gun(const robot_info &robptr, const robot_gun_number gun)
164 {
165 const uint8_t next_gun = 1 + static_cast<uint8_t>(gun);
166 if (next_gun >= robptr.n_guns)
167 return robot_gun_number::_0;
168 return robot_gun_number{next_gun};
169 }
170
171 static robot_gun_number robot_advance_current_gun_prefer_second(const robot_info &robptr, const robot_gun_number gun)
172 {
173 const uint8_t next_gun = 1 + static_cast<uint8_t>(gun);
174 if (next_gun >= robptr.n_guns)
175 {
176 #if DXX_BUILD_DESCENT == 2
177 if (robptr.n_guns != 1 && robptr.weapon_type2 != weapon_none)
178 return robot_gun_number::_1;
179 else
180 #endif
181 return robot_gun_number::_0;
182 }
183 return robot_gun_number{next_gun};
184 }
185
186 }
187 }
188
189 namespace dcx {
190 namespace {
191 constexpr std::integral_constant<int, F1_0 * 8> CHASE_TIME_LENGTH{};
192 constexpr std::integral_constant<int, F1_0> Robot_sound_volume{};
193 constexpr fix ANIM_RATE{F1_0 / 16};
194 constexpr int DELTA_ANG_SCALE{16};
195 constexpr int OVERALL_AGITATION_MAX{100};
196 constexpr std::size_t MAX_AI_CLOAK_INFO{8}; // Must be a power of 2!
197
198 enum {
199 Flinch_scale = 4,
200 Attack_scale = 24,
201 };
202
203 constexpr std::array<robot_animation_state, 8> Mike_to_matt_xlate{{
204 robot_animation_state::rest, robot_animation_state::rest, robot_animation_state::alert, robot_animation_state::alert, robot_animation_state::flinch, robot_animation_state::fire, robot_animation_state::recoil, robot_animation_state::rest
205 }};
206
207 #define BOSS_CLOAK_DURATION Boss_cloak_duration
208 constexpr fix BOSS_DEATH_DURATION{F1_0 * 6};
209 // Amount of time since the current robot was last processed for things such as movement.
210 // It is not valid to use FrameTime because robots do not get moved every frame.
211
212 // ---------- John: These variables must be saved as part of gamesave. --------
213 static int Overall_agitation;
214 static std::array<ai_cloak_info, MAX_AI_CLOAK_INFO> Ai_cloak_info;
215
216 fix build_savegametime_from_gametime(const fix64 gametime, const fix64 t)
217 {
218 const auto delta_time = t - gametime;
219 if (delta_time < F1_0 * (-18000))
220 return fix{F1_0 * (-18000)};
221 return static_cast<fix>(delta_time);
222 }
223
224 }
225 point_seg_array_t Point_segs;
226 point_seg_array_t::iterator Point_segs_free_ptr;
227
228 // ------ John: End of variables which must be saved as part of gamesave. -----
229
230 // 0 mech
231 // 1 green claw
232 // 2 spider
233 // 3 josh
234 // 4 violet
235 // 5 cloak vulcan
236 // 6 cloak mech
237 // 7 brain
238 // 8 onearm
239 // 9 plasma
240 // 10 toaster
241 // 11 bird
242 // 12 missile bird
243 // 13 polyhedron
244 // 14 baby spider
245 // 15 mini boss
246 // 16 super mech
247 // 17 shareware boss
248 // 18 cloak-green ; note, gating in this guy benefits player, cloak objects
249 // 19 vulcan
250 // 20 toad
251 // 21 4-claw
252 // 22 quad-laser
253 // 23 super boss
254
255 // byte Super_boss_gate_list[] = {0, 1, 2, 9, 11, 16, 18, 19, 21, 22, 0, 9, 9, 16, 16, 18, 19, 19, 22, 22};
256 constexpr std::array<robot_id, 21> Super_boss_gate_list{{
257 robot_id{0},
258 robot_id{1},
259 robot_id{8},
260 robot_id{9},
261 robot_id{10},
262 robot_id{11},
263 robot_id{12},
264 robot_id{15},
265 robot_id{16},
266 robot_id{18},
267 robot_id{19},
268 robot_id{20},
269 robot_id{22},
270 robot_id{0},
271 robot_id{8},
272 robot_id{11},
273 robot_id{19},
274 robot_id{20},
275 robot_id{8},
276 robot_id{20},
277 robot_id{8},
278 }};
279
280 std::optional<ai_static_state> build_ai_state_from_untrusted(const uint8_t untrusted)
281 {
282 switch (untrusted)
283 {
284 case static_cast<uint8_t>(ai_static_state::AIS_NONE):
285 case static_cast<uint8_t>(ai_static_state::AIS_REST):
286 case static_cast<uint8_t>(ai_static_state::AIS_SRCH):
287 case static_cast<uint8_t>(ai_static_state::AIS_LOCK):
288 case static_cast<uint8_t>(ai_static_state::AIS_FLIN):
289 case static_cast<uint8_t>(ai_static_state::AIS_FIRE):
290 case static_cast<uint8_t>(ai_static_state::AIS_RECO):
291 case static_cast<uint8_t>(ai_static_state::AIS_ERR_):
292 return ai_static_state{untrusted};
293 default:
294 return std::nullopt;
295 }
296 }
297
298 }
299 #define MAX_GATE_INDEX (Super_boss_gate_list.size())
300
301 #if DXX_BUILD_DESCENT == 2
302 namespace dsx {
303
304
305 // ------ John: End of variables which must be saved as part of gamesave. -----
306
307 vms_vector Last_fired_upon_player_pos;
308
309
310 // -- ubyte Boss_cloaks[NUM_D2_BOSSES] = {1,1,1,1,1,1}; // Set byte if this boss can cloak
311
312 constexpr boss_flags_t Boss_teleports{{{1,1,1,1,1,1, 1,1}}}; // Set byte if this boss can teleport
313 const boss_flags_t Boss_spew_more{{{0,1,0,0,0,0, 0,0}}}; // If set, 50% of time, spew two bots.
314 const boss_flags_t Boss_spews_bots_energy{{{1,1,0,1,0,1, 1,1}}}; // Set byte if boss spews bots when hit by energy weapon.
315 const boss_flags_t Boss_spews_bots_matter{{{0,0,1,1,1,1, 0,1}}}; // Set byte if boss spews bots when hit by matter weapon.
316 const boss_flags_t Boss_invulnerable_energy{{{0,0,1,1,0,0, 0,0}}}; // Set byte if boss is invulnerable to energy weapons.
317 const boss_flags_t Boss_invulnerable_matter{{{0,0,0,0,1,1, 1,0}}}; // Set byte if boss is invulnerable to matter weapons.
318 const boss_flags_t Boss_invulnerable_spot{{{0,0,0,0,0,1, 0,1}}}; // Set byte if boss is invulnerable in all but a certain spot. (Dot product fvec|vec_to_collision < BOSS_INVULNERABLE_DOT)
319
320 segnum_t Believed_player_seg;
321 }
322 #endif
323
324 namespace dcx {
325
326 vms_vector Believed_player_pos;
327
328 namespace {
329
330 struct robot_to_player_visibility_state
331 {
332 vms_vector vec_to_player;
333 player_visibility_state visibility;
334 uint8_t initialized{0};
335 };
336
337 struct awareness_t : enumerated_array<player_awareness_type_t, MAX_SEGMENTS, segnum_t>
338 {
339 };
340
341 static int ai_evaded;
342
343 // This is set by a call to find_vector_intersection, which is a slow routine,
344 // so we don't want to call it again (for this object) unless we have to.
345 static vms_vector Hit_pos;
346
347 static bool silly_animation_angle(fixang vms_angvec::*const a, const vms_angvec &jp, const vms_angvec &pobjp, const int flinch_attack_scale, vms_angvec &goal_angles, vms_angvec &delta_angles)
348 {
349 const fix delta_angle = jp.*a - pobjp.*a;
350 if (!delta_angle)
351 return false;
352 goal_angles.*a = jp.*a;
353 const fix delta_anim_rate = (delta_angle >= F1_0/2)
354 ? -ANIM_RATE
355 : (delta_angle >= 0)
356 ? ANIM_RATE
357 : (delta_angle >= -F1_0/2)
358 ? -ANIM_RATE
359 : ANIM_RATE
360 ;
361 const fix delta_2 = (flinch_attack_scale != 1)
362 ? delta_anim_rate * flinch_attack_scale
363 : delta_anim_rate;
364 delta_angles.*a = delta_2 / DELTA_ANG_SCALE; // complete revolutions per second
365 return true;
366 }
367
368 static void frame_animation_angle(fixang vms_angvec::*const a, const fix frametime, const vms_angvec &deltaang, const vms_angvec &goalang, vms_angvec &curang)
369 {
370 fix delta_to_goal = goalang.*a - curang.*a;
371 if (delta_to_goal > 32767)
372 delta_to_goal = delta_to_goal - 65536;
373 else if (delta_to_goal < -32767)
374 delta_to_goal = 65536 + delta_to_goal;
375 if (delta_to_goal)
376 {
377 // Due to deltaang.*a being usually small values and frametime getting smaller with higher FPS, the usual use of fixmul will have scaled_delta_angle result in 0 way too often and long, making the robot animation run circles around itself. So multiply deltaang by DELTA_ANG_SCALE when passed to fixmul.
378 const fix scaled_delta_angle = fixmul(deltaang.*a * DELTA_ANG_SCALE, frametime); // fixmul(deltaang.*a, frametime) * DELTA_ANG_SCALE;
379 auto &ca = curang.*a;
380 if (abs(delta_to_goal) < abs(scaled_delta_angle))
381 ca = goalang.*a;
382 else
383 ca += scaled_delta_angle;
384 }
385 }
386
387 static void move_toward_vector_component_assign(fix vms_vector::*const p, const vms_vector &vec_goal, const fix frametime32, vms_vector &velocity)
388 {
389 velocity.*p = (velocity.*p / 2) + fixmul(vec_goal.*p, frametime32);
390 }
391
392 static void move_toward_vector_component_add(fix vms_vector::*const p, const vms_vector &vec_goal, const fix frametime64, const fix difficulty_scale, vms_vector &velocity)
393 {
394 velocity.*p += fixmul(vec_goal.*p, frametime64) * difficulty_scale / 4;
395 }
396
397 }
398
399 }
400
401 #define AIS_MAX 8
402 #define AIE_MAX 4
403
404 // Current state indicates where the robot current is, or has just done.
405 // Transition table between states for an AI object.
406 // First dimension is trigger event.
407 // Second dimension is current state.
408 // Third dimension is goal state.
409 // Result is new goal state.
410 // ERR_ means something impossible has happened.
411 constexpr std::array<
412 enumerated_array<
413 enumerated_array<ai_static_state, AI_MAX_STATE, ai_static_state>,
414 AI_MAX_STATE,
415 ai_static_state
416 >,
417 4> Ai_transition_table = {{
418 {{{
419 // Event = AIE_FIRE, a nearby object fired
420 // none rest srch lock flin fire reco // CURRENT is rows, GOAL is columns
421 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FIRE, AIS_RECO}}}, // none
422 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FIRE, AIS_RECO}}}, // rest
423 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FIRE, AIS_RECO}}}, // search
424 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FIRE, AIS_RECO}}}, // lock
425 {{{AIS_ERR_, AIS_REST, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FIRE, AIS_RECO}}}, // flinch
426 {{{AIS_ERR_, AIS_FIRE, AIS_FIRE, AIS_FIRE, AIS_FLIN, AIS_FIRE, AIS_RECO}}}, // fire
427 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FIRE, AIS_FIRE}}}, // recoil
428 }}},
429
430 // Event = AIE_HITT, a nearby object was hit (or a wall was hit)
431 {{{
432 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FIRE, AIS_RECO}}},
433 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FIRE, AIS_RECO}}},
434 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FIRE, AIS_RECO}}},
435 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FIRE, AIS_RECO}}},
436 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FLIN}}},
437 {{{AIS_ERR_, AIS_REST, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FIRE, AIS_RECO}}},
438 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FIRE, AIS_FIRE}}},
439 }}},
440
441 // Event = AIE_COLL, player collided with robot
442 {{{
443 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FIRE, AIS_RECO}}},
444 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FIRE, AIS_RECO}}},
445 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FIRE, AIS_RECO}}},
446 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FIRE, AIS_RECO}}},
447 {{{AIS_ERR_, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_LOCK, AIS_FLIN, AIS_FLIN}}},
448 {{{AIS_ERR_, AIS_REST, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FIRE, AIS_RECO}}},
449 {{{AIS_ERR_, AIS_LOCK, AIS_LOCK, AIS_LOCK, AIS_FLIN, AIS_FIRE, AIS_FIRE}}},
450 }}},
451
452 // Event = AIE_HURT, player hurt robot (by firing at and hitting it)
453 // Note, this doesn't necessarily mean the robot JUST got hit, only that that is the most recent thing that happened.
454 {{{
455 {{{AIS_ERR_, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN}}},
456 {{{AIS_ERR_, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN}}},
457 {{{AIS_ERR_, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN}}},
458 {{{AIS_ERR_, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN}}},
459 {{{AIS_ERR_, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN}}},
460 {{{AIS_ERR_, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN}}},
461 {{{AIS_ERR_, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN, AIS_FLIN}}},
462 }}}
463 }};
464
465 namespace dsx {
466
467 weapon_id_type get_robot_weapon(const robot_info &ri, const robot_gun_number gun_num)
468 {
469 #if DXX_BUILD_DESCENT == 1
470 (void)gun_num;
471 #elif DXX_BUILD_DESCENT == 2
472 if (ri.weapon_type2 != weapon_none && gun_num == robot_gun_number::_0)
473 return ri.weapon_type2;
474 #endif
475 return ri.weapon_type;
476 }
477
478 namespace {
479
480 static int ready_to_fire_weapon1(const ai_local &ailp, fix threshold)
481 {
482 return ailp.next_fire <= threshold;
483 }
484
485 static int ready_to_fire_weapon2(const robot_info &robptr, const ai_local &ailp, fix threshold)
486 {
487 #if DXX_BUILD_DESCENT == 1
488 (void)robptr;
489 (void)ailp;
490 (void)threshold;
491 return 0;
492 #elif DXX_BUILD_DESCENT == 2
493 if (robptr.weapon_type2 == weapon_none)
494 return 0;
495 return ailp.next_fire2 <= threshold;
496 #endif
497 }
498
499 // ----------------------------------------------------------------------------
500 // Return firing status.
501 // If ready to fire a weapon, return true, else return false.
502 // Ready to fire a weapon if next_fire <= 0 or next_fire2 <= 0.
503 static int ready_to_fire_any_weapon(const robot_info &robptr, const ai_local &ailp, fix threshold)
504 {
505 return ready_to_fire_weapon1(ailp, threshold) || ready_to_fire_weapon2(robptr, ailp, threshold);
506 }
507
508 }
509
510 // ---------------------------------------------------------------------------------------------------------------------
511 // Given a behavior, set initial mode.
512 ai_mode ai_behavior_to_mode(ai_behavior behavior)
513 {
514 switch (behavior) {
515 case ai_behavior::AIB_STILL:
516 return ai_mode::AIM_STILL;
517 case ai_behavior::AIB_NORMAL:
518 return ai_mode::AIM_CHASE_OBJECT;
519 case ai_behavior::AIB_RUN_FROM:
520 return ai_mode::AIM_RUN_FROM_OBJECT;
521 case ai_behavior::AIB_STATION:
522 return ai_mode::AIM_STILL;
523 #if DXX_BUILD_DESCENT == 1
524 case ai_behavior::AIB_HIDE:
525 return ai_mode::AIM_HIDE;
526 case ai_behavior::AIB_FOLLOW_PATH:
527 return ai_mode::AIM_FOLLOW_PATH;
528 #elif DXX_BUILD_DESCENT == 2
529 case ai_behavior::AIB_BEHIND:
530 return ai_mode::AIM_BEHIND;
531 case ai_behavior::AIB_SNIPE:
532 return ai_mode::AIM_STILL; // Changed, 09/13/95, MK, snipers are still until they see you or are hit.
533 case ai_behavior::AIB_FOLLOW:
534 return ai_mode::AIM_FOLLOW_PATH;
535 #endif
536 default: Int3(); // Contact Mike: Error, illegal behavior type
537 }
538
539 return ai_mode::AIM_STILL;
540 }
541
542 // ---------------------------------------------------------------------------------------------------------------------
543 // Call every time the player starts a new ship.
544 void ai_init_boss_for_ship(void)
545 {
546 #if DXX_BUILD_DESCENT == 2
547 auto &BossUniqueState = LevelUniqueObjectState.BossState;
548 BossUniqueState.Boss_hit_time = -F1_0*10;
549 #endif
550 }
551
552 namespace {
553
554 static void boss_init_all_segments(const segment_array &Segments, const object &boss_objnum)
555 {
556 auto &Boss_gate_segs = LevelSharedBossState.Gate_segs;
557 auto &Boss_teleport_segs = LevelSharedBossState.Teleport_segs;
558 if (!Boss_teleport_segs.empty())
559 return; // already have boss segs
560
561 init_boss_segments(Segments, boss_objnum, Boss_gate_segs, 0, 0);
562
563 init_boss_segments(Segments, boss_objnum, Boss_teleport_segs, 1, 0);
564 #if DXX_BUILD_DESCENT == 2
565 if (Boss_teleport_segs.size() < 2)
566 init_boss_segments(Segments, boss_objnum, Boss_teleport_segs, 1, 1);
567 #endif
568 }
569
570 }
571
572 // ---------------------------------------------------------------------------------------------------------------------
573 // initial_mode == -1 means leave mode unchanged.
574 void init_ai_object(const d_robot_info_array &Robot_info, const vmobjptridx_t objp, ai_behavior behavior, const imsegidx_t hide_segment)
575 {
576 auto &BossUniqueState = LevelUniqueObjectState.BossState;
577 auto &obj = *objp;
578 ai_static *const aip = &obj.ctype.ai_info;
579 ai_local *const ailp = &aip->ail;
580
581 *ailp = {};
582
583 if (static_cast<unsigned>(behavior) == 0) {
584 behavior = ai_behavior::AIB_NORMAL;
585 aip->behavior = behavior;
586 }
587
588 // mode is now set from the Robot dialog, so this should get overwritten.
589 ailp->mode = ai_mode::AIM_STILL;
590
591 ailp->previous_visibility = player_visibility_state::no_line_of_sight;
592
593 {
594 aip->behavior = behavior;
595 ailp->mode = ai_behavior_to_mode(aip->behavior);
596 }
597
598 auto &robptr = Robot_info[get_robot_id(obj)];
599 #if DXX_BUILD_DESCENT == 2
600 if (robot_is_companion(robptr)) {
601 auto &BuddyState = LevelUniqueObjectState.BuddyState;
602 BuddyState.Buddy_objnum = objp;
603 ailp->mode = ai_mode::AIM_GOTO_PLAYER;
604 }
605
606 if (robot_is_thief(robptr)) {
607 aip->behavior = ai_behavior::AIB_SNIPE;
608 ailp->mode = ai_mode::AIM_THIEF_WAIT;
609 }
610
611 if (robptr.attack_type) {
612 aip->behavior = ai_behavior::AIB_NORMAL;
613 ailp->mode = ai_behavior_to_mode(aip->behavior);
614 }
615 #endif
616
617 // This is astonishingly stupid! This routine gets called by matcens! KILL KILL KILL!!! Point_segs_free_ptr = Point_segs;
618
619 obj.mtype.phys_info.velocity = {};
620 ailp->player_awareness_time = 0;
621 ailp->player_awareness_type = player_awareness_type_t::PA_NONE;
622 aip->GOAL_STATE = AIS_SRCH;
623 if constexpr (DXX_HAVE_POISON || static_cast<uint8_t>(robot_gun_number::_0) != 0)
624 /* If memory poisoning is enabled, then CURRENT_GUN is undefined. Set
625 * it to a reasonable value here, because nothing else will assign it
626 * before use.
627 *
628 * If memory poisoning is disabled, then obj_create initialized
629 * CURRENT_GUN to 0 as part of clearing the newly allocated structure.
630 * If the value that would be written by an explicit initialization is
631 * 0, then avoid actually writing it.
632 */
633 aip->CURRENT_GUN = robot_gun_number::_0;
634 aip->CURRENT_STATE = AIS_REST;
635 ailp->time_player_seen = {GameTime64};
636 ailp->next_misc_sound_time = {GameTime64};
637 ailp->time_player_sound_attacked = {GameTime64};
638
639 aip->hide_segment = hide_segment;
640 ailp->goal_segment = hide_segment;
641 aip->hide_index = -1; // This means the path has not yet been created.
642 aip->cur_path_index = 0;
643
644 aip->SKIP_AI_COUNT = 0;
645
646 if (robptr.cloak_type == RI_CLOAKED_ALWAYS)
647 aip->CLOAKED = 1;
648 else
649 aip->CLOAKED = 0;
650
651 obj.mtype.phys_info.flags |= (PF_BOUNCE | PF_TURNROLL);
652
653 aip->REMOTE_OWNER = -1;
654
655 #if DXX_BUILD_DESCENT == 2
656 aip->dying_sound_playing = 0;
657 aip->dying_start_time = 0;
658 #endif
659 aip->danger_laser_num = object_none;
660
661 if (robptr.boss_flag != boss_robot_id::None
662 #if DXX_USE_EDITOR
663 && !EditorWindow
664 #endif
665 )
666 {
667 BossUniqueState = {};
668 boss_init_all_segments(Segments, obj);
669 }
670 }
671
672 // ---------------------------------------------------------------------------------------------------------------------
673 void init_ai_objects(const d_robot_info_array &Robot_info)
674 {
675 auto &BossUniqueState = LevelUniqueObjectState.BossState;
676 auto &Boss_gate_segs = LevelSharedBossState.Gate_segs;
677 auto &Boss_teleport_segs = LevelSharedBossState.Teleport_segs;
678 auto &Objects = LevelUniqueObjectState.Objects;
679 auto &vmobjptridx = Objects.vmptridx;
680 Point_segs_free_ptr = Point_segs.begin();
681 Boss_gate_segs.clear();
682 Boss_teleport_segs.clear();
683
684 range_for (const auto &&o, vmobjptridx)
685 {
686 auto &obj = *o;
687 if (obj.type == OBJ_ROBOT && obj.control_source == object::control_type::ai)
688 init_ai_object(Robot_info, o, obj.ctype.ai_info.behavior, obj.ctype.ai_info.hide_segment);
689 }
690
691 BossUniqueState.Boss_dying_sound_playing = 0;
692 BossUniqueState.Boss_dying = 0;
693
694 const auto Difficulty_level = underlying_value(GameUniqueState.Difficulty_level);
695 #define D1_Boss_gate_interval F1_0*5 - Difficulty_level*F1_0/2
696 #if DXX_BUILD_DESCENT == 1
697 GameUniqueState.Boss_gate_interval = D1_Boss_gate_interval;
698 #elif DXX_BUILD_DESCENT == 2
699 ai_do_cloak_stuff();
700
701 init_buddy_for_level();
702
703 if (EMULATING_D1)
704 {
705 LevelSharedBossState.Boss_cloak_interval = d_level_shared_boss_state::D1_Boss_cloak_interval::value;
706 LevelSharedBossState.Boss_teleport_interval = d_level_shared_boss_state::D1_Boss_teleport_interval::value;
707 GameUniqueState.Boss_gate_interval = D1_Boss_gate_interval;
708 }
709 else
710 {
711 GameUniqueState.Boss_gate_interval = F1_0*4 - Difficulty_level*i2f(2)/3;
712 if (Current_level_num == Current_mission->last_level)
713 {
714 LevelSharedBossState.Boss_teleport_interval = F1_0*10;
715 LevelSharedBossState.Boss_cloak_interval = F1_0*15; // Time between cloaks
716 } else
717 {
718 LevelSharedBossState.Boss_teleport_interval = F1_0*7;
719 LevelSharedBossState.Boss_cloak_interval = F1_0*10; // Time between cloaks
720 }
721 }
722 #endif
723 #undef D1_Boss_gate_interval
724 }
725
726 //-------------------------------------------------------------------------------------------
727 void ai_turn_towards_vector(const vms_vector &goal_vector, object_base &objp, fix rate)
728 {
729 // Not all robots can turn, eg, robot_id::special_reactor
730 if (rate == 0)
731 return;
732
733 if (objp.type == OBJ_ROBOT && get_robot_id(objp) == robot_id::baby_spider)
734 {
735 physics_turn_towards_vector(goal_vector, objp, rate);
736 return;
737 }
738
739 auto new_fvec = goal_vector;
740
741 const fix dot = vm_vec_build_dot(goal_vector, objp.orient.fvec);
742
743 if (dot < (F1_0 - FrameTime/2)) {
744 fix new_scale = fixdiv(FrameTime, rate);
745 vm_vec_scale(new_fvec, new_scale);
746 vm_vec_add2(new_fvec, objp.orient.fvec);
747 auto mag = vm_vec_normalize_quick(new_fvec);
748 if (mag < F1_0/256) {
749 new_fvec = goal_vector; // if degenerate vector, go right to goal
750 }
751 }
752
753 #if DXX_BUILD_DESCENT == 2
754 auto &Robot_info = LevelSharedRobotInfoState.Robot_info;
755 if (const auto Seismic_tremor_magnitude = LevelUniqueSeismicState.Seismic_tremor_magnitude)
756 {
757 fix scale;
758 scale = fixdiv(2*Seismic_tremor_magnitude, Robot_info[get_robot_id(objp)].mass);
759 vm_vec_scale_add2(new_fvec, make_random_vector(), scale);
760 }
761 #endif
762
763 {
764 /* Copy `objp.orient.rvec` into a temporary and pass the temporary,
765 * since it is undefined behavior to access `objp.orient` after the old
766 * object is destroyed until the new value is constructed.
767 */
768 const auto old_rvec{objp.orient.rvec};
769 reconstruct_at(objp.orient, vm_vector_to_matrix_r, new_fvec, old_rvec);
770 }
771 }
772
773 #if DXX_BUILD_DESCENT == 1
774 namespace {
775 static void ai_turn_randomly(const vms_vector &vec_to_player, object_base &obj, const fix rate, const player_visibility_state previous_visibility)
776 {
777 vms_vector curvec;
778
779 // Random turning looks too stupid, so 1/4 of time, cheat.
780 if (player_is_visible(previous_visibility))
781 if (d_rand() > 0x7400) {
782 ai_turn_towards_vector(vec_to_player, obj, rate);
783 return;
784 }
785 //--debug-- if (d_rand() > 0x6000)
786 //--debug-- Prevented_turns++;
787
788 curvec = obj.mtype.phys_info.rotvel;
789
790 curvec.y += F1_0/64;
791
792 curvec.x += curvec.y/6;
793 curvec.y += curvec.z/4;
794 curvec.z += curvec.x/10;
795
796 if (abs(curvec.x) > F1_0/8) curvec.x /= 4;
797 if (abs(curvec.y) > F1_0/8) curvec.y /= 4;
798 if (abs(curvec.z) > F1_0/8) curvec.z /= 4;
799
800 obj.mtype.phys_info.rotvel = curvec;
801
802 }
803 }
804 #endif
805
806 // Overall_agitation affects:
807 // Widens field of view. Field of view is in range 0..1 (specified in bitmaps.tbl as N/360 degrees).
808 // Overall_agitation/128 subtracted from field of view, making robots see wider.
809 // Increases distance to which robot will search to create path to player by Overall_agitation/8 segments.
810 // Decreases wait between fire times by Overall_agitation/64 seconds.
811
812
813 // --------------------------------------------------------------------------------------------------------------------
814 // Returns:
815 // 0 Player is not visible from object, obstruction or something.
816 // 1 Player is visible, but not in field of view.
817 // 2 Player is visible and in field of view.
818 // Note: Uses Believed_player_pos as player's position for cloak effect.
819 // NOTE: Will destructively modify *pos if *pos is outside the mine.
820 player_visibility_state player_is_visible_from_object(const d_robot_info_array &Robot_info, const vmobjptridx_t objp, vms_vector &pos, const fix field_of_view, const vms_vector &vec_to_player)
821 {
822 auto &obj = *objp;
823 fix dot;
824
825 #if DXX_BUILD_DESCENT == 2
826 // Assume that robot's gun tip is in same segment as robot's center.
827 if (obj.control_source == object::control_type::ai)
828 obj.ctype.ai_info.SUB_FLAGS &= ~SUB_FLAGS_GUNSEG;
829 #endif
830
831 segnum_t startseg;
832 if (pos.x != obj.pos.x || pos.y != obj.pos.y || pos.z != obj.pos.z)
833 {
834 auto &Segments = LevelSharedSegmentState.get_segments();
835 const auto &&segnum = find_point_seg(LevelSharedSegmentState, pos, Segments.vcptridx(obj.segnum));
836 if (segnum == segment_none) {
837 startseg = obj.segnum;
838 pos = obj.pos;
839 auto &robptr = Robot_info[get_robot_id(obj)];
840 move_towards_segment_center(robptr, LevelSharedSegmentState, obj);
841 } else
842 {
843 #if DXX_BUILD_DESCENT == 2
844 if (segnum != obj.segnum) {
845 if (obj.control_source == object::control_type::ai)
846 obj.ctype.ai_info.SUB_FLAGS |= SUB_FLAGS_GUNSEG;
847 }
848 #endif
849 startseg = segnum;
850 }
851 } else
852 startseg = obj.segnum;
853 fvi_info Hit_data;
854 const auto Hit_type = find_vector_intersection(fvi_query{
855 pos,
856 Believed_player_pos,
857 fvi_query::unused_ignore_obj_list,
858 fvi_query::unused_LevelUniqueObjectState,
859 fvi_query::unused_Robot_info,
860 FQ_TRANSWALL, // -- Why were we checking objects? | FQ_CHECK_OBJS; //what about trans walls???
861 objp,
862 }, startseg, F1_0 / 4, Hit_data);
863 Hit_pos = Hit_data.hit_pnt;
864
865 if (Hit_type == fvi_hit_type::None)
866 {
867 dot = vm_vec_build_dot(vec_to_player, obj.orient.fvec);
868 if (dot > field_of_view - (Overall_agitation << 9)) {
869 return player_visibility_state::visible_and_in_field_of_view;
870 } else {
871 return player_visibility_state::visible_not_in_field_of_view;
872 }
873 } else {
874 return player_visibility_state::no_line_of_sight;
875 }
876 }
877
878 namespace {
879 // ------------------------------------------------------------------------------------------------------------------
880 // Return 1 if animates, else return 0
881 static int do_silly_animation(const d_robot_info_array &Robot_info, object &objp)
882 {
883 polyobj_info *const pobj_info = &objp.rtype.pobj_info;
884 auto &aip = objp.ctype.ai_info;
885 int at_goal;
886 int attack_type;
887 int flinch_attack_scale{1};
888
889 const auto robot_type{get_robot_id(objp)};
890 auto &Robot_joints = LevelSharedRobotJointState.Robot_joints;
891 auto &robptr = Robot_info[robot_type];
892 attack_type = robptr.attack_type;
893 const auto num_guns = robptr.n_guns;
894
895 if (num_guns == 0) {
896 return 0;
897 }
898
899 // This is a hack. All positions should be based on goal_state, not GOAL_STATE.
900 const auto robot_state = Mike_to_matt_xlate[aip.GOAL_STATE];
901 // previous_robot_state = Mike_to_matt_xlate[aip->CURRENT_STATE];
902
903 if (attack_type) // && ((robot_state == robot_animation_state::fire) || (robot_state == robot_animation_state::recoil)))
904 flinch_attack_scale = Attack_scale;
905 else if (robot_state == robot_animation_state::flinch || robot_state == robot_animation_state::recoil)
906 flinch_attack_scale = Flinch_scale;
907
908 at_goal = 1;
909 auto &Polygon_models = LevelSharedPolygonModelState.Polygon_models;
910 for (const uint8_t gun_num_idx : xrange(1u + num_guns))
911 {
912 const auto gun_num = robot_gun_number{gun_num_idx};
913 auto &ail = aip.ail;
914 for (auto &jr : robot_get_anim_state(Robot_info, Robot_joints, robot_type, robot_gun_animation_index{gun_num_idx}, robot_state))
915 {
916 unsigned jointnum = jr.jointnum;
917 auto &jp = jr.angles;
918 vms_angvec *pobjp = &pobj_info->anim_angles[jointnum];
919
920 if (jointnum >= Polygon_models[objp.rtype.pobj_info.model_num].n_models) {
921 Int3(); // Contact Mike: incompatible data, illegal jointnum, problem in pof file?
922 continue;
923 }
924 auto &goal_angles = ail.goal_angles[jointnum];
925 auto &delta_angles = ail.delta_angles[jointnum];
926 const auto animate_p = silly_animation_angle(&vms_angvec::p, jp, *pobjp, flinch_attack_scale, goal_angles, delta_angles);
927 const auto animate_b = silly_animation_angle(&vms_angvec::b, jp, *pobjp, flinch_attack_scale, goal_angles, delta_angles);
928 const auto animate_h = silly_animation_angle(&vms_angvec::h, jp, *pobjp, flinch_attack_scale, goal_angles, delta_angles);
929 if (gun_num == robot_gun_number::_0)
930 {
931 if (animate_p || animate_b || animate_h)
932 at_goal = 0;
933 }
934 }
935
936 if (at_goal) {
937 //ai_static *aip = &objp->ctype.ai_info;
938 ail.achieved_state[gun_num] = ail.goal_state[gun_num];
939 if (ail.achieved_state[gun_num] == AIS_RECO)
940 ail.goal_state[gun_num] = AIS_FIRE;
941 else if (ail.achieved_state[gun_num] == AIS_FLIN)
942 ail.goal_state[gun_num] = AIS_LOCK;
943 }
944 }
945
946 if (at_goal == 1) //num_guns)
947 aip.CURRENT_STATE = aip.GOAL_STATE;
948
949 return 1;
950 }
951
952 // ------------------------------------------------------------------------------------------
953 // Move all sub-objects in an object towards their goals.
954 // Current orientation of object is at: pobj_info.anim_angles
955 // Goal orientation of object is at: ai_info.goal_angles
956 // Delta orientation of object is at: ai_info.delta_angles
957 static void ai_frame_animation(object &objp)
958 {
959 int joint;
960 auto &pobj_info = objp.rtype.pobj_info;
961 auto &Polygon_models = LevelSharedPolygonModelState.Polygon_models;
962 const auto num_joints = Polygon_models[pobj_info.model_num].n_models;
963 const auto &ail = objp.ctype.ai_info.ail;
964 for (joint=1; joint<num_joints; joint++) {
965 auto &curang = pobj_info.anim_angles[joint];
966 auto &goalang = ail.goal_angles[joint];
967 auto &deltaang = ail.delta_angles[joint];
968
969 const fix frametime = FrameTime;
970 frame_animation_angle(&vms_angvec::p, frametime, deltaang, goalang, curang);
971 frame_animation_angle(&vms_angvec::b, frametime, deltaang, goalang, curang);
972 frame_animation_angle(&vms_angvec::h, frametime, deltaang, goalang, curang);
973 }
974 }
975
976 // ----------------------------------------------------------------------------------
977 static void set_next_fire_time(object &objp, ai_local &ailp, const robot_info &robptr, const robot_gun_number gun_num)
978 {
979 const auto Difficulty_level = GameUniqueState.Difficulty_level;
980 #if DXX_BUILD_DESCENT == 1
981 (void)objp;
982 (void)gun_num;
983 ailp.rapidfire_count++;
984
985 if (ailp.rapidfire_count < robptr.rapidfire_count[Difficulty_level]) {
986 ailp.next_fire = min(F1_0/8, robptr.firing_wait[Difficulty_level]/2);
987 } else {
988 ailp.rapidfire_count = 0;
989 ailp.next_fire = robptr.firing_wait[Difficulty_level];
990 }
991 #elif DXX_BUILD_DESCENT == 2
992 // For guys in snipe mode, they have a 50% shot of getting this shot in free.
993 if (gun_num != robot_gun_number::_0 || robptr.weapon_type2 == weapon_none)
994 if ((objp.ctype.ai_info.behavior != ai_behavior::AIB_SNIPE) || (d_rand() > 16384))
995 ailp.rapidfire_count++;
996
997 // Old way, 10/15/95: Continuous rapidfire if rapidfire_count set.
998 // -- if (((robptr.weapon_type2 == -1) || (gun_num != 0)) && (ailp->rapidfire_count < robptr.rapidfire_count[Difficulty_level])) {
999 // -- ailp->next_fire = min(F1_0/8, robptr.firing_wait[Difficulty_level]/2);
1000 // -- } else {
1001 // -- if ((robptr.weapon_type2 == -1) || (gun_num != 0)) {
1002 // -- ailp->rapidfire_count = 0;
1003 // -- ailp->next_fire = robptr.firing_wait[Difficulty_level];
1004 // -- } else
1005 // -- ailp->next_fire2 = robptr.firing_wait2[Difficulty_level];
1006 // -- }
1007
1008 if ((gun_num != robot_gun_number::_0 || robptr.weapon_type2 == weapon_none) && ailp.rapidfire_count < robptr.rapidfire_count[Difficulty_level])
1009 {
1010 ailp.next_fire = min(F1_0/8, robptr.firing_wait[Difficulty_level]/2);
1011 } else {
1012 if (gun_num != robot_gun_number::_0 || robptr.weapon_type2 == weapon_none)
1013 {
1014 ailp.next_fire = robptr.firing_wait[Difficulty_level];
1015 if (ailp.rapidfire_count >= robptr.rapidfire_count[Difficulty_level])
1016 ailp.rapidfire_count = 0;
1017 } else
1018 ailp.next_fire2 = robptr.firing_wait2[Difficulty_level];
1019 }
1020 #endif
1021 }
1022 }
1023
1024 // ----------------------------------------------------------------------------------
1025 // When some robots collide with the player, they attack.
1026 // If player is cloaked, then robot probably didn't actually collide, deal with that here.
1027 void do_ai_robot_hit_attack(const d_robot_info_array &Robot_info, const vmobjptridx_t robot, const vmobjptridx_t playerobj, const vms_vector &collision_point)
1028 {
1029 ai_local &ailp = robot->ctype.ai_info.ail;
1030 auto &robptr = Robot_info[get_robot_id(robot)];
1031
1032 //#ifndef NDEBUG
1033 if (cheats.robotfiringsuspended)
1034 return;
1035 //#endif
1036
1037 // If player is dead, stop firing.
1038 object &plrobj = *playerobj;
1039 if (plrobj.type == OBJ_GHOST)
1040 return;
1041
1042 if (robptr.attack_type == 1) {
1043 if (ready_to_fire_weapon1(ailp, 0)) {
1044 auto &player_info = plrobj.ctype.player_info;
1045 if (!(player_info.powerup_flags & PLAYER_FLAGS_CLOAKED))
1046 if (vm_vec_dist_quick(plrobj.pos, robot->pos) < robot->size + plrobj.size + F1_0*2)
1047 {
1048 collide_player_and_nasty_robot(Robot_info, playerobj, robot, collision_point);
1049 #if DXX_BUILD_DESCENT == 2
1050 auto &energy = player_info.energy;
1051 if (robptr.energy_drain && energy) {
1052 energy -= robptr.energy_drain * F1_0;
1053 if (energy < 0)
1054 energy = 0;
1055 }
1056 #endif
1057 }
1058
1059 robot->ctype.ai_info.GOAL_STATE = AIS_RECO;
1060 set_next_fire_time(robot, ailp, robptr, robot_gun_number::_1); // 1 = gun_num: 0 is special (uses next_fire2)
1061 }
1062 }
1063 }
1064
1065 namespace {
1066 #if DXX_BUILD_DESCENT == 2
1067 // --------------------------------------------------------------------------------------------------------------------
1068 // Computes point at which projectile fired by robot can hit player given positions, player vel, elapsed time
1069 static fix compute_lead_component(fix player_pos, fix robot_pos, fix player_vel, fix elapsed_time)
1070 {
1071 return fixdiv(player_pos - robot_pos, elapsed_time) + player_vel;
1072 }
1073
1074 static void compute_lead_component(fix vms_vector::*const m, vms_vector &out, const vms_vector &believed_player_pos, const vms_vector &fire_point, const vms_vector &velocity, const fix projected_time)
1075 {
1076 out.*m = compute_lead_component(believed_player_pos.*m, fire_point.*m, velocity.*m, projected_time);
1077 }
1078
1079 // --------------------------------------------------------------------------------------------------------------------
1080 // Lead the player, returning point to fire at in fire_point.
1081 // Rules:
1082 // Player not cloaked
1083 // Player must be moving at a speed >= MIN_LEAD_SPEED
1084 // Player not farther away than MAX_LEAD_DISTANCE
1085 // dot(vector_to_player, player_direction) must be in -LEAD_RANGE..LEAD_RANGE
1086 // if firing a matter weapon, less leading, based on skill level.
1087 static int lead_player(const object_base &objp, const vms_vector &fire_point, const vms_vector &believed_player_pos, const robot_gun_number gun_num, vms_vector &fire_vec)
1088 {
1089 const auto &plrobj = *ConsoleObject;
1090 if (plrobj.ctype.player_info.powerup_flags & PLAYER_FLAGS_CLOAKED)
1091 return 0;
1092
1093 const auto &velocity = plrobj.mtype.phys_info.velocity;
1094 const auto &&[player_speed, player_movement_dir] = vm_vec_normalize_quick_with_magnitude(velocity);
1095
1096 if (player_speed < MIN_LEAD_SPEED)
1097 return 0;
1098
1099 const auto &&[dist_to_player, vec_to_player] = vm_vec_normalize_quick_with_magnitude(vm_vec_build_sub(believed_player_pos, fire_point));
1100 if (dist_to_player > MAX_LEAD_DISTANCE)
1101 return 0;
1102
1103 const fix dot = vm_vec_build_dot(vec_to_player, player_movement_dir);
1104
1105 if ((dot < -LEAD_RANGE) || (dot > LEAD_RANGE))
1106 return 0;
1107
1108 // Looks like it might be worth trying to lead the player.
1109 auto &Robot_info = LevelSharedRobotInfoState.Robot_info;
1110 const auto weapon_type = get_robot_weapon(Robot_info[get_robot_id(objp)], gun_num);
1111
1112 const weapon_info *const wptr = &Weapon_info[weapon_type];
1113 const auto Difficulty_level = GameUniqueState.Difficulty_level;
1114 fix max_weapon_speed = wptr->speed[Difficulty_level];
1115 if (max_weapon_speed < F1_0)
1116 return 0;
1117
1118 // Matter weapons:
1119 // At Rookie or Trainee, don't lead at all.
1120 // At higher skill levels, don't lead as well. Accomplish this by screwing up max_weapon_speed.
1121 if (wptr->matter != weapon_info::matter_flag::energy)
1122 {
1123 switch (Difficulty_level)
1124 {
1125 case Difficulty_level_type::_0:
1126 case Difficulty_level_type::_1:
1127 return 0;
1128 case Difficulty_level_type::_2:
1129 case Difficulty_level_type::_3:
1130 max_weapon_speed *= NDL - underlying_value(Difficulty_level);
1131 break;
1132 case Difficulty_level_type::_4:
1133 break;
1134 }
1135 }
1136
1137 const fix projected_time = fixdiv(dist_to_player, max_weapon_speed);
1138
1139 compute_lead_component(&vms_vector::x, fire_vec, believed_player_pos, fire_point, velocity, projected_time);
1140 compute_lead_component(&vms_vector::y, fire_vec, believed_player_pos, fire_point, velocity, projected_time);
1141 compute_lead_component(&vms_vector::z, fire_vec, believed_player_pos, fire_point, velocity, projected_time);
1142
1143 vm_vec_normalize_quick(fire_vec);
1144
1145 Assert(vm_vec_build_dot(fire_vec, objp.orient.fvec) < 3*F1_0/2);
1146
1147 // Make sure not firing at especially strange angle. If so, try to correct. If still bad, give up after one try.
1148 if (vm_vec_build_dot(fire_vec, objp.orient.fvec) < F1_0/2) {
1149 vm_vec_add2(fire_vec, vec_to_player);
1150 vm_vec_scale(fire_vec, F1_0/2);
1151 if (vm_vec_build_dot(fire_vec, objp.orient.fvec) < F1_0/2) {
1152 return 0;
1153 }
1154 }
1155
1156 return 1;
1157 }
1158 #endif
1159
1160 // --------------------------------------------------------------------------------------------------------------------
1161 // Note: Parameter vec_to_player is only passed now because guns which aren't on the forward vector from the
1162 // center of the robot will not fire right at the player. We need to aim the guns at the player. Barring that, we cheat.
1163 // When this routine is complete, the parameter vec_to_player should not be necessary.
1164 static void ai_fire_laser_at_player(const d_robot_info_array &Robot_info, const d_level_shared_segment_state &LevelSharedSegmentState, const vmobjptridx_t obj, const player_info &player_info, robot_gun_point &gun_point, const robot_gun_number gun_num
1165 #if DXX_BUILD_DESCENT == 2
1166 , const vms_vector &believed_player_pos
1167 #endif
1168 )
1169 {
1170 auto &BossUniqueState = LevelUniqueObjectState.BossState;
1171 const auto Difficulty_level = underlying_value(GameUniqueState.Difficulty_level);
1172 const auto powerup_flags = player_info.powerup_flags;
1173 ai_local &ailp = obj->ctype.ai_info.ail;
1174 auto &robptr = Robot_info[get_robot_id(obj)];
1175 vms_vector fire_vec;
1176
1177 Assert(robptr.attack_type == 0); // We should never be coming here for the green guy, as he has no laser!
1178
1179 if (cheats.robotfiringsuspended)
1180 return;
1181
1182 if (obj->control_source == object::control_type::morph)
1183 return;
1184
1185 // If player is exploded, stop firing.
1186 if (Player_dead_state == player_dead_state::exploded)
1187 return;
1188
1189 #if DXX_BUILD_DESCENT == 2
1190 // If this robot is only awake because a camera woke it up, don't fire.
1191 if (obj->ctype.ai_info.SUB_FLAGS & SUB_FLAGS_CAMERA_AWAKE)
1192 return;
1193
1194 if (obj->ctype.ai_info.dying_start_time)
1195 return; // No firing while in death roll.
1196
1197 // Don't let the boss fire while in death roll. Sorry, this is the easiest way to do this.
1198 // If you try to key the boss off obj->ctype.ai_info.dying_start_time, it will hose the endlevel stuff.
1199 if (BossUniqueState.Boss_dying_start_time && robptr.boss_flag != boss_robot_id::None)
1200 return;
1201 #endif
1202
1203 // If player is cloaked, maybe don't fire based on how long cloaked and randomness.
1204 if (powerup_flags & PLAYER_FLAGS_CLOAKED) {
1205 fix64 cloak_time = Ai_cloak_info[static_cast<imobjptridx_t::index_type>(obj) % MAX_AI_CLOAK_INFO].last_time;
1206
1207 if (GameTime64 - cloak_time > CLOAK_TIME_MAX/4)
1208 if (d_rand() > fixdiv(GameTime64 - cloak_time, CLOAK_TIME_MAX)/2) {
1209 set_next_fire_time(obj, ailp, robptr, gun_num);
1210 return;
1211 }
1212 }
1213
1214 auto &fire_point = gun_point.build(robptr, obj, gun_num);
1215 #if DXX_BUILD_DESCENT == 1
1216 (void)LevelSharedSegmentState;
1217 // Set position to fire at based on difficulty level.
1218 vms_vector bpp_diff = Believed_player_pos;
1219 const auto m = (NDL - Difficulty_level - 1) * 4;
1220 bpp_diff.x += (d_rand() - 16384) * m;
1221 bpp_diff.y += (d_rand() - 16384) * m;
1222 bpp_diff.z += (d_rand() - 16384) * m;
1223
1224 // Half the time fire at the player, half the time lead the player.
1225 if (d_rand() > 16384) {
1226
1227 vm_vec_normalized_dir_quick(fire_vec, bpp_diff, fire_point);
1228
1229 } else {
1230 // If player is not moving, fire right at him!
1231 // Note: If the robot fires in the direction of its forward vector, this is bad because the weapon does not
1232 // come out from the center of the robot; it comes out from the side. So it is common for the weapon to miss
1233 // its target. Ideally, we want to point the guns at the player. For now, just fire right at the player.
1234 {
1235 vm_vec_normalized_dir_quick(fire_vec, bpp_diff, fire_point);
1236 // Player is moving. Determine where the player will be at the end of the next frame if he doesn't change his
1237 // behavior. Fire at exactly that point. This isn't exactly what you want because it will probably take the laser
1238 // a different amount of time to get there, since it will probably be a different distance from the player.
1239 // So, that's why we write games, instead of guiding missiles...
1240 }
1241 }
1242 #elif DXX_BUILD_DESCENT == 2
1243 auto &Walls = LevelUniqueWallSubsystemState.Walls;
1244 auto &vcwallptr = Walls.vcptr;
1245 // Handle problem of a robot firing through a wall because its gun tip is on the other
1246 // side of the wall than the robot's center. For speed reasons, we normally only compute
1247 // the vector from the gun point to the player. But we need to know whether the gun point
1248 // is separated from the robot's center by a wall. If so, don't fire!
1249 if (obj->ctype.ai_info.SUB_FLAGS & SUB_FLAGS_GUNSEG) {
1250 // Well, the gun point is in a different segment than the robot's center.
1251 // This is almost always ok, but it is not ok if something solid is in between.
1252 // See if these segments are connected, which should almost always be the case.
1253 auto &Segments = LevelSharedSegmentState.get_segments();
1254 const auto &&csegp = Segments.vcptridx(obj->segnum);
1255 const auto &&gun_segnum = find_point_seg(LevelSharedSegmentState, fire_point, csegp);
1256 const auto conn_side = find_connect_side(gun_segnum, csegp);
1257 if (conn_side != side_none)
1258 {
1259 // They are connected via conn_side in segment obj->segnum.
1260 // See if they are unobstructed.
1261 if (!(WALL_IS_DOORWAY(GameBitmaps, Textures, vcwallptr, csegp, conn_side) & WALL_IS_DOORWAY_FLAG::fly))
1262 {
1263 // Can't fly through, so don't let this bot fire through!
1264 return;
1265 }
1266 } else {
1267 // Well, they are not directly connected, so use find_vector_intersection to see if they are unobstructed.
1268 fvi_info hit_data;
1269
1270 const auto fate = find_vector_intersection(fvi_query{
1271 obj->pos,
1272 fire_point,
1273 fvi_query::unused_ignore_obj_list,
1274 fvi_query::unused_LevelUniqueObjectState,
1275 fvi_query::unused_Robot_info,
1276 FQ_TRANSWALL,
1277 obj,
1278 }, obj->segnum, 0, hit_data);
1279 if (fate != fvi_hit_type::None)
1280 {
1281 Int3(); // This bot's gun is poking through a wall, so don't fire.
1282 move_towards_segment_center(robptr, LevelSharedSegmentState, obj); // And decrease chances it will happen again.
1283 return;
1284 }
1285 }
1286 }
1287
1288 // Set position to fire at based on difficulty level and robot's aiming ability
1289 fix aim = FIRE_K*F1_0 - (FIRE_K-1)*(robptr.aim << 8); // F1_0 in bitmaps.tbl = same as used to be. Worst is 50% more error.
1290
1291 // Robots aim more poorly during seismic disturbance.
1292 if (const auto Seismic_tremor_magnitude = LevelUniqueSeismicState.Seismic_tremor_magnitude)
1293 {
1294 aim = fixmul(aim, std::max(F1_0 - abs(Seismic_tremor_magnitude), F1_0 / 2));
1295 }
1296
1297 // Lead the player half the time.
1298 // Note that when leading the player, aim is perfect. This is probably acceptable since leading is so hacked in.
1299 // Problem is all robots will lead equally badly.
1300 if (d_rand() < 16384) {
1301 if (lead_player(obj, fire_point, believed_player_pos, gun_num, fire_vec)) // Stuff direction to fire at in fire_point.
1302 goto player_led;
1303 }
1304
1305 {
1306 fix dot{0};
1307 unsigned count{0}; // Don't want to sit in this loop forever...
1308 const auto m = (NDL - Difficulty_level - 1) * 4;
1309 while ((count < 4) && (dot < F1_0/4)) {
1310 vms_vector bpp_diff = believed_player_pos;
1311 bpp_diff.x += fixmul((d_rand() - 16384) * m, aim);
1312 bpp_diff.y += fixmul((d_rand() - 16384) * m, aim);
1313 bpp_diff.z += fixmul((d_rand() - 16384) * m, aim);
1314
1315 vm_vec_normalized_dir_quick(fire_vec, bpp_diff, fire_point);
1316 dot = vm_vec_build_dot(obj->orient.fvec, fire_vec);
1317 count++;
1318 }
1319 }
1320 player_led: ;
1321 #endif
1322
1323 const auto weapon_type = get_robot_weapon(robptr, gun_num);
1324
1325 Laser_create_new_easy(Robot_info, fire_vec, fire_point, obj, weapon_type, weapon_sound_flag::audible);
1326
1327 #if DXX_USE_MULTIPLAYER
1328 if (Game_mode & GM_MULTI)
1329 {
1330 ai_multi_send_robot_position(obj, -1);
1331 multi_send_robot_fire(obj, obj->ctype.ai_info.CURRENT_GUN, fire_vec);
1332 }
1333 #endif
1334
1335 create_awareness_event(obj, player_awareness_type_t::PA_NEARBY_ROBOT_FIRED, LevelUniqueRobotAwarenessState);
1336
1337 set_next_fire_time(obj, ailp, robptr, gun_num);
1338
1339 // If the boss fired, allow him to teleport very soon (right after firing, cool!), pending other factors.
1340 if (robptr.boss_flag == boss_robot_id::d1_1 || robptr.boss_flag == boss_robot_id::d1_superboss)
1341 BossUniqueState.Last_teleport_time -= LevelSharedBossState.Boss_teleport_interval / 2;
1342 }
1343
1344 // --------------------------------------------------------------------------------------------------------------------
1345 // vec_goal must be normalized, or close to it.
1346 // if dot_based set, then speed is based on direction of movement relative to heading
1347 static void move_towards_vector(const robot_info &robptr, object_base &objp, const vms_vector &vec_goal, int dot_based)
1348 {
1349 auto &velocity = objp.mtype.phys_info.velocity;
1350
1351 // Trying to move towards player. If forward vector much different than velocity vector,
1352 // bash velocity vector twice as much towards player as usual.
1353
1354 const auto vel = vm_vec_normalized_quick(velocity);
1355 fix dot = vm_vec_build_dot(vel, objp.orient.fvec);
1356
1357 #if DXX_BUILD_DESCENT == 1
1358 dot_based = 1;
1359 #elif DXX_BUILD_DESCENT == 2
1360 if (robot_is_thief(robptr))
1361 dot = (F1_0+dot)/2;
1362 #endif
1363
1364 const auto Difficulty_level = GameUniqueState.Difficulty_level;
1365 if (dot_based && (dot < 3*F1_0/4)) {
1366 // This funny code is supposed to slow down the robot and move his velocity towards his direction
1367 // more quickly than the general code
1368 const fix frametime32 = FrameTime * 32;
1369 move_toward_vector_component_assign(&vms_vector::x, vec_goal, frametime32, velocity);
1370 move_toward_vector_component_assign(&vms_vector::y, vec_goal, frametime32, velocity);
1371 move_toward_vector_component_assign(&vms_vector::z, vec_goal, frametime32, velocity);
1372 } else {
1373 const fix frametime64 = FrameTime * 64;
1374 const fix difficulty_scale = underlying_value(Difficulty_level) + 5;
1375 move_toward_vector_component_add(&vms_vector::x, vec_goal, frametime64, difficulty_scale, velocity);
1376 move_toward_vector_component_add(&vms_vector::y, vec_goal, frametime64, difficulty_scale, velocity);
1377 move_toward_vector_component_add(&vms_vector::z, vec_goal, frametime64, difficulty_scale, velocity);
1378 }
1379
1380 const auto speed = vm_vec_mag_quick(velocity);
1381 fix max_speed = robptr.max_speed[Difficulty_level];
1382
1383 // Green guy attacks twice as fast as he moves away.
1384 #if DXX_BUILD_DESCENT == 1
1385 if (robptr.attack_type == 1)
1386 #elif DXX_BUILD_DESCENT == 2
1387 if (robptr.attack_type == 1 || robot_is_thief(robptr) || robptr.kamikaze)
1388 #endif
1389 max_speed *= 2;
1390
1391 if (speed > max_speed) {
1392 velocity.x = (velocity.x * 3) / 4;
1393 velocity.y = (velocity.y * 3) / 4;
1394 velocity.z = (velocity.z * 3) / 4;
1395 }
1396 }
1397
1398 }
1399
1400 // --------------------------------------------------------------------------------------------------------------------
1401 #if DXX_BUILD_DESCENT == 1
1402 static
1403 #endif
1404 void move_towards_player(const d_robot_info_array &Robot_info, object &objp, const vms_vector &vec_to_player)
1405 // vec_to_player must be normalized, or close to it.
1406 {
1407 auto &robptr = Robot_info[get_robot_id(objp)];
1408 move_towards_vector(robptr, objp, vec_to_player, 1);
1409 }
1410
1411 namespace {
1412
1413 // --------------------------------------------------------------------------------------------------------------------
1414 // I am ashamed of this: fast_flag == -1 means normal slide about. fast_flag = 0 means no evasion.
1415 static void move_around_player(const d_robot_info_array &Robot_info, const vmobjptridx_t objp, const player_flags powerup_flags, const vms_vector &vec_to_player, int fast_flag)
1416 {
1417 physics_info *pptr = &objp->mtype.phys_info;
1418 vms_vector evade_vector;
1419
1420 if (fast_flag == 0)
1421 return;
1422
1423 const unsigned dir = ((objp) ^ ((d_tick_count + 3*(objp)) >> 5)) & 3;
1424 switch (dir) {
1425 case 0:
1426 evade_vector.x = vec_to_player.z;
1427 evade_vector.y = vec_to_player.y;
1428 evade_vector.z = -vec_to_player.x;
1429 break;
1430 case 1:
1431 evade_vector.x = -vec_to_player.z;
1432 evade_vector.y = vec_to_player.y;
1433 evade_vector.z = vec_to_player.x;
1434 break;
1435 case 2:
1436 evade_vector.x = -vec_to_player.y;
1437 evade_vector.y = vec_to_player.x;
1438 evade_vector.z = vec_to_player.z;
1439 break;
1440 case 3:
1441 evade_vector.x = vec_to_player.y;
1442 evade_vector.y = -vec_to_player.x;
1443 evade_vector.z = vec_to_player.z;
1444 break;
1445 default:
1446 throw std::runtime_error("move_around_player: bad case");
1447 }
1448 const auto frametime32 = FrameTime * 32;
1449 evade_vector.x = fixmul(evade_vector.x, frametime32);
1450 evade_vector.y = fixmul(evade_vector.y, frametime32);
1451 evade_vector.z = fixmul(evade_vector.z, frametime32);
1452
1453 auto &robptr = Robot_info[get_robot_id(objp)];
1454 const auto Difficulty_level = GameUniqueState.Difficulty_level;
1455 // Note: -1 means normal circling about the player. > 0 means fast evasion.
1456 if (fast_flag > 0) {
1457 fix dot;
1458
1459 // Only take evasive action if looking at player.
1460 // Evasion speed is scaled by percentage of shields left so wounded robots evade less effectively.
1461
1462 dot = vm_vec_build_dot(vec_to_player, objp->orient.fvec);
1463 if (dot > robptr.field_of_view[Difficulty_level] && !(powerup_flags & PLAYER_FLAGS_CLOAKED)) {
1464 fix damage_scale;
1465
1466 if (!robptr.strength)
1467 damage_scale = F1_0;
1468 else
1469 damage_scale = fixdiv(objp->shields, robptr.strength);
1470 if (damage_scale > F1_0)
1471 damage_scale = F1_0; // Just in case...
1472 else if (damage_scale < 0)
1473 damage_scale = 0; // Just in case...
1474
1475 vm_vec_scale(evade_vector, i2f(fast_flag) + damage_scale);
1476 }
1477 }
1478
1479 pptr->velocity.x += evade_vector.x;
1480 pptr->velocity.y += evade_vector.y;
1481 pptr->velocity.z += evade_vector.z;
1482
1483 const auto speed = vm_vec_mag_quick(pptr->velocity);
1484 if (speed > robptr.max_speed[Difficulty_level]) {
1485 pptr->velocity.x = (pptr->velocity.x*3)/4;
1486 pptr->velocity.y = (pptr->velocity.y*3)/4;
1487 pptr->velocity.z = (pptr->velocity.z*3)/4;
1488 }
1489 }
1490
1491 // --------------------------------------------------------------------------------------------------------------------
1492 static void move_away_from_player(const d_robot_info_array &Robot_info, const vmobjptridx_t objp, const vms_vector &vec_to_player, int attack_type)
1493 {
1494 physics_info *pptr = &objp->mtype.phys_info;
1495
1496 const auto frametime{FrameTime};
1497 pptr->velocity.x -= fixmul(vec_to_player.x, frametime*16);
1498 pptr->velocity.y -= fixmul(vec_to_player.y, frametime*16);
1499 pptr->velocity.z -= fixmul(vec_to_player.z, frametime*16);
1500
1501 if (attack_type) {
1502 // Get value in 0..3 to choose evasion direction.
1503 const int objref = objp ^ ((d_tick_count + 3 * objp) >> 5);
1504 vm_vec_scale_add2(pptr->velocity, (objref & 2) ? objp->orient.rvec : objp->orient.uvec, ((objref & 1) ? -frametime : frametime) << 5);
1505 }
1506
1507
1508 auto speed = vm_vec_mag_quick(pptr->velocity);
1509
1510 auto &robptr = Robot_info[get_robot_id(objp)];
1511 const auto Difficulty_level = GameUniqueState.Difficulty_level;
1512 if (speed > robptr.max_speed[Difficulty_level])
1513 {
1514 pptr->velocity.x = (pptr->velocity.x*3)/4;
1515 pptr->velocity.y = (pptr->velocity.y*3)/4;
1516 pptr->velocity.z = (pptr->velocity.z*3)/4;
1517 }
1518
1519 }
1520
1521 // --------------------------------------------------------------------------------------------------------------------
1522 // Move towards, away_from or around player.
1523 // Also deals with evasion.
1524 // If the flag evade_only is set, then only allowed to evade, not allowed to move otherwise (must have mode == AIM_STILL).
1525 static void ai_move_relative_to_player(const d_robot_info_array &Robot_info, const vmobjptridx_t objp, ai_local &ailp, const fix dist_to_player, const fix circle_distance, const int evade_only, const robot_to_player_visibility_state &player_visibility, const player_info &player_info)
1526 {
1527 const auto Difficulty_level = GameUniqueState.Difficulty_level;
1528 auto &vec_to_player = player_visibility.vec_to_player;
1529 auto &robptr = Robot_info[get_robot_id(objp)];
1530
1531 // See if should take avoidance.
1532
1533 // New way, green guys don't evade: if ((robptr.attack_type == 0) && (objp->ctype.ai_info.danger_laser_num != -1))
1534 if (objp->ctype.ai_info.danger_laser_num != object_none) {
1535 const auto &&dobjp = objp.absolute_sibling(objp->ctype.ai_info.danger_laser_num);
1536
1537 if ((dobjp->type == OBJ_WEAPON) && (dobjp->signature == objp->ctype.ai_info.danger_laser_signature)) {
1538 vms_vector laser_fvec;
1539
1540 const fix field_of_view = robptr.field_of_view[Difficulty_level];
1541
1542 const auto &&[dist_to_laser, vec_to_laser] = vm_vec_normalize_quick_with_magnitude(vm_vec_build_sub(dobjp->pos, objp->pos));
1543 const fix dot = vm_vec_build_dot(vec_to_laser, objp->orient.fvec);
1544
1545 if (dot > field_of_view || robot_is_companion(robptr))
1546 {
1547 fix laser_robot_dot;
1548
1549 // The laser is seen by the robot, see if it might hit the robot.
1550 // Get the laser's direction. If it's a polyobj, it can be gotten cheaply from the orientation matrix.
1551 if (dobjp->render_type == render_type::RT_POLYOBJ)
1552 laser_fvec = dobjp->orient.fvec;
1553 else { // Not a polyobj, get velocity and normalize.
1554 laser_fvec = vm_vec_normalized_quick(dobjp->mtype.phys_info.velocity); //dobjp->orient.fvec;
1555 }
1556 const auto laser_vec_to_robot = vm_vec_normalized_quick(vm_vec_build_sub(objp->pos, dobjp->pos));
1557 laser_robot_dot = vm_vec_build_dot(laser_fvec, laser_vec_to_robot);
1558
1559 if ((laser_robot_dot > F1_0*7/8) && (dist_to_laser < F1_0*80)) {
1560 int evade_speed;
1561
1562 ai_evaded = 1;
1563 evade_speed = robptr.evade_speed[Difficulty_level];
1564 move_around_player(Robot_info, objp, player_info.powerup_flags, vec_to_player, evade_speed);
1565 }
1566 }
1567 return;
1568 }
1569 }
1570
1571 // If only allowed to do evade code, then done.
1572 // Hmm, perhaps brilliant insight. If want claw-type guys to keep coming, don't return here after evasion.
1573 if (!robptr.attack_type && !robot_is_thief(robptr) && evade_only)
1574 return;
1575
1576 // If we fall out of above, then no object to be avoided.
1577 objp->ctype.ai_info.danger_laser_num = object_none;
1578
1579 // Green guy selects move around/towards/away based on firing time, not distance.
1580 if (robptr.attack_type == 1) {
1581 if ((!ready_to_fire_weapon1(ailp, robptr.firing_wait[Difficulty_level]/4) && dist_to_player < F1_0*30) ||
1582 Player_dead_state != player_dead_state::no)
1583 {
1584 // 1/4 of time, move around player, 3/4 of time, move away from player
1585 if (d_rand() < 8192) {
1586 move_around_player(Robot_info, objp, player_info.powerup_flags, vec_to_player, -1);
1587 } else {
1588 move_away_from_player(Robot_info, objp, vec_to_player, 1);
1589 }
1590 } else {
1591 move_towards_player(Robot_info, objp, vec_to_player);
1592 }
1593 }
1594 else if (robot_is_thief(robptr))
1595 {
1596 move_towards_player(Robot_info, objp, vec_to_player);
1597 }
1598 else {
1599 #if DXX_BUILD_DESCENT == 1
1600 if (dist_to_player < circle_distance)
1601 move_away_from_player(Robot_info, objp, vec_to_player, 0);
1602 else if (dist_to_player < circle_distance*2)
1603 move_around_player(Robot_info, objp, player_info.powerup_flags, vec_to_player, -1);
1604 else
1605 move_towards_player(Robot_info, objp, vec_to_player);
1606 #elif DXX_BUILD_DESCENT == 2
1607 int objval = ((objp) & 0x0f) ^ 0x0a;
1608
1609 // Changes here by MK, 12/29/95. Trying to get rid of endless circling around bots in a large room.
1610 if (robptr.kamikaze) {
1611 move_towards_player(Robot_info, objp, vec_to_player);
1612 } else if (dist_to_player < circle_distance)
1613 move_away_from_player(Robot_info, objp, vec_to_player, 0);
1614 else if ((dist_to_player < (3+objval)*circle_distance/2) && !ready_to_fire_weapon1(ailp, -F1_0)) {
1615 move_around_player(Robot_info, objp, player_info.powerup_flags, vec_to_player, -1);
1616 } else {
1617 if (ready_to_fire_weapon1(ailp, -(F1_0 + (objval << 12))) && player_is_visible(player_visibility.visibility))
1618 {
1619 // Usually move away, but sometimes move around player.
1620 if ((((GameTime64 >> 18) & 0x0f) ^ objval) > 4) {
1621 move_away_from_player(Robot_info, objp, vec_to_player, 0);
1622 } else {
1623 move_around_player(Robot_info, objp, player_info.powerup_flags, vec_to_player, -1);
1624 }
1625 } else
1626 move_towards_player(Robot_info, objp, vec_to_player);
1627 }
1628 #endif
1629 }
1630 }
1631
1632 }
1633
1634 }
1635
1636 namespace dcx {
1637
1638 // --------------------------------------------------------------------------------------------------------------------
1639 // Compute a somewhat random, normalized vector.
1640 vms_vector make_random_vector()
1641 {
1642 vms_vector vec;
1643 vec.x = (d_rand() - 16384) | 1; // make sure we don't create null vector
1644 vec.y = d_rand() - 16384;
1645 vec.z = d_rand() - 16384;
1646 vm_vec_normalize_quick(vec);
1647 return vec;
1648 }
1649
1650 }
1651
1652 namespace dsx {
1653 namespace {
1654
1655 // -------------------------------------------------------------------------------------------------------------------
1656 static void do_firing_stuff(object &obj, const player_flags powerup_flags, const robot_to_player_visibility_state &player_visibility)
1657 {
1658 #if DXX_BUILD_DESCENT == 1
1659 if (player_is_visible(player_visibility.visibility))
1660 #elif DXX_BUILD_DESCENT == 2
1661 if (Dist_to_last_fired_upon_player_pos < FIRE_AT_NEARBY_PLAYER_THRESHOLD || player_is_visible(player_visibility.visibility))
1662 #endif
1663 {
1664 // Now, if in robot's field of view, lock onto player
1665 const fix dot = vm_vec_build_dot(obj.orient.fvec, player_visibility.vec_to_player);
1666 if ((dot >= 7*F1_0/8) || (powerup_flags & PLAYER_FLAGS_CLOAKED)) {
1667 ai_static *const aip = &obj.ctype.ai_info;
1668 ai_local *const ailp = &obj.ctype.ai_info.ail;
1669
1670 switch (aip->GOAL_STATE) {
1671 case AIS_NONE:
1672 case AIS_REST:
1673 case AIS_SRCH:
1674 case AIS_LOCK:
1675 aip->GOAL_STATE = AIS_FIRE;
1676 if (ailp->player_awareness_type <= player_awareness_type_t::PA_NEARBY_ROBOT_FIRED) {
1677 ailp->player_awareness_type = player_awareness_type_t::PA_NEARBY_ROBOT_FIRED;
1678 ailp->player_awareness_time = PLAYER_AWARENESS_INITIAL_TIME;
1679 }
1680 break;
1681 case ai_static_state::AIS_FLIN:
1682 case ai_static_state::AIS_FIRE:
1683 case ai_static_state::AIS_RECO:
1684 case ai_static_state::AIS_ERR_:
1685 break;
1686 }
1687 } else if (dot >= F1_0/2) {
1688 ai_static *const aip = &obj.ctype.ai_info;
1689 switch (aip->GOAL_STATE) {
1690 case AIS_NONE:
1691 case AIS_REST:
1692 case AIS_SRCH:
1693 aip->GOAL_STATE = AIS_LOCK;
1694 break;
1695 case ai_static_state::AIS_LOCK:
1696 case ai_static_state::AIS_FLIN:
1697 case ai_static_state::AIS_FIRE:
1698 case ai_static_state::AIS_RECO:
1699 case ai_static_state::AIS_ERR_:
1700 break;
1701 }
1702 }
1703 }
1704 }
1705
1706 }
1707
1708 // --------------------------------------------------------------------------------------------------------------------
1709 // If a hiding robot gets bumped or hit, he decides to find another hiding place.
1710 void do_ai_robot_hit(const vmobjptridx_t objp, const robot_info &robptr, player_awareness_type_t type)
1711 {
1712 if (objp->control_source == object::control_type::ai)
1713 {
1714 if (type == player_awareness_type_t::PA_WEAPON_ROBOT_COLLISION || type == player_awareness_type_t::PA_PLAYER_COLLISION)
1715 switch (objp->ctype.ai_info.behavior) {
1716 #if DXX_BUILD_DESCENT == 1
1717 case ai_behavior::AIB_HIDE:
1718 objp->ctype.ai_info.SUBMODE = AISM_GOHIDE;
1719 break;
1720 case ai_behavior::AIB_STILL:
1721 // objp->ctype.ai_info.ail.mode = ai_mode::AIM_CHASE_OBJECT; // NOTE: Should be triggered but causes unwanted movements with bosses. I leave this here for future reference.
1722 break;
1723 case ai_behavior::AIB_FOLLOW_PATH:
1724 #elif DXX_BUILD_DESCENT == 2
1725 case ai_behavior::AIB_STILL:
1726 {
1727 int r;
1728
1729 r = d_rand();
1730 // 1/8 time, charge player, 1/4 time create path, rest of time, do nothing
1731 ai_local *ailp = &objp->ctype.ai_info.ail;
1732 if (r < 4096) {
1733 create_path_to_believed_player_segment(objp, robptr, 10, create_path_safety_flag::safe);
1734 objp->ctype.ai_info.behavior = ai_behavior::AIB_STATION;
1735 objp->ctype.ai_info.hide_segment = objp->segnum;
1736 ailp->mode = ai_mode::AIM_CHASE_OBJECT;
1737 } else if (r < 4096+8192) {
1738 create_n_segment_path(objp, robptr, d_rand() / 8192 + 2, segment_none);
1739 ailp->mode = ai_mode::AIM_FOLLOW_PATH;
1740 }
1741 break;
1742 }
1743 case ai_behavior::AIB_BEHIND:
1744 case ai_behavior::AIB_SNIPE:
1745 case ai_behavior::AIB_FOLLOW:
1746 #endif
1747 case ai_behavior::AIB_NORMAL:
1748 case ai_behavior::AIB_RUN_FROM:
1749 case ai_behavior::AIB_STATION:
1750 break;
1751 }
1752 }
1753 }
1754
1755 namespace {
1756
1757 // --------------------------------------------------------------------------------------------------------------------
1758 // Note: This function could be optimized. Surely player_is_visible_from_object would benefit from the
1759 // information of a normalized vec_to_player.
1760 // Return player visibility:
1761 // 0 not visible
1762 // 1 visible, but robot not looking at player (ie, on an unobstructed vector)
1763 // 2 visible and in robot's field of view
1764 // -1 player is cloaked
1765 // If the player is cloaked, set vec_to_player based on time player cloaked and last uncloaked position.
1766 // Updates ailp->previous_visibility if player is not cloaked, in which case the previous visibility is left unchanged
1767 // and is copied to player_visibility
1768
1769 static void compute_vis_and_vec(const d_robot_info_array &Robot_info, const vmobjptridx_t objp, const player_info &player_info, vms_vector &pos, ai_local &ailp, robot_to_player_visibility_state &player_visibility, const robot_info &robptr)
1770 {
1771 if (player_visibility.initialized)
1772 return;
1773 const auto Difficulty_level = GameUniqueState.Difficulty_level;
1774 const auto powerup_flags = player_info.powerup_flags;
1775 if (powerup_flags & PLAYER_FLAGS_CLOAKED)
1776 {
1777 const unsigned cloak_index = (objp) % MAX_AI_CLOAK_INFO;
1778 const fix delta_time = GameTime64 - Ai_cloak_info[cloak_index].last_time;
1779 if (delta_time > F1_0*2) {
1780 Ai_cloak_info[cloak_index].last_time = {GameTime64};
1781 vm_vec_scale_add2(Ai_cloak_info[cloak_index].last_position, make_random_vector(), 8 * delta_time);
1782 }
1783
1784 const auto dist = vm_vec_normalized_dir_quick(player_visibility.vec_to_player, Ai_cloak_info[cloak_index].last_position, pos);
1785 player_visibility.visibility = player_is_visible_from_object(Robot_info, objp, pos, robptr.field_of_view[Difficulty_level], player_visibility.vec_to_player);
1786 if (ailp.next_misc_sound_time < GameTime64 && ready_to_fire_any_weapon(robptr, ailp, F1_0) && dist < F1_0 * 20)
1787 {
1788 ailp.next_misc_sound_time = GameTime64 + (d_rand() + F1_0) * (7 - underlying_value(Difficulty_level)) / 1;
1789 digi_link_sound_to_object(robptr.see_sound, objp, 0, Robot_sound_volume, sound_stack::allow_stacking);
1790 }
1791 } else {
1792 // Compute expensive stuff -- vec_to_player and player_visibility
1793 vm_vec_normalized_dir_quick(player_visibility.vec_to_player, Believed_player_pos, pos);
1794 if (player_visibility.vec_to_player == vms_vector{})
1795 {
1796 player_visibility.vec_to_player.x = F1_0;
1797 }
1798 player_visibility.visibility = player_is_visible_from_object(Robot_info, objp, pos, robptr.field_of_view[Difficulty_level], player_visibility.vec_to_player);
1799
1800 // This horrible code added by MK in desperation on 12/13/94 to make robots wake up as soon as they
1801 // see you without killing frame rate.
1802 {
1803 ai_static *aip = &objp->ctype.ai_info;
1804 if (player_visibility.visibility == player_visibility_state::visible_and_in_field_of_view && ailp.previous_visibility != player_visibility_state::visible_and_in_field_of_view)
1805 if ((aip->GOAL_STATE == AIS_REST) || (aip->CURRENT_STATE == AIS_REST)) {
1806 aip->GOAL_STATE = AIS_FIRE;
1807 aip->CURRENT_STATE = AIS_FIRE;
1808 }
1809 }
1810
1811 #if DXX_BUILD_DESCENT == 1
1812 if (Player_dead_state != player_dead_state::exploded)
1813 #endif
1814 if (ailp.previous_visibility != player_visibility.visibility && player_visibility.visibility == player_visibility_state::visible_and_in_field_of_view)
1815 {
1816 if (ailp.previous_visibility == player_visibility_state::no_line_of_sight)
1817 {
1818 if (ailp.time_player_seen + F1_0/2 < GameTime64)
1819 {
1820 digi_link_sound_to_object(robptr.see_sound, objp, 0, Robot_sound_volume, sound_stack::allow_stacking);
1821 ailp.time_player_sound_attacked = {GameTime64};
1822 ailp.next_misc_sound_time = GameTime64 + F1_0 + d_rand()*4;
1823 }
1824 }
1825 else if (ailp.time_player_sound_attacked + F1_0/4 < GameTime64)
1826 {
1827 digi_link_sound_to_object(robptr.attack_sound, objp, 0, Robot_sound_volume, sound_stack::allow_stacking);
1828 ailp.time_player_sound_attacked = {GameTime64};
1829 }
1830 }
1831
1832 if (player_visibility.visibility == player_visibility_state::visible_and_in_field_of_view && ailp.next_misc_sound_time < GameTime64)
1833 {
1834 ailp.next_misc_sound_time = GameTime64 + (d_rand() + F1_0) * (7 - underlying_value(Difficulty_level)) / 2;
1835 digi_link_sound_to_object(robptr.attack_sound, objp, 0, Robot_sound_volume, sound_stack::allow_stacking);
1836 }
1837 ailp.previous_visibility = player_visibility.visibility;
1838 }
1839
1840 #if DXX_BUILD_DESCENT == 2
1841 // @mk, 09/21/95: If player view is not obstructed and awareness is at least as high as a nearby collision,
1842 // act is if robot is looking at player.
1843 if (ailp.player_awareness_type >= player_awareness_type_t::PA_NEARBY_ROBOT_FIRED)
1844 if (player_visibility.visibility == player_visibility_state::visible_not_in_field_of_view)
1845 player_visibility.visibility = player_visibility_state::visible_and_in_field_of_view;
1846 #endif
1847
1848 if (player_is_visible(player_visibility.visibility))
1849 {
1850 ailp.time_player_seen = {GameTime64};
1851 }
1852 player_visibility.initialized = 1;
1853 }
1854
1855 #if DXX_BUILD_DESCENT == 2
1856 static void compute_buddy_vis_vec(const vmobjptridx_t buddy_obj, const vms_vector &buddy_pos, robot_to_player_visibility_state &player_visibility, const robot_info &robptr)
1857 {
1858 if (player_visibility.initialized)
1859 return;
1860 auto &BuddyState = LevelUniqueObjectState.BuddyState;
1861 auto &Objects = LevelUniqueObjectState.Objects;
1862 auto &plr = get_player_controlling_guidebot(BuddyState, Players);
1863 if (plr.objnum == object_none)
1864 {
1865 player_visibility.vec_to_player = {};
1866 player_visibility.visibility = player_visibility_state::no_line_of_sight;
1867 player_visibility.initialized = 1;
1868 return;
1869 }
1870 auto &plrobj = *Objects.vcptr(plr.objnum);
1871 /* Buddy ignores cloaking */
1872 vm_vec_normalized_dir_quick(player_visibility.vec_to_player, plrobj.pos, buddy_pos);
1873 if (player_visibility.vec_to_player == vms_vector{})
1874 player_visibility.vec_to_player.x = F1_0;
1875
1876 fvi_info hit_data;
1877 const auto hit_type = find_vector_intersection(fvi_query{
1878 buddy_pos,
1879 plrobj.pos,
1880 fvi_query::unused_ignore_obj_list,
1881 fvi_query::unused_LevelUniqueObjectState,
1882 fvi_query::unused_Robot_info,
1883 FQ_TRANSWALL,
1884 buddy_obj,
1885 }, buddy_obj->segnum, F1_0 / 4, hit_data);
1886
1887 auto &ailp = buddy_obj->ctype.ai_info.ail;
1888 player_visibility.visibility = (hit_type == fvi_hit_type::None)
1889 ? ((ailp.time_player_seen = GameTime64, vm_vec_build_dot(player_visibility.vec_to_player, buddy_obj->orient.fvec) > robptr.field_of_view[GameUniqueState.Difficulty_level])
1890 ? player_visibility_state::visible_and_in_field_of_view
1891 : player_visibility_state::visible_not_in_field_of_view
1892 )
1893 : player_visibility_state::no_line_of_sight;
1894 ailp.previous_visibility = player_visibility.visibility;
1895 player_visibility.initialized = 1;
1896 }
1897 #endif
1898
1899 }
1900
1901 // --------------------------------------------------------------------------------------------------------------------
1902 // Move object one object radii from current position towards segment center.
1903 // If segment center is nearer than 2 radii, move it to center.
1904 void move_towards_segment_center(const robot_info &robptr, const d_level_shared_segment_state &LevelSharedSegmentState, object_base &objp)
1905 {
1906 /* ZICO's change of 20081103:
1907 Make move to segment center smoother by using move_towards vector.
1908 Bot's should not jump around and maybe even intersect with each other!
1909 In case it breaks something what I do not see, yet, old code is still there. */
1910 const auto segnum{objp.segnum};
1911 vms_vector vec_to_center;
1912
1913 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
1914 auto &Vertices = LevelSharedVertexState.get_vertices();
1915 auto &SSegments = LevelSharedSegmentState.get_segments();
1916 const auto segment_center{compute_segment_center(Vertices.vcptr, SSegments.vcptr(segnum))};
1917 vm_vec_normalized_dir_quick(vec_to_center, segment_center, objp.pos);
1918 move_towards_vector(robptr, objp, vec_to_center, 1);
1919 }
1920
1921 // -----------------------------------------------------------------------------------------------------------
1922 // Return true if door can be flown through by a suitable type robot.
1923 // Brains, avoid robots, companions can open doors.
1924 // objp == NULL means treat as buddy.
1925 int ai_door_is_openable(
1926 const object &obj, const robot_info *const robptr,
1927 #if DXX_BUILD_DESCENT == 2
1928 const player_flags powerup_flags,
1929 #endif
1930 const shared_segment &segp, const sidenum_t sidenum)
1931 {
1932 if (!IS_CHILD(segp.children[sidenum]))
1933 return 0; //trap -2 (exit side)
1934
1935 const auto wall_num = segp.sides[sidenum].wall_num;
1936
1937 if (wall_num == wall_none) //if there's no door at all...
1938 return 0; //..then say it can't be opened
1939
1940 auto &Walls = LevelUniqueWallSubsystemState.Walls;
1941 auto &vcwallptr = Walls.vcptr;
1942 auto &wall = *vcwallptr(wall_num);
1943 // The mighty console object can open all doors (for purposes of determining paths).
1944 if (&obj == ConsoleObject) {
1945 const auto wt{wall.type};
1946 if (wt == WALL_DOOR)
1947 {
1948 static_assert(WALL_DOOR != 0, "WALL_DOOR must be nonzero for this shortcut to work properly.");
1949 return wt;
1950 }
1951 }
1952 if (!robptr)
1953 return 0;
1954
1955 #if DXX_BUILD_DESCENT == 1
1956 if (get_robot_id(obj) == robot_id::brain || obj.ctype.ai_info.behavior == ai_behavior::AIB_RUN_FROM)
1957 {
1958
1959 if (wall_num != wall_none)
1960 {
1961 const auto wt{wall.type};
1962 if (wt == WALL_DOOR && wall.keys == wall_key::none && !(wall.flags & wall_flag::door_locked))
1963 {
1964 static_assert(WALL_DOOR != 0, "WALL_DOOR must be nonzero for this shortcut to work properly.");
1965 return wt;
1966 }
1967 }
1968 }
1969 #elif DXX_BUILD_DESCENT == 2
1970 auto &WallAnims = GameSharedState.WallAnims;
1971 if (robptr->companion)
1972 {
1973 const auto wt{wall.type};
1974 if (wall.flags & wall_flag::buddy_proof) {
1975 if (wt == WALL_DOOR && wall.state == wall_state::closed)
1976 return 0;
1977 else if (wt == WALL_CLOSED)
1978 return 0;
1979 else if (wt == WALL_ILLUSION && !(wall.flags & wall_flag::illusion_off))
1980 return 0;
1981 }
1982 switch (const auto wall_keys = wall.keys)
1983 {
1984 case wall_key::blue:
1985 case wall_key::gold:
1986 case wall_key::red:
1987 {
1988 return powerup_flags & static_cast<PLAYER_FLAG>(wall_keys);
1989 }
1990 default:
1991 break;
1992 }
1993
1994 if (wt != WALL_DOOR && wt != WALL_CLOSED)
1995 return 1;
1996
1997 // If Buddy is returning to player, don't let him think he can get through triggered doors.
1998 // It's only valid to think that if the player is going to get him through. But if he's
1999 // going to the player, the player is probably on the opposite side.
2000 const ai_mode ailp_mode = obj.ctype.ai_info.ail.mode;
2001
2002 // -- if (Buddy_got_stuck) {
2003 if (ailp_mode == ai_mode::AIM_GOTO_PLAYER) {
2004 if (wt == WALL_BLASTABLE && !(wall.flags & wall_flag::blasted))
2005 return 0;
2006 if (wt == WALL_CLOSED)
2007 return 0;
2008 if (wt == WALL_DOOR) {
2009 if ((wall.flags & wall_flag::door_locked) && (wall.state == wall_state::closed))
2010 return 0;
2011 }
2012 }
2013 // -- }
2014
2015 if (ailp_mode != ai_mode::AIM_GOTO_PLAYER && wall.controlling_trigger != trigger_none)
2016 {
2017 const auto clip_num = wall.clip_num;
2018 if (clip_num == -1)
2019 return clip_num;
2020 else if (WallAnims[clip_num].flags & WCF_HIDDEN) {
2021 static_assert(static_cast<unsigned>(wall_state::closed) == 0, "wall_state::closed must be zero for this shortcut to work properly.");
2022 return underlying_value(wall.state);
2023 } else
2024 return 1;
2025 }
2026
2027 if (wt == WALL_DOOR) {
2028 const auto clip_num = wall.clip_num;
2029
2030 if (clip_num == -1)
2031 return clip_num;
2032 // Buddy allowed to go through secret doors to get to player.
2033 else if ((ailp_mode != ai_mode::AIM_GOTO_PLAYER) && (WallAnims[clip_num].flags & WCF_HIDDEN)) {
2034 static_assert(static_cast<unsigned>(wall_state::closed) == 0, "wall_state::closed must be zero for this shortcut to work properly.");
2035 return underlying_value(wall.state);
2036 } else
2037 return 1;
2038 }
2039 }
2040 else if (get_robot_id(obj) == robot_id::brain || obj.ctype.ai_info.behavior == ai_behavior::AIB_RUN_FROM || obj.ctype.ai_info.behavior == ai_behavior::AIB_SNIPE)
2041 {
2042 if (wall_num != wall_none)
2043 {
2044 const auto wt{wall.type};
2045 if (wt == WALL_DOOR && (wall.keys == wall_key::none) && !(wall.flags & wall_flag::door_locked))
2046 {
2047 static_assert(WALL_DOOR != 0, "WALL_DOOR must be nonzero for this shortcut to work properly.");
2048 return wt;
2049 }
2050 else if (wall.keys != wall_key::none) { // Allow bots to open doors to which player has keys.
2051 return powerup_flags & static_cast<PLAYER_FLAG>(wall.keys);
2052 }
2053 }
2054 }
2055 #endif
2056 return 0;
2057 }
2058
2059 namespace {
2060
2061 // -----------------------------------------------------------------------------------------------------------
2062 // Return side of openable door in segment, if any. If none, return side_none.
2063 static std::optional<sidenum_t> openable_doors_in_segment(fvcwallptr &vcwallptr, const shared_segment &segp)
2064 {
2065 #if DXX_BUILD_DESCENT == 2
2066 auto &WallAnims = GameSharedState.WallAnims;
2067 #endif
2068 for (const auto &&[idx, value] : enumerate(segp.sides))
2069 {
2070 const auto wall_num = value.wall_num;
2071 if (wall_num != wall_none)
2072 {
2073 auto &w = *vcwallptr(wall_num);
2074 if (w.type != WALL_DOOR)
2075 continue;
2076 if (w.keys != wall_key::none)
2077 continue;
2078 if (w.state != wall_state::closed)
2079 continue;
2080 if (w.flags & wall_flag::door_locked)
2081 continue;
2082 #if DXX_BUILD_DESCENT == 2
2083 if (WallAnims[w.clip_num].flags & WCF_HIDDEN)
2084 continue;
2085 #endif
2086 return static_cast<sidenum_t>(idx);
2087 }
2088 }
2089 return std::nullopt;
2090 }
2091
2092 // --------------------------------------------------------------------------------------------------------------------
2093 // Return true if placing an object of size size at pos *pos intersects a (player or robot or control center) in segment *segp.
2094 static int check_object_object_intersection(const vms_vector &pos, fix size, const unique_segment &segp)
2095 {
2096 auto &Objects = LevelUniqueObjectState.Objects;
2097 auto &vcobjptridx = Objects.vcptridx;
2098 // If this would intersect with another object (only check those in this segment), then try to move.
2099 for (auto &curobj : objects_in<const object_base>(segp, vcobjptridx, vcsegptr))
2100 {
2101 if (curobj.type == OBJ_PLAYER || curobj.type == OBJ_ROBOT || curobj.type == OBJ_CNTRLCEN)
2102 {
2103 if (vm_vec_dist_quick(pos, curobj.pos) < size + curobj.size)
2104 return 1;
2105 }
2106 }
2107 return 0;
2108 }
2109
2110 // --------------------------------------------------------------------------------------------------------------------
2111 // Return objnum if object created, else return -1.
2112 // If pos == NULL, pick random spot in segment.
2113 static imobjptridx_t create_gated_robot(const d_robot_info_array &Robot_info, const d_vclip_array &Vclip, fvcobjptr &vcobjptr, const vmsegptridx_t segp, const robot_id object_id, const vms_vector *const pos)
2114 {
2115 auto &BossUniqueState = LevelUniqueObjectState.BossState;
2116 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
2117 auto &LevelUniqueMorphObjectState = LevelUniqueObjectState.MorphObjectState;
2118 auto &Vertices = LevelSharedVertexState.get_vertices();
2119 const auto Difficulty_level = GameUniqueState.Difficulty_level;
2120 const auto Gate_interval = GameUniqueState.Boss_gate_interval;
2121 #if DXX_BUILD_DESCENT == 1
2122 const unsigned maximum_gated_robots = 2 * underlying_value(Difficulty_level) + 3;
2123 #elif DXX_BUILD_DESCENT == 2
2124 if (GameTime64 - BossUniqueState.Last_gate_time < Gate_interval)
2125 return object_none;
2126 const unsigned maximum_gated_robots = 2 * underlying_value(Difficulty_level) + 6;
2127 #endif
2128
2129 unsigned count{0};
2130 for (auto &obj : vcobjptr)
2131 {
2132 if (obj.type == OBJ_ROBOT)
2133 if (obj.matcen_creator == BOSS_GATE_MATCEN_NUM)
2134 count++;
2135 }
2136
2137 if (count > maximum_gated_robots)
2138 {
2139 BossUniqueState.Last_gate_time = GameTime64 - 3*Gate_interval/4;
2140 return object_none;
2141 }
2142
2143 auto &vcvertptr = Vertices.vcptr;
2144 const auto object_pos{pos ? *pos : pick_random_point_in_seg(vcvertptr, segp, std::minstd_rand(d_rand()))};
2145
2146 // See if legal to place object here. If not, move about in segment and try again.
2147 auto &robptr = Robot_info[object_id];
2148 auto &Polygon_models = LevelSharedPolygonModelState.Polygon_models;
2149 const fix objsize = Polygon_models[robptr.model_num].rad;
2150 if (check_object_object_intersection(object_pos, objsize, segp)) {
2151 BossUniqueState.Last_gate_time = GameTime64 - 3*Gate_interval/4;
2152 return object_none;
2153 }
2154
2155 #if DXX_BUILD_DESCENT == 1
2156 const ai_behavior default_behavior = (object_id == robot_id::toaster) // This is a toaster guy!
2157 ? ai_behavior::AIB_RUN_FROM
2158 : ai_behavior::AIB_NORMAL;
2159 #elif DXX_BUILD_DESCENT == 2
2160 const ai_behavior default_behavior = robptr.behavior;
2161 #endif
2162 auto objp = robot_create(Robot_info, object_id, segp, object_pos, &vmd_identity_matrix, objsize, default_behavior);
2163
2164 if ( objp == object_none ) {
2165 BossUniqueState.Last_gate_time = GameTime64 - 3*Gate_interval/4;
2166 return object_none;
2167 }
2168
2169 //Set polygon-object-specific data
2170
2171 objp->rtype.pobj_info.model_num = robptr.model_num;
2172 objp->rtype.pobj_info.subobj_flags = 0;
2173
2174 //set Physics info
2175
2176 objp->mtype.phys_info.mass = robptr.mass;
2177 objp->mtype.phys_info.drag = robptr.drag;
2178
2179 objp->mtype.phys_info.flags |= (PF_LEVELLING);
2180
2181 objp->shields = robptr.strength;
2182 objp->matcen_creator = BOSS_GATE_MATCEN_NUM; // flag this robot as having been created by the boss.
2183
2184 #if DXX_BUILD_DESCENT == 2
2185 objp->lifeleft = F1_0*30; // Gated in robots only live 30 seconds.
2186 #endif
2187
2188 object_create_explosion_without_damage(Vclip, segp, object_pos, i2f(10), vclip_index::morphing_robot);
2189 digi_link_sound_to_pos(Vclip[vclip_index::morphing_robot].sound_num, segp, sidenum_t::WLEFT, object_pos, 0, F1_0);
2190 morph_start(LevelUniqueMorphObjectState, LevelSharedPolygonModelState, objp);
2191
2192 BossUniqueState.Last_gate_time = {GameTime64};
2193 ++LevelUniqueObjectState.accumulated_robots;
2194 ++GameUniqueState.accumulated_robots;
2195
2196 return objp;
2197 }
2198
2199 }
2200
2201 // --------------------------------------------------------------------------------------------------------------------
2202 // Make object objp gate in a robot.
2203 // The process of him bringing in a robot takes one second.
2204 // Then a robot appears somewhere near the player.
2205 // Return objnum if robot successfully created, else return -1
2206 imobjptridx_t gate_in_robot(const d_robot_info_array &Robot_info, const robot_id type, const vmsegptridx_t segnum)
2207 {
2208 auto &Objects = LevelUniqueObjectState.Objects;
2209 auto &vcobjptr = Objects.vcptr;
2210 return create_gated_robot(Robot_info, Vclip, vcobjptr, segnum, type, nullptr);
2211 }
2212
2213 namespace {
2214
2215 static imobjptridx_t gate_in_robot(const d_robot_info_array &Robot_info, fvmsegptridx &vmsegptridx, const robot_id type)
2216 {
2217 auto &Boss_gate_segs = LevelSharedBossState.Gate_segs;
2218 auto segnum = Boss_gate_segs[(d_rand() * Boss_gate_segs.size()) >> 15];
2219 return gate_in_robot(Robot_info, type, vmsegptridx(segnum));
2220 }
2221
2222 }
2223
2224 }
2225
2226 namespace dcx {
2227
2228 namespace {
2229
2230 static const shared_segment *boss_intersects_wall(fvcvertptr &vcvertptr, const object_base &boss_objp, const vcsegptridx_t segp)
2231 {
2232 const auto size = boss_objp.size;
2233 const auto segcenter{compute_segment_center(vcvertptr, segp)};
2234 const auto &&r{std::ranges::subrange(segp->verts)};
2235 const auto re = r.end();
2236 auto pos = segcenter;
2237 for (auto ri = r.begin();; ++ri)
2238 {
2239 const auto seg = sphere_intersects_wall(vcsegptridx, vcvertptr, pos, segp, size).seg;
2240 if (!seg)
2241 return seg;
2242 if (ri == re)
2243 return seg;
2244 auto &vertex_pos = *vcvertptr(*ri);
2245 pos = vm_vec_build_avg(vertex_pos, segcenter);
2246 }
2247 }
2248
2249 // ----------------------------------------------------------------------------------
2250 static void pae_aux(const vcsegptridx_t segnum, const player_awareness_type_t type, awareness_t &New_awareness, const unsigned allowed_recursions_remaining)
2251 {
2252 if (New_awareness[segnum] < type)
2253 New_awareness[segnum] = type;
2254 const auto sub_allowed_recursions_remaining = allowed_recursions_remaining - 1;
2255 if (!sub_allowed_recursions_remaining)
2256 return;
2257 // Process children.
2258 const auto subtype = (type == player_awareness_type_t::PA_WEAPON_ROBOT_COLLISION)
2259 ? player_awareness_type_t::PA_PLAYER_COLLISION
2260 : type;
2261 for (const auto j : segnum->shared_segment::children)
2262 if (IS_CHILD(j))
2263 pae_aux(segnum.absolute_sibling(j), subtype, New_awareness, sub_allowed_recursions_remaining);
2264 }
2265
2266 }
2267
2268 }
2269
2270 namespace dsx {
2271
2272 #if DXX_BUILD_DESCENT == 2
2273 // --------------------------------------------------------------------------------------------------------------------
2274 // Create a Buddy bot.
2275 // This automatically happens when you bring up the Buddy menu in a debug version.
2276 // It is available as a cheat in a non-debug (release) version.
2277 void create_buddy_bot(const d_level_shared_robot_info_state &LevelSharedRobotInfoState)
2278 {
2279 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
2280 auto &Vertices = LevelSharedVertexState.get_vertices();
2281 for (auto &&[idx, ri] : enumerate(partial_const_range(LevelSharedRobotInfoState.Robot_info, LevelSharedRobotInfoState.N_robot_types)))
2282 {
2283 if (!ri.companion)
2284 continue;
2285 const auto &&segp = vmsegptridx(ConsoleObject->segnum);
2286 const auto object_pos{compute_segment_center(Vertices.vcptr, segp)};
2287 create_morph_robot(LevelSharedRobotInfoState.Robot_info, segp, object_pos, idx);
2288 break;
2289 }
2290 }
2291 #endif
2292
2293 namespace {
2294
2295 // --------------------------------------------------------------------------------------------------------------------
2296 // Create list of segments boss is allowed to teleport to at imsegptr.
2297 // Set *num_segs.
2298 // Boss is allowed to teleport to segments he fits in (calls object_intersects_wall) and
2299 // he can reach from his initial position (calls find_connected_distance).
2300 // If size_check is set, then only add segment if boss can fit in it, else any segment is legal.
2301 // one_wall_hack added by MK, 10/13/95: A mega-hack! Set to !0 to ignore the
2302 static void init_boss_segments(const segment_array &segments, const object &boss_objp, d_level_shared_boss_state::special_segment_array_t &a, const int size_check, int one_wall_hack)
2303 {
2304 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
2305 auto &Vertices = LevelSharedVertexState.get_vertices();
2306 constexpr unsigned QUEUE_SIZE = 256;
2307 auto &vcsegptridx = segments.vcptridx;
2308 auto &vmsegptr = segments.vmptr;
2309 #if DXX_BUILD_DESCENT == 1
2310 one_wall_hack = 0;
2311 #endif
2312
2313 a.clear();
2314 #if DXX_USE_EDITOR
2315 Selected_segs.clear();
2316 #endif
2317
2318 auto &Walls = LevelUniqueWallSubsystemState.Walls;
2319 auto &vcwallptr = Walls.vcptr;
2320 {
2321 int head, tail;
2322 std::array<segnum_t, QUEUE_SIZE> seg_queue;
2323
2324 const auto original_boss_seg = boss_objp.segnum;
2325 head = 0;
2326 tail = 0;
2327 seg_queue[head++] = original_boss_seg;
2328 auto &vcvertptr = Vertices.vcptr;
2329
2330 if (!size_check || !boss_intersects_wall(vcvertptr, boss_objp, vcsegptridx(original_boss_seg)))
2331 {
2332 a.emplace_back(original_boss_seg);
2333 #if DXX_USE_EDITOR
2334 Selected_segs.emplace_back(original_boss_seg);
2335 #endif
2336 }
2337
2338 visited_segment_bitarray_t visited;
2339
2340 while (tail != head) {
2341 const cscusegment segp = *vmsegptr(seg_queue[tail++]);
2342
2343 tail &= QUEUE_SIZE-1;
2344
2345 for (const auto &&[sidenum, csegnum] : enumerate(segp.s.children))
2346 {
2347 const auto w = WALL_IS_DOORWAY(GameBitmaps, Textures, vcwallptr, segp, static_cast<sidenum_t>(sidenum));
2348 if ((w & WALL_IS_DOORWAY_FLAG::fly) || one_wall_hack)
2349 {
2350 #if DXX_BUILD_DESCENT == 2
2351 // If we get here and w == wall_is_doorway_result::wall, then we want to process through this wall, else not.
2352 if (IS_CHILD(csegnum)) {
2353 if (one_wall_hack)
2354 one_wall_hack--;
2355 } else
2356 continue;
2357 #endif
2358
2359 if (auto &&v = visited[csegnum])
2360 {
2361 }
2362 else
2363 {
2364 v = true;
2365 seg_queue[head++] = csegnum;
2366 head &= QUEUE_SIZE-1;
2367 if (head > tail) {
2368 if (head == tail + QUEUE_SIZE-1)
2369 Int3(); // queue overflow. Make it bigger!
2370 } else
2371 if (head+QUEUE_SIZE == tail + QUEUE_SIZE-1)
2372 Int3(); // queue overflow. Make it bigger!
2373
2374 if (!size_check || !boss_intersects_wall(vcvertptr, boss_objp, vcsegptridx(csegnum))) {
2375 a.emplace_back(csegnum);
2376 #if DXX_USE_EDITOR
2377 Selected_segs.emplace_back(csegnum);
2378 #endif
2379 if (a.size() >= a.max_size())
2380 {
2381 tail = head;
2382 break;
2383 }
2384 }
2385 }
2386 }
2387 }
2388 }
2389 // Last resort - add original seg even if boss doesn't fit in it
2390 if (a.empty())
2391 a.emplace_back(original_boss_seg);
2392 }
2393 }
2394
2395 // --------------------------------------------------------------------------------------------------------------------
2396 static void teleport_boss(const d_robot_info_array &Robot_info, const d_vclip_array &Vclip, fvmsegptridx &vmsegptridx, const vmobjptridx_t objp, const vms_vector &target_pos)
2397 {
2398 auto &BossUniqueState = LevelUniqueObjectState.BossState;
2399 auto &Boss_teleport_segs = LevelSharedBossState.Teleport_segs;
2400 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
2401 segnum_t rand_segnum;
2402 int rand_index;
2403 assert(!Boss_teleport_segs.empty());
2404 auto &Objects = LevelUniqueObjectState.Objects;
2405 auto &vmobjptr = Objects.vmptr;
2406
2407 // Pick a random segment from the list of boss-teleportable-to segments.
2408 rand_index = (d_rand() * Boss_teleport_segs.size()) >> 15;
2409 rand_segnum = Boss_teleport_segs[rand_index];
2410 Assert(rand_segnum <= Highest_segment_index);
2411
2412 #if DXX_USE_MULTIPLAYER
2413 if (Game_mode & GM_MULTI)
2414 multi_send_boss_teleport(objp, rand_segnum);
2415 #endif
2416
2417 const auto &&rand_segp = vmsegptridx(rand_segnum);
2418 auto &Vertices = LevelSharedVertexState.get_vertices();
2419 auto &vcvertptr = Vertices.vcptr;
2420 objp->pos = compute_segment_center(vcvertptr, rand_segp);
2421 obj_relink(vmobjptr, vmsegptr, objp, rand_segp);
2422
2423 BossUniqueState.Last_teleport_time = {GameTime64};
2424
2425 // make boss point right at player
2426 reconstruct_at(objp->orient, vm_vector_to_matrix, vm_vec_build_sub(target_pos, objp->pos));
2427
2428 digi_link_sound_to_pos(Vclip[vclip_index::morphing_robot].sound_num, rand_segp, sidenum_t::WLEFT, objp->pos, 0, F1_0);
2429 digi_kill_sound_linked_to_object( objp);
2430
2431 // After a teleport, boss can fire right away.
2432 ai_local *ailp = &objp->ctype.ai_info.ail;
2433 ailp->next_fire = 0;
2434 #if DXX_BUILD_DESCENT == 2
2435 ailp->next_fire2 = 0;
2436 #endif
2437 boss_link_see_sound(Robot_info, objp);
2438 }
2439
2440 }
2441
2442 // ----------------------------------------------------------------------
2443 void start_boss_death_sequence(d_level_unique_boss_state &BossUniqueState, const d_robot_info_array &Robot_info, object &objp)
2444 {
2445 auto &robptr = Robot_info[get_robot_id(objp)];
2446 if (robptr.boss_flag != boss_robot_id::None)
2447 {
2448 BossUniqueState.Boss_dying = 1;
2449 BossUniqueState.Boss_dying_start_time = {GameTime64};
2450 }
2451
2452 }
2453
2454 // ----------------------------------------------------------------------------------------------------------
2455 #if DXX_BUILD_DESCENT == 1
2456 namespace {
2457 static void do_boss_dying_frame(const d_robot_info_array &Robot_info, const vmobjptridx_t objp)
2458 {
2459 auto &BossUniqueState = LevelUniqueObjectState.BossState;
2460 const auto time_boss_dying = GameTime64 - BossUniqueState.Boss_dying_start_time;
2461 {
2462 auto &rotvel = objp->mtype.phys_info.rotvel;
2463 rotvel.x = time_boss_dying / 9;
2464 rotvel.y = time_boss_dying / 5;
2465 rotvel.z = time_boss_dying / 7;
2466 }
2467
2468 if (BossUniqueState.Boss_dying_start_time + BOSS_DEATH_DURATION - BOSS_DEATH_SOUND_DURATION < GameTime64) {
2469 if (!BossUniqueState.Boss_dying_sound_playing)
2470 {
2471 BossUniqueState.Boss_dying_sound_playing = 1;
2472 digi_link_sound_to_object2(sound_effect::SOUND_BOSS_SHARE_DIE, objp, 0, F1_0*4, sound_stack::allow_stacking, vm_distance{F1_0*1024}); // F1_0*512 means play twice as loud
2473 } else if (d_rand() < FrameTime*16)
2474 create_small_fireball_on_object(objp, (F1_0 + d_rand()) * 8, 0);
2475 } else if (d_rand() < FrameTime*8)
2476 create_small_fireball_on_object(objp, (F1_0/2 + d_rand()) * 8, 1);
2477
2478 if (BossUniqueState.Boss_dying_start_time + BOSS_DEATH_DURATION < GameTime64 || GameTime64+(F1_0*2) < BossUniqueState.Boss_dying_start_time)
2479 {
2480 BossUniqueState.Boss_dying_start_time = {GameTime64}; // make sure following only happens one time!
2481 do_controlcen_destroyed_stuff(object_none);
2482 explode_object(LevelUniqueObjectState, Robot_info, LevelSharedSegmentState, LevelUniqueSegmentState, objp, F1_0/4);
2483 digi_link_sound_to_object2(sound_effect::SOUND_BADASS_EXPLOSION, objp, 0, F2_0, sound_stack::allow_stacking, vm_distance{F1_0*512});
2484 }
2485 }
2486
2487 static int do_any_robot_dying_frame(const d_robot_info_array &, vmobjptridx_t)
2488 {
2489 return 0;
2490 }
2491 }
2492 #elif DXX_BUILD_DESCENT == 2
2493 // objp points at a boss. He was presumably just hit and he's supposed to create a bot at the hit location *pos.
2494 imobjptridx_t boss_spew_robot(const d_robot_info_array &Robot_info, const object_base &objp, const vms_vector &pos)
2495 {
2496 auto &Objects = LevelUniqueObjectState.Objects;
2497 auto &vcobjptr = Objects.vcptr;
2498 const auto boss_index = build_boss_robot_index_from_boss_robot_id(Robot_info[get_robot_id(objp)].boss_flag);
2499 assert(Boss_spew_more.valid_index(boss_index));
2500
2501 auto &Segments = LevelUniqueSegmentState.get_segments();
2502 const auto &&segnum = find_point_seg(LevelSharedSegmentState, LevelUniqueSegmentState, pos, Segments.vmptridx(objp.segnum));
2503 if (segnum == segment_none) {
2504 return object_none;
2505 }
2506
2507 const auto &&newobjp = create_gated_robot(Robot_info, Vclip, vcobjptr, segnum, Spew_bots[boss_index][(Max_spew_bots[boss_index] * d_rand()) >> 15], &pos);
2508
2509 // Make spewed robot come tumbling out as if blasted by a flash missile.
2510 if (newobjp != object_none) {
2511 int force_val;
2512
2513 force_val = F1_0/FrameTime;
2514
2515 if (force_val) {
2516 newobjp->ctype.ai_info.SKIP_AI_COUNT += force_val;
2517 newobjp->mtype.phys_info.rotthrust.x = ((d_rand() - 16384) * force_val)/16;
2518 newobjp->mtype.phys_info.rotthrust.y = ((d_rand() - 16384) * force_val)/16;
2519 newobjp->mtype.phys_info.rotthrust.z = ((d_rand() - 16384) * force_val)/16;
2520 newobjp->mtype.phys_info.flags |= PF_USES_THRUST;
2521
2522 // Now, give a big initial velocity to get moving away from boss.
2523 vm_vec_sub(newobjp->mtype.phys_info.velocity, pos, objp.pos);
2524 vm_vec_normalize_quick(newobjp->mtype.phys_info.velocity);
2525 vm_vec_scale(newobjp->mtype.phys_info.velocity, F1_0*128);
2526 }
2527 }
2528
2529 return newobjp;
2530 }
2531
2532 // ----------------------------------------------------------------------
2533 void start_robot_death_sequence(object &obj)
2534 {
2535 auto &ai_info = obj.ctype.ai_info;
2536 ai_info.dying_start_time = {GameTime64};
2537 ai_info.dying_sound_playing = 0;
2538 ai_info.SKIP_AI_COUNT = 0;
2539 }
2540
2541 namespace {
2542
2543 // ----------------------------------------------------------------------
2544 // General purpose robot-dies-with-death-roll-and-groan code.
2545 // Return true if object just died.
2546 // scale: F1_0*4 for boss, much smaller for much smaller guys
2547 static int do_robot_dying_frame(const vmobjptridx_t objp, fix64 start_time, fix roll_duration, sbyte *dying_sound_playing, const sound_effect death_sound, fix expl_scale, fix sound_scale)
2548 {
2549 fix sound_duration;
2550
2551 if (!roll_duration)
2552 roll_duration = F1_0/4;
2553
2554 objp->mtype.phys_info.rotvel.x = (GameTime64 - start_time)/9;
2555 objp->mtype.phys_info.rotvel.y = (GameTime64 - start_time)/5;
2556 objp->mtype.phys_info.rotvel.z = (GameTime64 - start_time)/7;
2557
2558 if (const auto SndDigiSampleRate = underlying_value(GameArg.SndDigiSampleRate))
2559 sound_duration = fixdiv(GameSounds[digi_xlat_sound(death_sound)].length, SndDigiSampleRate);
2560 else
2561 sound_duration = F1_0;
2562
2563 if (start_time + roll_duration - sound_duration < GameTime64) {
2564 if (!*dying_sound_playing) {
2565 *dying_sound_playing = 1;
2566 digi_link_sound_to_object2(death_sound, objp, 0, sound_scale, sound_stack::allow_stacking, vm_distance{sound_scale*256}); // F1_0*512 means play twice as loud
2567 } else if (d_rand() < FrameTime*16)
2568 create_small_fireball_on_object(objp, (F1_0 + d_rand()) * (16 * expl_scale/F1_0)/8, 0);
2569 } else if (d_rand() < FrameTime*8)
2570 create_small_fireball_on_object(objp, (F1_0/2 + d_rand()) * (16 * expl_scale/F1_0)/8, 1);
2571
2572 if (start_time + roll_duration < GameTime64 || GameTime64+(F1_0*2) < start_time)
2573 return 1;
2574 else
2575 return 0;
2576 }
2577
2578 // ----------------------------------------------------------------------
2579 static void do_boss_dying_frame(const d_robot_info_array &Robot_info, const vmobjptridx_t objp)
2580 {
2581 auto &BossUniqueState = LevelUniqueObjectState.BossState;
2582 int rval;
2583
2584 rval = do_robot_dying_frame(objp, BossUniqueState.Boss_dying_start_time, BOSS_DEATH_DURATION, &BossUniqueState.Boss_dying_sound_playing, Robot_info[get_robot_id(objp)].deathroll_sound, F1_0*4, F1_0*4);
2585
2586 if (rval)
2587 {
2588 BossUniqueState.Boss_dying_start_time = {GameTime64}; // make sure following only happens one time!
2589 do_controlcen_destroyed_stuff(object_none);
2590 explode_object(LevelUniqueObjectState, Robot_info, LevelSharedSegmentState, LevelUniqueSegmentState, objp, F1_0/4);
2591 digi_link_sound_to_object2(sound_effect::SOUND_BADASS_EXPLOSION, objp, 0, F2_0, sound_stack::allow_stacking, vm_distance{F1_0*512});
2592 }
2593 }
2594
2595 // ----------------------------------------------------------------------
2596 static int do_any_robot_dying_frame(const d_robot_info_array &Robot_info, const vmobjptridx_t objp)
2597 {
2598 if (objp->ctype.ai_info.dying_start_time) {
2599 int rval, death_roll;
2600
2601 death_roll = Robot_info[get_robot_id(objp)].death_roll;
2602 rval = do_robot_dying_frame(objp, objp->ctype.ai_info.dying_start_time, min(death_roll/2+1,6)*F1_0, &objp->ctype.ai_info.dying_sound_playing, Robot_info[get_robot_id(objp)].deathroll_sound, death_roll*F1_0/8, death_roll*F1_0/2);
2603
2604 if (rval) {
2605 objp->ctype.ai_info.dying_start_time = {GameTime64}; // make sure following only happens one time!
2606 explode_object(LevelUniqueObjectState, Robot_info, LevelSharedSegmentState, LevelUniqueSegmentState, objp, F1_0/4);
2607 digi_link_sound_to_object2(sound_effect::SOUND_BADASS_EXPLOSION, objp, 0, F2_0, sound_stack::allow_stacking, vm_distance{F1_0*512});
2608 if (Current_level_num < 0)
2609 {
2610 const auto id = get_robot_id(objp);
2611 if (Robot_info[id].thief)
2612 recreate_thief(Robot_info, id);
2613 }
2614 }
2615
2616 return 1;
2617 }
2618
2619 return 0;
2620 }
2621
2622 }
2623 #endif
2624
2625 // --------------------------------------------------------------------------------------------------------------------
2626 // Called for an AI object if it is fairly aware of the player.
2627 // awareness_level is in 0..100. Larger numbers indicate greater awareness (eg, 99 if firing at player).
2628 // In a given frame, might not get called for an object, or might be called more than once.
2629 // The fact that this routine is not called for a given object does not mean that object is not interested in the player.
2630 // Objects are moved by physics, so they can move even if not interested in a player. However, if their velocity or
2631 // orientation is changing, this routine will be called.
2632 // Return value:
2633 // 0 this player IS NOT allowed to move this robot.
2634 // 1 this player IS allowed to move this robot.
2635 static int ai_multiplayer_awareness(const vmobjptridx_t objp, int awareness_level)
2636 {
2637 int rval{1};
2638 #if DXX_USE_MULTIPLAYER
2639 if (Game_mode & GM_MULTI) {
2640 if (awareness_level == 0)
2641 return 0;
2642 rval = multi_can_move_robot(objp, awareness_level);
2643 }
2644 #else
2645 (void)objp;
2646 (void)awareness_level;
2647 #endif
2648 return rval;
2649 }
2650
2651 }
2652
2653 #ifndef NDEBUG
2654 namespace {
2655 fix Prev_boss_shields = -1;
2656 }
2657 #endif
2658
2659 namespace dsx {
2660 namespace {
2661
2662 #if DXX_BUILD_DESCENT == 1
2663 #define do_d1_boss_stuff(Robot_info,FS,FO,PV) do_d1_boss_stuff(Robot_info,FS,FO)
2664 #endif
2665
2666 // --------------------------------------------------------------------------------------------------------------------
2667 // Do special stuff for a boss.
2668 static void do_d1_boss_stuff(const d_robot_info_array &Robot_info, fvmsegptridx &vmsegptridx, const vmobjptridx_t objp, const player_visibility_state player_visibility)
2669 {
2670 auto &BossUniqueState = LevelUniqueObjectState.BossState;
2671 auto &Objects = LevelUniqueObjectState.Objects;
2672 auto &vmobjptr = Objects.vmptr;
2673 #ifndef NDEBUG
2674 if (objp->shields != Prev_boss_shields) {
2675 Prev_boss_shields = objp->shields;
2676 }
2677 #endif
2678
2679 #if DXX_BUILD_DESCENT == 2
2680 if (!EMULATING_D1 && !player_is_visible(player_visibility) && !BossUniqueState.Boss_hit_this_frame)
2681 return;
2682 #endif
2683
2684 if (!BossUniqueState.Boss_dying) {
2685 const auto Boss_cloak_start_time = BossUniqueState.Boss_cloak_start_time;
2686 if (objp->ctype.ai_info.CLOAKED == 1) {
2687 if (GameTime64 - Boss_cloak_start_time > Boss_cloak_duration / 3 &&
2688 (Boss_cloak_start_time + Boss_cloak_duration) - GameTime64 > Boss_cloak_duration / 3 &&
2689 GameTime64 - BossUniqueState.Last_teleport_time > LevelSharedBossState.Boss_teleport_interval)
2690 {
2691 if (ai_multiplayer_awareness(objp, 98))
2692 teleport_boss(Robot_info, Vclip, vmsegptridx, objp, get_local_plrobj().pos);
2693 } else if (BossUniqueState.Boss_hit_this_frame) {
2694 BossUniqueState.Boss_hit_this_frame = 0;
2695 BossUniqueState.Last_teleport_time -= LevelSharedBossState.Boss_teleport_interval / 4;
2696 }
2697
2698 if (GameTime64 > (Boss_cloak_start_time + Boss_cloak_duration) ||
2699 GameTime64 < Boss_cloak_start_time)
2700 objp->ctype.ai_info.CLOAKED = 0;
2701 } else {
2702 if (BossUniqueState.Boss_hit_this_frame ||
2703 GameTime64 - (Boss_cloak_start_time + Boss_cloak_duration) > LevelSharedBossState.Boss_cloak_interval)
2704 {
2705 if (ai_multiplayer_awareness(objp, 95))
2706 {
2707 BossUniqueState.Boss_hit_this_frame = 0;
2708 BossUniqueState.Boss_cloak_start_time = {GameTime64};
2709 objp->ctype.ai_info.CLOAKED = 1;
2710 #if DXX_USE_MULTIPLAYER
2711 if (Game_mode & GM_MULTI)
2712 multi_send_boss_cloak(objp);
2713 #endif
2714 }
2715 }
2716 }
2717 } else
2718 do_boss_dying_frame(Robot_info, objp);
2719
2720 }
2721
2722 // --------------------------------------------------------------------------------------------------------------------
2723 // Do special stuff for a boss.
2724 static void do_super_boss_stuff(const d_robot_info_array &Robot_info, fvmsegptridx &vmsegptridx, const vmobjptridx_t objp, const fix dist_to_player, const player_visibility_state player_visibility)
2725 {
2726 auto &BossUniqueState = LevelUniqueObjectState.BossState;
2727 static int eclip_state = 0;
2728 do_d1_boss_stuff(Robot_info, vmsegptridx, objp, player_visibility);
2729
2730 // Only master player can cause gating to occur.
2731 const auto multiplayer{Game_mode & GM_MULTI};
2732 #if DXX_USE_MULTIPLAYER
2733 if (multiplayer && !multi_i_am_master())
2734 return;
2735 #endif
2736
2737 if (
2738 multiplayer ||
2739 dist_to_player < /* BOSS_TO_PLAYER_GATE_DISTANCE = */ (F1_0 * 150) ||
2740 player_is_visible(player_visibility)
2741 ) {
2742 const auto Gate_interval = GameUniqueState.Boss_gate_interval;
2743 if (GameTime64 - BossUniqueState.Last_gate_time > Gate_interval/2) {
2744 restart_effect(ECLIP_NUM_BOSS);
2745 if (eclip_state == 0) {
2746 #if DXX_USE_MULTIPLAYER
2747 if (multiplayer)
2748 multi_send_boss_start_gate(objp);
2749 #endif
2750 eclip_state = 1;
2751 }
2752 }
2753 else {
2754 stop_effect(ECLIP_NUM_BOSS);
2755 if (eclip_state == 1) {
2756 #if DXX_USE_MULTIPLAYER
2757 if (multiplayer)
2758 multi_send_boss_stop_gate(objp);
2759 #endif
2760 eclip_state = 0;
2761 }
2762 }
2763
2764 if (GameTime64 - BossUniqueState.Last_gate_time > Gate_interval)
2765 if (ai_multiplayer_awareness(objp, 99)) {
2766 uint_fast32_t randtype = (d_rand() * MAX_GATE_INDEX) >> 15;
2767
2768 Assert(randtype < MAX_GATE_INDEX);
2769 const auto &&rtval = gate_in_robot(Robot_info, vmsegptridx, Super_boss_gate_list[randtype]);
2770 #if DXX_USE_MULTIPLAYER
2771 if (rtval != object_none && multiplayer)
2772 {
2773 multi_send_boss_create_robot(objp, rtval);
2774 }
2775 #else
2776 (void)rtval;
2777 #endif
2778 }
2779 }
2780 }
2781
2782 #if DXX_BUILD_DESCENT == 2
2783 static void do_d2_boss_stuff(fvmsegptridx &vmsegptridx, const vmobjptridx_t objp, const player_visibility_state player_visibility)
2784 {
2785 auto &BossUniqueState = LevelUniqueObjectState.BossState;
2786 auto &Objects = LevelUniqueObjectState.Objects;
2787 auto &vmobjptr = Objects.vmptr;
2788
2789 auto &Robot_info = LevelSharedRobotInfoState.Robot_info;
2790 const auto boss_index = build_boss_robot_index_from_boss_robot_id(Robot_info[get_robot_id(objp)].boss_flag);
2791 assert(Boss_spew_more.valid_index(boss_index));
2792
2793 #ifndef NDEBUG
2794 if (objp->shields != Prev_boss_shields) {
2795 Prev_boss_shields = objp->shields;
2796 }
2797 #endif
2798
2799 // @mk, 10/13/95: Reason:
2800 // Level 4 boss behind locked door. But he's allowed to teleport out of there. So he
2801 // teleports out of there right away, and blasts player right after first door.
2802 if (!player_is_visible(player_visibility) && GameTime64 - BossUniqueState.Boss_hit_time > F1_0 * 2)
2803 return;
2804
2805 if (!BossUniqueState.Boss_dying && Boss_teleports[boss_index]) {
2806 const auto Boss_cloak_start_time = BossUniqueState.Boss_cloak_start_time;
2807 if (objp->ctype.ai_info.CLOAKED == 1) {
2808 BossUniqueState.Boss_hit_time = {GameTime64}; // Keep the cloak:teleport process going.
2809 if (GameTime64 - Boss_cloak_start_time > Boss_cloak_duration / 3 &&
2810 (Boss_cloak_start_time + Boss_cloak_duration) - GameTime64 > Boss_cloak_duration / 3 &&
2811 GameTime64 - BossUniqueState.Last_teleport_time > LevelSharedBossState.Boss_teleport_interval)
2812 {
2813 if (ai_multiplayer_awareness(objp, 98))
2814 teleport_boss(LevelSharedRobotInfoState.Robot_info, Vclip, vmsegptridx, objp, get_local_plrobj().pos);
2815 } else if (GameTime64 - BossUniqueState.Boss_hit_time > F1_0*2) {
2816 BossUniqueState.Last_teleport_time -= LevelSharedBossState.Boss_teleport_interval / 4;
2817 }
2818
2819 if (GameTime64 > (Boss_cloak_start_time + Boss_cloak_duration) ||
2820 GameTime64 < Boss_cloak_start_time)
2821 objp->ctype.ai_info.CLOAKED = 0;
2822 } else if (GameTime64 - (Boss_cloak_start_time + Boss_cloak_duration) > LevelSharedBossState.Boss_cloak_interval ||
2823 GameTime64 - (Boss_cloak_start_time + Boss_cloak_duration) < -Boss_cloak_duration) {
2824 if (ai_multiplayer_awareness(objp, 95)) {
2825 BossUniqueState.Boss_cloak_start_time = {GameTime64};
2826 objp->ctype.ai_info.CLOAKED = 1;
2827 #if DXX_USE_MULTIPLAYER
2828 if (Game_mode & GM_MULTI)
2829 multi_send_boss_cloak(objp);
2830 #endif
2831 }
2832 }
2833 }
2834
2835 }
2836 #endif
2837
2838 static void ai_multi_send_robot_position(object &obj, int force)
2839 {
2840 #if DXX_USE_MULTIPLAYER
2841 if (Game_mode & GM_MULTI)
2842 multi_send_robot_position(obj, force != -1 ? multi_send_robot_position_priority::_2 : multi_send_robot_position_priority::_1);
2843 #else
2844 (void)obj;
2845 (void)force;
2846 #endif
2847 return;
2848 }
2849
2850 // --------------------------------------------------------------------------------------------------------------------
2851 // Returns true if this object should be allowed to fire at the player.
2852 static int maybe_ai_do_actual_firing_stuff(object &obj)
2853 {
2854 if (Game_mode & GM_MULTI)
2855 {
2856 auto &aip = obj.ctype.ai_info;
2857 if (aip.GOAL_STATE != AIS_FLIN && get_robot_id(obj) != robot_id::brain)
2858 {
2859 const auto s = aip.CURRENT_STATE;
2860 if (s == AIS_FIRE)
2861 {
2862 static_assert(AIS_FIRE != 0, "AIS_FIRE must be nonzero for this shortcut to work properly.");
2863 return s;
2864 }
2865 }
2866 }
2867 return 0;
2868 }
2869
2870 #if DXX_BUILD_DESCENT == 1
2871 static void ai_do_actual_firing_stuff(const d_robot_info_array &Robot_info, fvmobjptridx &vmobjptridx, const vmobjptridx_t obj, ai_static *const aip, ai_local &ailp, const robot_info &robptr, const fix dist_to_player, robot_gun_point &gun_point, const robot_to_player_visibility_state &player_visibility, const int object_animates, const player_info &player_info, robot_gun_number)
2872 {
2873 auto &vec_to_player = player_visibility.vec_to_player;
2874 fix dot;
2875
2876 if (player_visibility.visibility == player_visibility_state::visible_and_in_field_of_view)
2877 {
2878 // Changed by mk, 01/04/94, onearm would take about 9 seconds until he can fire at you.
2879 // if (((!object_animates) || (ailp->achieved_state[aip->CURRENT_GUN] == AIS_FIRE)) && (ailp->next_fire <= 0))
2880 if (!object_animates || ready_to_fire_any_weapon(robptr, ailp, 0)) {
2881 dot = vm_vec_build_dot(obj->orient.fvec, vec_to_player);
2882 if (dot >= 7*F1_0/8) {
2883 if (robot_gun_number_valid(robptr, aip->CURRENT_GUN))
2884 {
2885 if (robptr.attack_type == 1) {
2886 if (Player_dead_state != player_dead_state::exploded &&
2887 dist_to_player < obj->size + ConsoleObject->size + F1_0*2)
2888 {
2889 if (!ai_multiplayer_awareness(obj, ROBOT_FIRE_AGITATION-2))
2890 return;
2891 do_ai_robot_hit_attack(Robot_info, obj, vmobjptridx(ConsoleObject), obj->pos);
2892 } else {
2893 return;
2894 }
2895 } else {
2896 if (!gun_point.has_value()) {
2897 ;
2898 } else {
2899 if (!ai_multiplayer_awareness(obj, ROBOT_FIRE_AGITATION))
2900 return;
2901 ai_fire_laser_at_player(Robot_info, LevelSharedSegmentState, obj, player_info, gun_point, robot_gun_number::_0);
2902 }
2903 }
2904
2905 // Wants to fire, so should go into chase mode, probably.
2906 if (aip->behavior != ai_behavior::AIB_RUN_FROM && aip->behavior != ai_behavior::AIB_STILL && aip->behavior != ai_behavior::AIB_FOLLOW_PATH && (ailp.mode == ai_mode::AIM_FOLLOW_PATH || ailp.mode == ai_mode::AIM_STILL))
2907 ailp.mode = ai_mode::AIM_CHASE_OBJECT;
2908 }
2909
2910 aip->GOAL_STATE = AIS_RECO;
2911 ailp.goal_state[aip->CURRENT_GUN] = AIS_RECO;
2912 // Switch to next gun for next fire.
2913 aip->CURRENT_GUN = robot_advance_current_gun(robptr, aip->CURRENT_GUN);
2914 }
2915 }
2916 } else if (Weapon_info[robptr.weapon_type].homing_flag) {
2917 // Robots which fire homing weapons might fire even if they don't have a bead on the player.
2918 if ((!object_animates || ailp.achieved_state[aip->CURRENT_GUN] == AIS_FIRE)
2919 && ready_to_fire_weapon1(ailp, 0)
2920 && (vm_vec_dist_quick(Hit_pos, obj->pos) > F1_0*40)) {
2921 if (!ai_multiplayer_awareness(obj, ROBOT_FIRE_AGITATION))
2922 return;
2923 ai_fire_laser_at_player(Robot_info, LevelSharedSegmentState, obj, player_info, gun_point, robot_gun_number::_0);
2924
2925 aip->GOAL_STATE = AIS_RECO;
2926 ailp.goal_state[aip->CURRENT_GUN] = AIS_RECO;
2927 }
2928 // Switch to next gun for next fire.
2929 aip->CURRENT_GUN = robot_advance_current_gun(robptr, aip->CURRENT_GUN);
2930 }
2931 }
2932 #elif DXX_BUILD_DESCENT == 2
2933
2934 // --------------------------------------------------------------------------------------------------------------------
2935 // If fire_anyway, fire even if player is not visible. We're firing near where we believe him to be. Perhaps he's
2936 // lurking behind a corner.
2937 static void ai_do_actual_firing_stuff(const d_robot_info_array &Robot_info, fvmobjptridx &vmobjptridx, const vmobjptridx_t obj, ai_static *const aip, ai_local &ailp, const robot_info &robptr, const fix dist_to_player, robot_gun_point &gun_point, const robot_to_player_visibility_state &player_visibility, const int object_animates, const player_info &player_info, const robot_gun_number gun_num)
2938 {
2939 auto &vec_to_player = player_visibility.vec_to_player;
2940 fix dot;
2941
2942 if (player_visibility.visibility == player_visibility_state::visible_and_in_field_of_view || Dist_to_last_fired_upon_player_pos < FIRE_AT_NEARBY_PLAYER_THRESHOLD)
2943 {
2944 vms_vector fire_pos;
2945
2946 fire_pos = Believed_player_pos;
2947
2948 // Hack: If visibility not == 2, we're here because we're firing at a nearby player.
2949 // So, fire at Last_fired_upon_player_pos instead of the player position.
2950 if (!robptr.attack_type && player_visibility.visibility != player_visibility_state::visible_and_in_field_of_view)
2951 fire_pos = Last_fired_upon_player_pos;
2952
2953 // Changed by mk, 01/04/95, onearm would take about 9 seconds until he can fire at you.
2954 // Above comment corrected. Date changed from 1994, to 1995. Should fix some very subtle bugs, as well as not cause me to wonder, in the future, why I was writing AI code for onearm ten months before he existed.
2955 if (!object_animates || ready_to_fire_any_weapon(robptr, ailp, 0)) {
2956 dot = vm_vec_build_dot(obj->orient.fvec, vec_to_player);
2957 if ((dot >= 7*F1_0/8) || ((dot > F1_0/4) && robptr.boss_flag != boss_robot_id::None))
2958 {
2959 if (robot_gun_number_valid(robptr, gun_num))
2960 {
2961 if (robptr.attack_type == 1) {
2962 if (Player_dead_state != player_dead_state::exploded &&
2963 dist_to_player < obj->size + ConsoleObject->size + F1_0*2)
2964 {
2965 if (!ai_multiplayer_awareness(obj, ROBOT_FIRE_AGITATION-2))
2966 return;
2967 do_ai_robot_hit_attack(Robot_info, obj, vmobjptridx(ConsoleObject), obj->pos);
2968 } else {
2969 return;
2970 }
2971 } else {
2972 if (!gun_point.has_value()) {
2973 ;
2974 } else {
2975 if (!ai_multiplayer_awareness(obj, ROBOT_FIRE_AGITATION))
2976 return;
2977 // New, multi-weapon-type system, 06/05/95 (life is slipping away...)
2978 if (ready_to_fire_weapon1(ailp, 0)) {
2979 ai_fire_laser_at_player(Robot_info, LevelSharedSegmentState, obj, player_info, gun_point, gun_num, fire_pos);
2980 Last_fired_upon_player_pos = fire_pos;
2981 }
2982 if (gun_num != robot_gun_number::_0)
2983 {
2984 if (ready_to_fire_weapon2(robptr, ailp, 0)) {
2985 ai_fire_laser_at_player(Robot_info, LevelSharedSegmentState, obj, player_info, gun_point, robot_gun_number::_0, fire_pos);
2986 Last_fired_upon_player_pos = fire_pos;
2987 }
2988 }
2989 }
2990 }
2991
2992 // Wants to fire, so should go into chase mode, probably.
2993 if ( (aip->behavior != ai_behavior::AIB_RUN_FROM)
2994 && (aip->behavior != ai_behavior::AIB_STILL)
2995 && (aip->behavior != ai_behavior::AIB_SNIPE)
2996 && (aip->behavior != ai_behavior::AIB_FOLLOW)
2997 && (!robptr.attack_type)
2998 && (ailp.mode == ai_mode::AIM_FOLLOW_PATH || ailp.mode == ai_mode::AIM_STILL))
2999 ailp.mode = ai_mode::AIM_CHASE_OBJECT;
3000 }
3001
3002 aip->GOAL_STATE = AIS_RECO;
3003 ailp.goal_state[aip->CURRENT_GUN] = AIS_RECO;
3004
3005 // Switch to next gun for next fire. If has 2 gun types, select gun #1, if exists.
3006 aip->CURRENT_GUN = robot_advance_current_gun_prefer_second(robptr, aip->CURRENT_GUN);
3007 }
3008 }
3009 }
3010 else if ((!robptr.attack_type && Weapon_info[Robot_info[get_robot_id(obj)].weapon_type].homing_flag) || ((Robot_info[get_robot_id(obj)].weapon_type2 != weapon_none && Weapon_info[Robot_info[get_robot_id(obj)].weapon_type2].homing_flag)))
3011 {
3012 // Robots which fire homing weapons might fire even if they don't have a bead on the player.
3013 if ((!object_animates || ailp.achieved_state[aip->CURRENT_GUN] == AIS_FIRE)
3014 && (
3015 (aip->CURRENT_GUN != robot_gun_number::_0 && ready_to_fire_weapon1(ailp, 0)) ||
3016 (aip->CURRENT_GUN == robot_gun_number::_0 && ready_to_fire_weapon2(robptr, ailp, 0)))
3017 && (vm_vec_dist_quick(Hit_pos, obj->pos) > F1_0*40)) {
3018 if (!ai_multiplayer_awareness(obj, ROBOT_FIRE_AGITATION))
3019 return;
3020 robot_gun_point gun_point;
3021 ai_fire_laser_at_player(Robot_info, LevelSharedSegmentState, obj, player_info, gun_point, gun_num, Believed_player_pos);
3022
3023 aip->GOAL_STATE = AIS_RECO;
3024 ailp.goal_state[aip->CURRENT_GUN] = AIS_RECO;
3025 }
3026 // Switch to next gun for next fire.
3027 aip->CURRENT_GUN = robot_advance_current_gun(robptr, aip->CURRENT_GUN);
3028 } else {
3029 // ---------------------------------------------------------------
3030 vms_vector vec_to_last_pos;
3031 if (d_rand()/2 < fixmul(FrameTime, (underlying_value(GameUniqueState.Difficulty_level) << 12) + 0x4000)) {
3032 if ((!object_animates || ready_to_fire_any_weapon(robptr, ailp, 0)) && (Dist_to_last_fired_upon_player_pos < FIRE_AT_NEARBY_PLAYER_THRESHOLD)) {
3033 vm_vec_normalized_dir_quick(vec_to_last_pos, Believed_player_pos, obj->pos);
3034 dot = vm_vec_build_dot(obj->orient.fvec, vec_to_last_pos);
3035 if (dot >= 7*F1_0/8) {
3036 if (robot_gun_number_valid(robptr, aip->CURRENT_GUN))
3037 {
3038 if (robptr.attack_type == 1) {
3039 if (Player_dead_state != player_dead_state::exploded &&
3040 dist_to_player < obj->size + ConsoleObject->size + F1_0*2)
3041 {
3042 if (!ai_multiplayer_awareness(obj, ROBOT_FIRE_AGITATION-2))
3043 return;
3044 do_ai_robot_hit_attack(Robot_info, obj, vmobjptridx(ConsoleObject), obj->pos);
3045 } else {
3046 return;
3047 }
3048 } else {
3049 if (!gun_point.has_value()) {
3050 ;
3051 } else {
3052 if (!ai_multiplayer_awareness(obj, ROBOT_FIRE_AGITATION))
3053 return;
3054 // New, multi-weapon-type system, 06/05/95 (life is slipping away...)
3055 if (ready_to_fire_weapon1(ailp, 0))
3056 {
3057 ai_fire_laser_at_player(Robot_info, LevelSharedSegmentState, obj, player_info, gun_point, gun_num, Last_fired_upon_player_pos);
3058 }
3059 if (gun_num != robot_gun_number::_0)
3060 {
3061 if (ready_to_fire_weapon2(robptr, ailp, 0)) {
3062 ai_fire_laser_at_player(Robot_info, LevelSharedSegmentState, obj, player_info, gun_point, robot_gun_number::_0, Last_fired_upon_player_pos);
3063 }
3064 }
3065 }
3066 }
3067
3068 // Wants to fire, so should go into chase mode, probably.
3069 if (aip->behavior != ai_behavior::AIB_RUN_FROM && aip->behavior != ai_behavior::AIB_STILL && aip->behavior != ai_behavior::AIB_SNIPE && aip->behavior != ai_behavior::AIB_FOLLOW && (ailp.mode == ai_mode::AIM_FOLLOW_PATH || ailp.mode == ai_mode::AIM_STILL))
3070 ailp.mode = ai_mode::AIM_CHASE_OBJECT;
3071 }
3072 aip->GOAL_STATE = AIS_RECO;
3073 ailp.goal_state[aip->CURRENT_GUN] = AIS_RECO;
3074
3075 // Switch to next gun for next fire.
3076 aip->CURRENT_GUN = robot_advance_current_gun_prefer_second(robptr, aip->CURRENT_GUN);
3077 }
3078 }
3079 }
3080
3081 // ---------------------------------------------------------------
3082 }
3083 }
3084
3085 }
3086
3087 // ----------------------------------------------------------------------------
3088 void init_ai_frame(const player_flags powerup_flags, const control_info &Controls)
3089 {
3090 Dist_to_last_fired_upon_player_pos = vm_vec_dist_quick(Last_fired_upon_player_pos, Believed_player_pos);
3091
3092 if (!(powerup_flags & PLAYER_FLAGS_CLOAKED) ||
3093 (powerup_flags & PLAYER_FLAGS_HEADLIGHT_ON) ||
3094 (Afterburner_charge && Controls.state.afterburner && (powerup_flags & PLAYER_FLAGS_AFTERBURNER)))
3095 {
3096 ai_do_cloak_stuff();
3097 }
3098 }
3099
3100 namespace {
3101
3102 // ----------------------------------------------------------------------------
3103 // Make a robot near the player snipe.
3104 static void make_nearby_robot_snipe(fvmsegptr &vmsegptr, const object &robot, const robot_info &robptr, const player_flags powerup_flags)
3105 {
3106 auto &Objects = LevelUniqueObjectState.Objects;
3107 auto &vmobjptridx = Objects.vmptridx;
3108 std::array<segnum_t, /* MNRS_SEG_MAX = */ 70> bfs_list;
3109 /* Passing powerup_flags here seems wrong. Sniping robots do not
3110 * open doors, so they should not care what doors the player can
3111 * open. However, passing powerup_flags here maintains the
3112 * semantics that past versions used.
3113 */
3114 const auto bfs_length = create_bfs_list(robot, robptr, ConsoleObject->segnum, powerup_flags, bfs_list);
3115
3116 auto &Robot_info = LevelSharedRobotInfoState.Robot_info;
3117 range_for (auto &i, partial_const_range(bfs_list, bfs_length)) {
3118 for (auto &obj : objects_in<object>(vmsegptr(i), vmobjptridx, vmsegptr))
3119 {
3120 if (obj.type != OBJ_ROBOT)
3121 continue;
3122 if (obj.ctype.ai_info.behavior == ai_behavior::AIB_SNIPE)
3123 continue;
3124 if (obj.ctype.ai_info.behavior == ai_behavior::AIB_RUN_FROM)
3125 continue;
3126 const auto rid = get_robot_id(obj);
3127 if (rid == robot_id::brain)
3128 continue;
3129 auto &robptr = Robot_info[rid];
3130 if (robptr.boss_flag == boss_robot_id::None && !robot_is_companion(robptr))
3131 {
3132 obj.ctype.ai_info.behavior = ai_behavior::AIB_SNIPE;
3133 obj.ctype.ai_info.ail.mode = ai_mode::AIM_SNIPE_ATTACK;
3134 return;
3135 }
3136 }
3137 }
3138 }
3139
3140 static int openable_door_on_near_path(fvcsegptr &vcsegptr, fvcwallptr &vcwallptr, const object &obj, const ai_static &aip)
3141 {
3142 const auto path_length = aip.path_length;
3143 if (path_length < 1)
3144 return 0;
3145 if (const auto r = openable_doors_in_segment(vcwallptr, vcsegptr(obj.segnum)).has_value())
3146 return r;
3147 if (path_length < 2)
3148 return 0;
3149 size_t idx;
3150 idx = aip.hide_index + aip.cur_path_index + aip.PATH_DIR;
3151 /* Hack: Point_segs[idx].segnum should never be none here, but
3152 * sometimes the guidebot has a none. Guard against the bogus none
3153 * until someone can track down why the guidebot does this.
3154 */
3155 if (idx < Point_segs.size() && Point_segs[idx].segnum != segment_none)
3156 {
3157 if (const auto r = openable_doors_in_segment(vcwallptr, vcsegptr(Point_segs[idx].segnum)).has_value())
3158 return r;
3159 }
3160 if (path_length < 3)
3161 return 0;
3162 idx = aip.hide_index + aip.cur_path_index + 2*aip.PATH_DIR;
3163 if (idx < Point_segs.size() && Point_segs[idx].segnum != segment_none)
3164 {
3165 if (const auto r = openable_doors_in_segment(vcwallptr, vcsegptr(Point_segs[idx].segnum)).has_value())
3166 return r;
3167 }
3168 return 0;
3169 }
3170
3171 static unsigned guidebot_should_fire_flare(fvcobjptr &vcobjptr, fvcsegptr &vcsegptr, fvcwallptr &vcwallptr, d_unique_buddy_state &BuddyState, const robot_info &robptr, const object &buddy_obj)
3172 {
3173 auto &ais = buddy_obj.ctype.ai_info;
3174 auto &ail = ais.ail;
3175 if (const auto r = ready_to_fire_any_weapon(robptr, ail, 0))
3176 {
3177 }
3178 else
3179 return r;
3180 if (const auto r = openable_door_on_near_path(vcsegptr, vcwallptr, buddy_obj, ais))
3181 return r;
3182 if (ail.mode != ai_mode::AIM_GOTO_PLAYER)
3183 return 0;
3184 auto &plr = get_player_controlling_guidebot(BuddyState, Players);
3185 if (plr.objnum == object_none)
3186 /* should never happen */
3187 return 0;
3188 auto &plrobj = *vcobjptr(plr.objnum);
3189 if (plrobj.type != OBJ_PLAYER)
3190 return 0;
3191 vms_vector vec_to_controller;
3192 const auto dist_to_controller = vm_vec_normalized_dir_quick(vec_to_controller, plrobj.pos, buddy_obj.pos);
3193 if (dist_to_controller >= 3 * MIN_ESCORT_DISTANCE / 2)
3194 return 0;
3195 if (vm_vec_build_dot(plrobj.orient.fvec, vec_to_controller) <= -F1_0 / 4)
3196 return 0;
3197 return 1;
3198 }
3199 #endif
3200
3201 #ifdef NDEBUG
3202 static bool is_break_object(vcobjidx_t)
3203 {
3204 return false;
3205 }
3206 #else
3207 dxx_compiler_attribute_used
3208 static objnum_t Break_on_object = object_none;
3209
3210 static bool is_break_object(const vcobjidx_t robot)
3211 {
3212 return Break_on_object == robot;
3213 }
3214 #endif
3215
3216 static bool skip_ai_for_time_splice(const vcobjptridx_t robot, const robot_info &robptr, const vm_distance &dist_to_player)
3217 {
3218 if (unlikely(is_break_object(robot)))
3219 // don't time slice if we're interested in this object.
3220 return false;
3221 const auto &aip = robot->ctype.ai_info;
3222 const auto &ailp = aip.ail;
3223 #if DXX_BUILD_DESCENT == 1
3224 (void)robptr;
3225 if (static_cast<uint8_t>(ailp.player_awareness_type) < static_cast<uint8_t>(player_awareness_type_t::PA_WEAPON_ROBOT_COLLISION) - 1)
3226 { // If robot got hit, he gets to attack player always!
3227 {
3228 if ((dist_to_player > F1_0*250) && (ailp.time_since_processed <= F1_0*2))
3229 return true;
3230 else if (!((aip.behavior == ai_behavior::AIB_STATION) && (ailp.mode == ai_mode::AIM_FOLLOW_PATH) && (aip.hide_segment != robot->segnum))) {
3231 if ((dist_to_player > F1_0*150) && (ailp.time_since_processed <= F1_0))
3232 return true;
3233 else if ((dist_to_player > F1_0*100) && (ailp.time_since_processed <= F1_0/2))
3234 return true;
3235 }
3236 }
3237 }
3238 #elif DXX_BUILD_DESCENT == 2
3239 if (!((aip.behavior == ai_behavior::AIB_SNIPE) && (ailp.mode != ai_mode::AIM_SNIPE_WAIT)) && !robot_is_companion(robptr) && !robot_is_thief(robptr) && static_cast<uint8_t>(ailp.player_awareness_type) < static_cast<uint8_t>(player_awareness_type_t::PA_WEAPON_ROBOT_COLLISION) - 1)
3240 { // If robot got hit, he gets to attack player always!
3241 {
3242 if ((aip.behavior == ai_behavior::AIB_STATION) && (ailp.mode == ai_mode::AIM_FOLLOW_PATH) && (aip.hide_segment != robot->segnum)) {
3243 if (dist_to_player > F1_0*250) // station guys not at home always processed until 250 units away.
3244 return true;
3245 }
3246 else if (!player_is_visible(ailp.previous_visibility) && ((dist_to_player >> 7) > ailp.time_since_processed))
3247 { // 128 units away (6.4 segments) processed after 1 second.
3248 return true;
3249 }
3250 }
3251 }
3252 #endif
3253 return false;
3254 }
3255
3256 }
3257
3258 // --------------------------------------------------------------------------------------------------------------------
3259 void do_ai_frame(const d_level_shared_robot_info_state &LevelSharedRobotInfoState, const vmobjptridx_t obj)
3260 {
3261 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
3262 auto &Vertices = LevelSharedVertexState.get_vertices();
3263 const auto Difficulty_level = GameUniqueState.Difficulty_level;
3264 const objnum_t &objnum = obj;
3265 ai_static *const aip = &obj->ctype.ai_info;
3266 ai_local &ailp = obj->ctype.ai_info.ail;
3267 int obj_ref;
3268 int object_animates;
3269 vms_vector vis_vec_pos;
3270 auto &Objects = LevelUniqueObjectState.Objects;
3271 auto &vmobjptr = Objects.vmptr;
3272 auto &vmobjptridx = Objects.vmptridx;
3273
3274 #if DXX_BUILD_DESCENT == 2
3275 auto &BuddyState = LevelUniqueObjectState.BuddyState;
3276 auto &vcobjptr = Objects.vcptr;
3277 ailp.next_action_time -= FrameTime;
3278 #endif
3279
3280 if (aip->SKIP_AI_COUNT) {
3281 aip->SKIP_AI_COUNT--;
3282 #if DXX_BUILD_DESCENT == 2
3283 if (obj->mtype.phys_info.flags & PF_USES_THRUST) {
3284 obj->mtype.phys_info.rotthrust.x = (obj->mtype.phys_info.rotthrust.x * 15)/16;
3285 obj->mtype.phys_info.rotthrust.y = (obj->mtype.phys_info.rotthrust.y * 15)/16;
3286 obj->mtype.phys_info.rotthrust.z = (obj->mtype.phys_info.rotthrust.z * 15)/16;
3287 if (!aip->SKIP_AI_COUNT)
3288 obj->mtype.phys_info.flags &= ~PF_USES_THRUST;
3289 }
3290 #endif
3291 return;
3292 }
3293
3294 auto &Robot_info = LevelSharedRobotInfoState.Robot_info;
3295 #if DXX_BUILD_DESCENT == 2
3296 auto &Station = LevelUniqueFuelcenterState.Station;
3297 #endif
3298 auto &robptr = Robot_info[get_robot_id(obj)];
3299 Assert(robptr.always_0xabcd == 0xabcd);
3300
3301 if (do_any_robot_dying_frame(Robot_info, obj))
3302 return;
3303
3304 // Kind of a hack. If a robot is flinching, but it is time for it to fire, unflinch it.
3305 // Else, you can turn a big nasty robot into a wimp by firing flares at it.
3306 // This also allows the player to see the cool flinch effect for mechs without unbalancing the game.
3307 if ((aip->GOAL_STATE == AIS_FLIN) && ready_to_fire_any_weapon(robptr, ailp, 0)) {
3308 aip->GOAL_STATE = AIS_FIRE;
3309 }
3310
3311 #ifndef NDEBUG
3312 if (aip->behavior == ai_behavior::AIB_RUN_FROM && ailp.mode != ai_mode::AIM_RUN_FROM_OBJECT)
3313 Int3(); // This is peculiar. Behavior is run from, but mode is not. Contact Mike.
3314
3315 if (Break_on_object != object_none)
3316 if ((obj) == Break_on_object)
3317 Int3(); // Contact Mike: This is a debug break
3318 #endif
3319
3320 //Assert((aip->behavior >= MIN_BEHAVIOR) && (aip->behavior <= MAX_BEHAVIOR));
3321 switch (aip->behavior)
3322 {
3323 case ai_behavior::AIB_STILL:
3324 case ai_behavior::AIB_NORMAL:
3325 case ai_behavior::AIB_RUN_FROM:
3326 case ai_behavior::AIB_STATION:
3327 #if DXX_BUILD_DESCENT == 1
3328 case ai_behavior::AIB_HIDE:
3329 case ai_behavior::AIB_FOLLOW_PATH:
3330 #elif DXX_BUILD_DESCENT == 2
3331 case ai_behavior::AIB_BEHIND:
3332 case ai_behavior::AIB_SNIPE:
3333 case ai_behavior::AIB_FOLLOW:
3334 #endif
3335 break;
3336 default:
3337 aip->behavior = ai_behavior::AIB_NORMAL;
3338 break;
3339 }
3340
3341 Assert(obj->segnum != segment_none);
3342 assert(underlying_value(get_robot_id(obj)) < LevelSharedRobotInfoState.N_robot_types);
3343
3344 obj_ref = objnum ^ d_tick_count;
3345
3346 if (!ready_to_fire_weapon1(ailp, -F1_0*8))
3347 ailp.next_fire -= FrameTime;
3348
3349 #if DXX_BUILD_DESCENT == 1
3350 Believed_player_pos = Ai_cloak_info[objnum & (MAX_AI_CLOAK_INFO-1)].last_position;
3351 #elif DXX_BUILD_DESCENT == 2
3352 if (robptr.weapon_type2 != weapon_none) {
3353 if (!ready_to_fire_weapon2(robptr, ailp, -F1_0*8))
3354 ailp.next_fire2 -= FrameTime;
3355 } else
3356 ailp.next_fire2 = F1_0*8;
3357 #endif
3358
3359 if (ailp.time_since_processed < F1_0*256)
3360 ailp.time_since_processed += FrameTime;
3361
3362 const auto previous_visibility = ailp.previous_visibility; // Must get this before we toast the master copy!
3363
3364 auto &plrobj = get_local_plrobj();
3365 auto &player_info = plrobj.ctype.player_info;
3366 robot_to_player_visibility_state player_visibility;
3367 auto &vec_to_player = player_visibility.vec_to_player;
3368 #if DXX_BUILD_DESCENT == 1
3369 if (!(player_info.powerup_flags & PLAYER_FLAGS_CLOAKED))
3370 Believed_player_pos = ConsoleObject->pos;
3371 #elif DXX_BUILD_DESCENT == 2
3372 // If only awake because of a camera, make that the believed player position.
3373 if ((aip->SUB_FLAGS & SUB_FLAGS_CAMERA_AWAKE) && Ai_last_missile_camera)
3374 Believed_player_pos = Ai_last_missile_camera->pos;
3375 else {
3376 if (cheats.robotskillrobots) {
3377 vis_vec_pos = obj->pos;
3378 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
3379 if (player_is_visible(player_visibility.visibility))
3380 {
3381 const object *min_obj{nullptr};
3382 fix min_dist = F1_0*200, cur_dist;
3383
3384 for (auto &obj_search : vcobjptr)
3385 {
3386 if (&obj_search != obj && obj_search.type == OBJ_ROBOT)
3387 {
3388 cur_dist = vm_vec_dist_quick(obj->pos, obj_search.pos);
3389 if (cur_dist < F1_0*100)
3390 if (object_to_object_visibility(obj, obj_search, FQ_TRANSWALL))
3391 if (cur_dist < min_dist) {
3392 min_obj = &obj_search;
3393 min_dist = cur_dist;
3394 }
3395 }
3396 }
3397
3398 if (min_obj != nullptr)
3399 {
3400 Believed_player_pos = min_obj->pos;
3401 Believed_player_seg = min_obj->segnum;
3402 vm_vec_normalized_dir_quick(vec_to_player, Believed_player_pos, obj->pos);
3403 } else
3404 goto _exit_cheat;
3405 } else
3406 goto _exit_cheat;
3407 } else {
3408 _exit_cheat:
3409 DXX_MAKE_VAR_UNDEFINED(player_visibility);
3410 player_visibility.initialized = 0;
3411 if (!(player_info.powerup_flags & PLAYER_FLAGS_CLOAKED))
3412 Believed_player_pos = ConsoleObject->pos;
3413 else
3414 Believed_player_pos = Ai_cloak_info[objnum & (MAX_AI_CLOAK_INFO-1)].last_position;
3415 }
3416 }
3417 #endif
3418 auto dist_to_player = vm_vec_dist_quick(Believed_player_pos, obj->pos);
3419
3420 // If this robot can fire, compute visibility from gun position.
3421 // Don't want to compute visibility twice, as it is expensive. (So is call to calc_gun_point).
3422 robot_gun_point gun_point;
3423 #if DXX_BUILD_DESCENT == 1
3424 if (ready_to_fire_any_weapon(robptr, ailp, 0) && (dist_to_player < F1_0*200) && (robptr.n_guns) && !(robptr.attack_type))
3425 #elif DXX_BUILD_DESCENT == 2
3426 if ((player_is_visible(previous_visibility) || !(obj_ref & 3)) && ready_to_fire_any_weapon(robptr, ailp, 0) && (dist_to_player < F1_0*200) && (robptr.n_guns) && !(robptr.attack_type))
3427 #endif
3428 {
3429 // Since we passed ready_to_fire_any_weapon(), either next_fire or next_fire2 <= 0. calc_gun_point from relevant one.
3430 // If both are <= 0, we will deal with the mess in ai_do_actual_firing_stuff
3431 const auto gun_num =
3432 #if DXX_BUILD_DESCENT == 2
3433 (!ready_to_fire_weapon1(ailp, 0))
3434 ? robot_gun_number::_0
3435 :
3436 #endif
3437 aip->CURRENT_GUN;
3438 vis_vec_pos = gun_point.build(robptr, obj, gun_num);
3439 } else {
3440 vis_vec_pos = obj->pos;
3441 }
3442
3443 switch (const auto boss_flag = robptr.boss_flag) {
3444 case boss_robot_id::None:
3445 break;
3446
3447 case boss_robot_id::d1_superboss:
3448 if (aip->GOAL_STATE == AIS_FLIN)
3449 aip->GOAL_STATE = AIS_FIRE;
3450 if (aip->CURRENT_STATE == AIS_FLIN)
3451 aip->CURRENT_STATE = AIS_FIRE;
3452 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
3453
3454 {
3455 auto pv = player_visibility.visibility;
3456 auto dtp = dist_to_player/4;
3457
3458 // If player cloaked, visibility is screwed up and superboss will gate in robots when not supposed to.
3459 if (player_info.powerup_flags & PLAYER_FLAGS_CLOAKED) {
3460 pv = player_visibility_state::no_line_of_sight;
3461 dtp = vm_vec_dist_quick(ConsoleObject->pos, obj->pos)/4;
3462 }
3463
3464 do_super_boss_stuff(Robot_info, vmsegptridx, obj, dtp, pv);
3465 }
3466 break;
3467
3468 default:
3469 #if DXX_BUILD_DESCENT == 1
3470 (void)boss_flag;
3471 Int3(); // Bogus boss flag value.
3472 break;
3473 #endif
3474 case boss_robot_id::d1_1:
3475 {
3476 if (aip->GOAL_STATE == AIS_FLIN)
3477 aip->GOAL_STATE = AIS_FIRE;
3478 if (aip->CURRENT_STATE == AIS_FLIN)
3479 aip->CURRENT_STATE = AIS_FIRE;
3480
3481 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
3482
3483 #if DXX_BUILD_DESCENT == 2
3484 auto pv = player_visibility.visibility;
3485 // If player cloaked, visibility is screwed up and superboss will gate in robots when not supposed to.
3486 if (player_info.powerup_flags & PLAYER_FLAGS_CLOAKED) {
3487 pv = player_visibility_state::no_line_of_sight;
3488 }
3489
3490 if (boss_flag != boss_robot_id::d1_1)
3491 {
3492 do_d2_boss_stuff(vmsegptridx, obj, pv);
3493 break;
3494 }
3495 #endif
3496 do_d1_boss_stuff(Robot_info, vmsegptridx, obj, pv);
3497 }
3498 break;
3499 }
3500 const auto multiplayer{Game_mode & GM_MULTI};
3501 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3502 // Occasionally make non-still robots make a path to the player. Based on agitation and distance from player.
3503 #if DXX_BUILD_DESCENT == 1
3504 if ((aip->behavior != ai_behavior::AIB_RUN_FROM) && (aip->behavior != ai_behavior::AIB_STILL) && !multiplayer)
3505 #elif DXX_BUILD_DESCENT == 2
3506 if ((aip->behavior != ai_behavior::AIB_SNIPE) && (aip->behavior != ai_behavior::AIB_RUN_FROM) && (aip->behavior != ai_behavior::AIB_STILL) && !multiplayer && (robot_is_companion(robptr) != 1) && (robot_is_thief(robptr) != 1))
3507 #endif
3508 if (Overall_agitation > 70) {
3509 if ((dist_to_player < F1_0*200) && (d_rand() < FrameTime/4)) {
3510 if (d_rand() * (Overall_agitation - 40) > F1_0*5) {
3511 create_path_to_believed_player_segment(obj, robptr, 4 + Overall_agitation/8 + underlying_value(Difficulty_level), create_path_safety_flag::safe);
3512 return;
3513 }
3514 }
3515 }
3516
3517 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3518 // If retry count not 0, then add it into consecutive_retries.
3519 // If it is 0, cut down consecutive_retries.
3520 // This is largely a hack to speed up physics and deal with stupid
3521 // AI. This is low level communication between systems of a sort
3522 // that should not be done.
3523 if (ailp.retry_count && !multiplayer)
3524 {
3525 ailp.consecutive_retries += ailp.retry_count;
3526 ailp.retry_count = 0;
3527 if (ailp.consecutive_retries > 3)
3528 {
3529 switch (ailp.mode) {
3530 #if DXX_BUILD_DESCENT == 2
3531 case ai_mode::AIM_GOTO_PLAYER:
3532 move_towards_segment_center(robptr, LevelSharedSegmentState, obj);
3533 create_path_to_guidebot_player_segment(obj, robptr, 100, create_path_safety_flag::safe);
3534 break;
3535 case ai_mode::AIM_GOTO_OBJECT:
3536 BuddyState.Escort_goal_object = ESCORT_GOAL_UNSPECIFIED;
3537 break;
3538 #endif
3539 case ai_mode::AIM_CHASE_OBJECT:
3540 create_path_to_believed_player_segment(obj, robptr, 4 + Overall_agitation/8 + underlying_value(Difficulty_level), create_path_safety_flag::safe);
3541 break;
3542 case ai_mode::AIM_STILL:
3543 #if DXX_BUILD_DESCENT == 1
3544 if (!((aip->behavior == ai_behavior::AIB_STILL) || (aip->behavior == ai_behavior::AIB_STATION))) // Behavior is still, so don't follow path.
3545 #elif DXX_BUILD_DESCENT == 2
3546 if (robptr.attack_type)
3547 move_towards_segment_center(robptr, LevelSharedSegmentState, obj);
3548 else if (!((aip->behavior == ai_behavior::AIB_STILL) || (aip->behavior == ai_behavior::AIB_STATION) || (aip->behavior == ai_behavior::AIB_FOLLOW))) // Behavior is still, so don't follow path.
3549 #endif
3550 attempt_to_resume_path(Robot_info, obj);
3551 break;
3552 case ai_mode::AIM_FOLLOW_PATH:
3553 if (multiplayer)
3554 ailp.mode = ai_mode::AIM_STILL;
3555 else
3556 attempt_to_resume_path(Robot_info, obj);
3557 break;
3558 case ai_mode::AIM_RUN_FROM_OBJECT:
3559 move_towards_segment_center(robptr, LevelSharedSegmentState, obj);
3560 obj->mtype.phys_info.velocity = {};
3561 create_n_segment_path(obj, robptr, 5, segment_none);
3562 ailp.mode = ai_mode::AIM_RUN_FROM_OBJECT;
3563 break;
3564 #if DXX_BUILD_DESCENT == 1
3565 case ai_mode::AIM_HIDE:
3566 move_towards_segment_center(robptr, LevelSharedSegmentState, obj);
3567 obj->mtype.phys_info.velocity = {};
3568 if (Overall_agitation > (50 - underlying_value(Difficulty_level) * 4))
3569 create_path_to_believed_player_segment(obj, robptr, 4 + Overall_agitation/8, create_path_safety_flag::safe);
3570 else {
3571 create_n_segment_path(obj, robptr, 5, segment_none);
3572 }
3573 break;
3574 #elif DXX_BUILD_DESCENT == 2
3575 case ai_mode::AIM_BEHIND:
3576 move_towards_segment_center(robptr, LevelSharedSegmentState, obj);
3577 obj->mtype.phys_info.velocity = {};
3578 break;
3579 case ai_mode::AIM_SNIPE_ATTACK:
3580 case ai_mode::AIM_SNIPE_FIRE:
3581 case ai_mode::AIM_SNIPE_RETREAT:
3582 case ai_mode::AIM_SNIPE_RETREAT_BACKWARDS:
3583 case ai_mode::AIM_SNIPE_WAIT:
3584 case ai_mode::AIM_THIEF_ATTACK:
3585 case ai_mode::AIM_THIEF_RETREAT:
3586 case ai_mode::AIM_THIEF_WAIT:
3587 break;
3588 #endif
3589 case ai_mode::AIM_OPEN_DOOR:
3590 create_n_segment_path_to_door(obj, robptr, 5);
3591 break;
3592 case ai_mode::AIM_FOLLOW_PATH_2:
3593 Int3(); // Should never happen!
3594 break;
3595 case ai_mode::AIM_WANDER:
3596 break;
3597 }
3598 ailp.consecutive_retries = 0;
3599 }
3600 } else
3601 ailp.consecutive_retries /= 2;
3602
3603 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3604 // If in materialization center, exit
3605 if (!multiplayer)
3606 {
3607 const shared_segment &seg = *vcsegptr(obj->segnum);
3608 if (seg.special == segment_special::robotmaker)
3609 {
3610 #if DXX_BUILD_DESCENT == 2
3611 if (Station[seg.station_idx].Enabled)
3612 #endif
3613 {
3614 ai_follow_path(Robot_info, obj, player_visibility_state::visible_not_in_field_of_view, nullptr); // 1 = player is visible, which might be a lie, but it works.
3615 return;
3616 }
3617 }
3618 }
3619
3620 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3621 // Decrease player awareness due to the passage of time.
3622 if (ailp.player_awareness_type != player_awareness_type_t::PA_NONE)
3623 {
3624 if (ailp.player_awareness_time > 0)
3625 {
3626 ailp.player_awareness_time -= FrameTime;
3627 if (ailp.player_awareness_time <= 0)
3628 {
3629 ailp.player_awareness_time = F1_0*2; //new: 11/05/94
3630 ailp.player_awareness_type = static_cast<player_awareness_type_t>(static_cast<unsigned>(ailp.player_awareness_type) - 1); //new: 11/05/94
3631 }
3632 } else {
3633 ailp.player_awareness_time = F1_0*2;
3634 ailp.player_awareness_type = static_cast<player_awareness_type_t>(static_cast<unsigned>(ailp.player_awareness_type) - 1);
3635 //aip->GOAL_STATE = AIS_REST;
3636 }
3637 } else
3638 aip->GOAL_STATE = AIS_REST; //new: 12/13/94
3639
3640
3641 if (Player_dead_state != player_dead_state::no &&
3642 ailp.player_awareness_type == player_awareness_type_t::PA_NONE)
3643 if ((dist_to_player < F1_0*200) && (d_rand() < FrameTime/8)) {
3644 if ((aip->behavior != ai_behavior::AIB_STILL) && (aip->behavior != ai_behavior::AIB_RUN_FROM)) {
3645 if (!ai_multiplayer_awareness(obj, 30))
3646 return;
3647 ai_multi_send_robot_position(obj, -1);
3648
3649 if (!(ailp.mode == ai_mode::AIM_FOLLOW_PATH && aip->cur_path_index < aip->path_length - 1))
3650 #if DXX_BUILD_DESCENT == 2
3651 if ((aip->behavior != ai_behavior::AIB_SNIPE) && (aip->behavior != ai_behavior::AIB_RUN_FROM))
3652 #endif
3653 {
3654 if (dist_to_player < F1_0*30)
3655 create_n_segment_path(obj, robptr, 5, segment_none);
3656 else
3657 create_path_to_believed_player_segment(obj, robptr, 20, create_path_safety_flag::safe);
3658 }
3659 }
3660 }
3661
3662 // Make sure that if this guy got hit or bumped, then he's chasing player.
3663 if (ailp.player_awareness_type == player_awareness_type_t::PA_WEAPON_ROBOT_COLLISION || ailp.player_awareness_type >= player_awareness_type_t::PA_PLAYER_COLLISION)
3664 #if DXX_BUILD_DESCENT == 1
3665 {
3666 if (aip->behavior != ai_behavior::AIB_STILL && aip->behavior != ai_behavior::AIB_FOLLOW_PATH && aip->behavior != ai_behavior::AIB_RUN_FROM && get_robot_id(obj) != robot_id::brain)
3667 ailp.mode = ai_mode::AIM_CHASE_OBJECT;
3668 }
3669 #elif DXX_BUILD_DESCENT == 2
3670 {
3671 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
3672 if (player_visibility.visibility == player_visibility_state::visible_not_in_field_of_view) // Only increase visibility if unobstructed, else claw guys attack through doors.
3673 player_visibility.visibility = player_visibility_state::visible_and_in_field_of_view;
3674 } else if (((obj_ref&3) == 0) && !player_is_visible(previous_visibility) && (dist_to_player < F1_0*100)) {
3675 fix sval, rval;
3676
3677 rval = d_rand();
3678 sval = (dist_to_player * (static_cast<int>(Difficulty_level) + 1)) / 64;
3679
3680 if ((fixmul(rval, sval) < FrameTime) || (player_info.powerup_flags & PLAYER_FLAGS_HEADLIGHT_ON)) {
3681 ailp.player_awareness_type = player_awareness_type_t::PA_PLAYER_COLLISION;
3682 ailp.player_awareness_time = F1_0*3;
3683 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
3684 if (player_visibility.visibility == player_visibility_state::visible_not_in_field_of_view)
3685 player_visibility.visibility = player_visibility_state::visible_and_in_field_of_view;
3686 }
3687 }
3688 #endif
3689
3690 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3691 if ((aip->GOAL_STATE == AIS_FLIN) && (aip->CURRENT_STATE == AIS_FLIN))
3692 aip->GOAL_STATE = AIS_LOCK;
3693
3694 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3695 // Note: Should only do these two function calls for objects which animate
3696 if (dist_to_player < F1_0*100) { // && !multiplayer)
3697 object_animates = do_silly_animation(Robot_info, obj);
3698 if (object_animates)
3699 ai_frame_animation(obj);
3700 } else {
3701 // If Object is supposed to animate, but we don't let it animate due to distance, then
3702 // we must change its state, else it will never update.
3703 aip->CURRENT_STATE = aip->GOAL_STATE;
3704 object_animates = 0; // If we're not doing the animation, then should pretend it doesn't animate.
3705 }
3706
3707 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3708 // Time-slice, don't process all the time, purely an efficiency hack.
3709 // Guys whose behavior is station and are not at their hide segment get processed anyway.
3710 if (skip_ai_for_time_splice(obj, robptr, dist_to_player))
3711 return;
3712
3713 // Reset time since processed, but skew objects so not everything
3714 // processed synchronously, else we get fast frames with the
3715 // occasional very slow frame.
3716 // AI_proc_time = ailp->time_since_processed;
3717 ailp.time_since_processed = - ((objnum & 0x03) * FrameTime ) / 2;
3718
3719 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3720 // Perform special ability
3721 switch (get_robot_id(obj)) {
3722 case robot_id::brain:
3723 // Robots function nicely if behavior is Station. This
3724 // means they won't move until they can see the player, at
3725 // which time they will start wandering about opening doors.
3726 if (ConsoleObject->segnum == obj->segnum) {
3727 if (!ai_multiplayer_awareness(obj, 97))
3728 return;
3729 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
3730 move_away_from_player(Robot_info, obj, vec_to_player, 0);
3731 ai_multi_send_robot_position(obj, -1);
3732 }
3733 else if (ailp.mode != ai_mode::AIM_STILL)
3734 {
3735 auto &Walls = LevelUniqueWallSubsystemState.Walls;
3736 auto &vcwallptr = Walls.vcptr;
3737 if (const auto r = openable_doors_in_segment(vcwallptr, vcsegptr(obj->segnum)); r.has_value())
3738 {
3739 ailp.mode = ai_mode::AIM_OPEN_DOOR;
3740 aip->GOALSIDE = *r;
3741 }
3742 else if (ailp.mode != ai_mode::AIM_FOLLOW_PATH)
3743 {
3744 if (!ai_multiplayer_awareness(obj, 50))
3745 return;
3746 create_n_segment_path_to_door(obj, robptr, 8 + underlying_value(Difficulty_level));
3747 ai_multi_send_robot_position(obj, -1);
3748 }
3749
3750 #if DXX_BUILD_DESCENT == 2
3751 if (ailp.next_action_time < 0)
3752 {
3753 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
3754 if (player_is_visible(player_visibility.visibility))
3755 {
3756 const auto powerup_flags = player_info.powerup_flags;
3757 make_nearby_robot_snipe(vmsegptr, obj, robptr, powerup_flags);
3758 ailp.next_action_time = (NDL - underlying_value(Difficulty_level)) * 2*F1_0;
3759 }
3760 }
3761 #endif
3762 } else {
3763 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
3764 if (player_is_visible(player_visibility.visibility))
3765 {
3766 if (!ai_multiplayer_awareness(obj, 50))
3767 return;
3768 create_n_segment_path_to_door(obj, robptr, 8 + underlying_value(Difficulty_level));
3769 ai_multi_send_robot_position(obj, -1);
3770 }
3771 }
3772 break;
3773 default:
3774 break;
3775 }
3776
3777 #if DXX_BUILD_DESCENT == 2
3778 if (aip->behavior == ai_behavior::AIB_SNIPE) {
3779 if (multiplayer && !robot_is_thief(robptr)) {
3780 aip->behavior = ai_behavior::AIB_NORMAL;
3781 ailp.mode = ai_mode::AIM_CHASE_OBJECT;
3782 return;
3783 }
3784
3785 if (!(obj_ref & 3) || player_is_visible(previous_visibility))
3786 {
3787 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
3788
3789 // If this sniper is in still mode, if he was hit or can see player, switch to snipe mode.
3790 if (ailp.mode == ai_mode::AIM_STILL)
3791 if (player_is_visible(player_visibility.visibility) || ailp.player_awareness_type == player_awareness_type_t::PA_WEAPON_ROBOT_COLLISION)
3792 ailp.mode = ai_mode::AIM_SNIPE_ATTACK;
3793
3794 if (!robot_is_thief(robptr) && ailp.mode != ai_mode::AIM_STILL)
3795 do_snipe_frame(obj, robptr, dist_to_player, player_visibility.visibility, vec_to_player);
3796 } else if (!robot_is_thief(robptr) && !robot_is_companion(robptr))
3797 return;
3798 }
3799
3800 auto &Walls = LevelUniqueWallSubsystemState.Walls;
3801 auto &vcwallptr = Walls.vcptr;
3802 // More special ability stuff, but based on a property of a robot, not its ID.
3803 if (robot_is_companion(robptr)) {
3804 compute_buddy_vis_vec(obj, obj->pos, player_visibility, robptr);
3805 auto &player_controlling_guidebot = get_player_controlling_guidebot(BuddyState, Players);
3806 if (player_controlling_guidebot.objnum != object_none)
3807 {
3808 auto &plrobj_controlling_guidebot = *Objects.vcptr(player_controlling_guidebot.objnum);
3809 do_escort_frame(obj, robptr, plrobj_controlling_guidebot, player_visibility.visibility);
3810 }
3811
3812 if (obj->ctype.ai_info.danger_laser_num != object_none) {
3813 auto &dobjp = *vcobjptr(obj->ctype.ai_info.danger_laser_num);
3814 if ((dobjp.type == OBJ_WEAPON) && (dobjp.signature == obj->ctype.ai_info.danger_laser_signature))
3815 {
3816 fix circle_distance;
3817 circle_distance = robptr.circle_distance[Difficulty_level] + ConsoleObject->size;
3818 ai_move_relative_to_player(Robot_info, obj, ailp, dist_to_player, circle_distance, 1, player_visibility, player_info);
3819 }
3820 }
3821
3822 if (guidebot_should_fire_flare(vcobjptr, vcsegptr, vcwallptr, BuddyState, robptr, *obj))
3823 {
3824 Laser_create_new_easy(Robot_info, obj->orient.fvec, obj->pos, obj, weapon_id_type::FLARE_ID, weapon_sound_flag::audible);
3825 ailp.next_fire = F1_0/2;
3826 if (!BuddyState.Buddy_allowed_to_talk) // If buddy not talking, make him fire flares less often.
3827 ailp.next_fire += d_rand()*4;
3828 }
3829 }
3830
3831 if (robot_is_thief(robptr)) {
3832
3833 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
3834 do_thief_frame(obj, robptr, dist_to_player, player_visibility.visibility, vec_to_player);
3835
3836 if (ready_to_fire_any_weapon(robptr, ailp, 0)) {
3837 if (openable_door_on_near_path(vmsegptr, vcwallptr, *obj, *aip))
3838 {
3839 // @mk, 05/08/95: Firing flare from center of object, this is dumb...
3840 Laser_create_new_easy(Robot_info, obj->orient.fvec, obj->pos, obj, weapon_id_type::FLARE_ID, weapon_sound_flag::audible);
3841 ailp.next_fire = F1_0/2;
3842 if (LevelUniqueObjectState.ThiefState.Stolen_item_index == 0) // If never stolen an item, fire flares less often (bad: Stolen_item_index wraps, but big deal)
3843 ailp.next_fire += d_rand()*4;
3844 }
3845 }
3846 }
3847 #endif
3848
3849 switch (ailp.mode)
3850 {
3851 case ai_mode::AIM_CHASE_OBJECT: { // chasing player, sort of, chase if far, back off if close, circle in between
3852 fix circle_distance;
3853
3854 circle_distance = robptr.circle_distance[Difficulty_level] + ConsoleObject->size;
3855 // Green guy doesn't get his circle distance boosted, else he might never attack.
3856 if (robptr.attack_type != 1)
3857 circle_distance += (objnum&0xf) * F1_0/2;
3858
3859 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
3860
3861 // @mk, 12/27/94, structure here was strange. Would do both clauses of what are now this if/then/else. Used to be if/then, if/then.
3862 if (player_visibility.visibility != player_visibility_state::visible_and_in_field_of_view && previous_visibility == player_visibility_state::visible_and_in_field_of_view)
3863 { // this is redundant: mk, 01/15/95: && (ailp->mode == ai_mode::AIM_CHASE_OBJECT))
3864 if (!ai_multiplayer_awareness(obj, 53)) {
3865 if (maybe_ai_do_actual_firing_stuff(obj))
3866 ai_do_actual_firing_stuff(Robot_info, vmobjptridx, obj, aip, ailp, robptr, dist_to_player, gun_point, player_visibility, object_animates, player_info, aip->CURRENT_GUN);
3867 return;
3868 }
3869 create_path_to_believed_player_segment(obj, robptr, 8, create_path_safety_flag::safe);
3870 ai_multi_send_robot_position(obj, -1);
3871 } else if (!player_is_visible(player_visibility.visibility) && dist_to_player > F1_0 * 80 && !multiplayer)
3872 {
3873 // If pretty far from the player, player cannot be seen
3874 // (obstructed) and in chase mode, switch to follow path mode.
3875 // This has one desirable benefit of avoiding physics retries.
3876 if (aip->behavior == ai_behavior::AIB_STATION) {
3877 ailp.goal_segment = aip->hide_segment;
3878 create_path_to_station(obj, robptr, 15);
3879 } // -- this looks like a dumb thing to do...robots following paths far away from you! else create_n_segment_path(obj, 5, -1);
3880 #if DXX_BUILD_DESCENT == 1
3881 else
3882 create_n_segment_path(obj, robptr, 5, segment_none);
3883 #endif
3884 break;
3885 }
3886
3887 if ((aip->CURRENT_STATE == AIS_REST) && (aip->GOAL_STATE == AIS_REST)) {
3888 const auto pv = player_visibility.visibility;
3889 if (player_is_visible(pv))
3890 {
3891 const auto upv = static_cast<unsigned>(pv);
3892 if (d_rand() < FrameTime * upv)
3893 if (dist_to_player/256 < static_cast<fix>(d_rand() * upv))
3894 {
3895 aip->GOAL_STATE = AIS_SRCH;
3896 aip->CURRENT_STATE = AIS_SRCH;
3897 }
3898 }
3899 }
3900
3901 if (GameTime64 - ailp.time_player_seen > CHASE_TIME_LENGTH)
3902 {
3903
3904 if (multiplayer)
3905 {
3906 if (!player_is_visible(player_visibility.visibility) && dist_to_player > F1_0 * 70)
3907 {
3908 ailp.mode = ai_mode::AIM_STILL;
3909 return;
3910 }
3911 }
3912
3913 if (!ai_multiplayer_awareness(obj, 64)) {
3914 if (maybe_ai_do_actual_firing_stuff(obj))
3915 ai_do_actual_firing_stuff(Robot_info, vmobjptridx, obj, aip, ailp, robptr, dist_to_player, gun_point, player_visibility, object_animates, player_info, aip->CURRENT_GUN);
3916 return;
3917 }
3918 #if DXX_BUILD_DESCENT == 1
3919 create_path_to_believed_player_segment(obj, robptr, 10, create_path_safety_flag::safe);
3920 ai_multi_send_robot_position(obj, -1);
3921 #endif
3922 } else if ((aip->CURRENT_STATE != AIS_REST) && (aip->GOAL_STATE != AIS_REST)) {
3923 if (!ai_multiplayer_awareness(obj, 70)) {
3924 if (maybe_ai_do_actual_firing_stuff(obj))
3925 ai_do_actual_firing_stuff(Robot_info, vmobjptridx, obj, aip, ailp, robptr, dist_to_player, gun_point, player_visibility, object_animates, player_info, aip->CURRENT_GUN);
3926 return;
3927 }
3928 ai_move_relative_to_player(Robot_info, obj, ailp, dist_to_player, circle_distance, 0, player_visibility, player_info);
3929
3930 if ((obj_ref & 1) && ((aip->GOAL_STATE == AIS_SRCH) || (aip->GOAL_STATE == AIS_LOCK))) {
3931 if (player_is_visible(player_visibility.visibility))
3932 ai_turn_towards_vector(vec_to_player, obj, robptr.turn_time[Difficulty_level]);
3933 #if DXX_BUILD_DESCENT == 1
3934 else
3935 ai_turn_randomly(vec_to_player, obj, robptr.turn_time[Difficulty_level], previous_visibility);
3936 #endif
3937 }
3938
3939 ai_multi_send_robot_position(obj, ai_evaded ? (ai_evaded = 0, 1) : -1);
3940
3941 do_firing_stuff(obj, player_info.powerup_flags, player_visibility);
3942 }
3943 break;
3944 }
3945
3946 case ai_mode::AIM_RUN_FROM_OBJECT:
3947 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
3948
3949 {
3950 const auto pv = player_visibility.visibility;
3951 const auto player_is_in_line_of_sight = player_is_visible(pv);
3952 if (player_is_in_line_of_sight)
3953 {
3954 if (ailp.player_awareness_type == player_awareness_type_t::PA_NONE)
3955 ailp.player_awareness_type = player_awareness_type_t::PA_WEAPON_ROBOT_COLLISION;
3956 }
3957
3958 // If in multiplayer, only do if player visible. If not multiplayer, do always.
3959 if (!multiplayer || player_is_in_line_of_sight)
3960 if (ai_multiplayer_awareness(obj, 75)) {
3961 ai_follow_path(Robot_info, obj, player_visibility.visibility, &vec_to_player);
3962 ai_multi_send_robot_position(obj, -1);
3963 }
3964
3965 if (aip->GOAL_STATE != AIS_FLIN)
3966 aip->GOAL_STATE = AIS_LOCK;
3967 else if (aip->CURRENT_STATE == AIS_FLIN)
3968 aip->GOAL_STATE = AIS_LOCK;
3969
3970 // Bad to let run_from robot fire at player because it
3971 // will cause a war in which it turns towards the player
3972 // to fire and then towards its goal to move.
3973 // do_firing_stuff(obj, player_visibility, &vec_to_player);
3974 // Instead, do this:
3975 // (Note, only drop if player is visible. This prevents
3976 // the bombs from being a giveaway, and also ensures that
3977 // the robot is moving while it is dropping. Also means
3978 // fewer will be dropped.)
3979 if (ready_to_fire_weapon1(ailp, 0) && player_is_in_line_of_sight)
3980 {
3981 if (!ai_multiplayer_awareness(obj, 75))
3982 return;
3983
3984 const auto fire_vec{vm_vec_build_negated(obj->orient.fvec)};
3985 const auto fire_pos = vm_vec_build_add(obj->pos, fire_vec);
3986
3987 #if DXX_BUILD_DESCENT == 1
3988 ailp.next_fire = F1_0*5; // Drop a proximity bomb every 5 seconds.
3989 const auto weapon_id =
3990 #elif DXX_BUILD_DESCENT == 2
3991 ailp.next_fire = (F1_0 / 2) * (NDL + 5 - underlying_value(Difficulty_level)); // Drop a proximity bomb every 5 seconds.
3992 const auto weapon_id = (aip->SUB_FLAGS & SUB_FLAGS_SPROX)
3993 ? weapon_id_type::ROBOT_SUPERPROX_ID
3994 :
3995 #endif
3996 weapon_id_type::PROXIMITY_ID;
3997 Laser_create_new_easy(Robot_info, fire_vec, fire_pos, obj, weapon_id, weapon_sound_flag::audible);
3998
3999 if (multiplayer)
4000 {
4001 ai_multi_send_robot_position(obj, -1);
4002 const auto gun_num =
4003 #if DXX_BUILD_DESCENT == 2
4004 (aip->SUB_FLAGS & SUB_FLAGS_SPROX)
4005 ? robot_gun_number::smart_mine
4006 :
4007 #endif
4008 robot_gun_number::proximity;
4009 multi_send_robot_fire(obj, gun_num, fire_vec);
4010 }
4011 }
4012 }
4013 break;
4014
4015 #if DXX_BUILD_DESCENT == 2
4016 case ai_mode::AIM_GOTO_PLAYER:
4017 case ai_mode::AIM_GOTO_OBJECT:
4018 ai_follow_path(Robot_info, obj, player_visibility_state::visible_and_in_field_of_view, &vec_to_player); // Follows path as if player can see robot.
4019 ai_multi_send_robot_position(obj, -1);
4020 break;
4021 #endif
4022
4023 case ai_mode::AIM_FOLLOW_PATH: {
4024 int anger_level{65};
4025
4026 if (aip->behavior == ai_behavior::AIB_STATION)
4027 {
4028 const std::size_t idx = aip->hide_index + aip->path_length - 1;
4029 if (idx < Point_segs.size() && Point_segs[idx].segnum == aip->hide_segment)
4030 {
4031 anger_level = 64;
4032 }
4033 }
4034
4035 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
4036
4037 if (!ai_multiplayer_awareness(obj, anger_level)) {
4038 if (maybe_ai_do_actual_firing_stuff(obj)) {
4039 ai_do_actual_firing_stuff(Robot_info, vmobjptridx, obj, aip, ailp, robptr, dist_to_player, gun_point, player_visibility, object_animates, player_info, aip->CURRENT_GUN);
4040 }
4041 return;
4042 }
4043
4044 ai_follow_path(Robot_info, obj, player_visibility.visibility, &vec_to_player);
4045
4046 if (aip->GOAL_STATE != AIS_FLIN)
4047 aip->GOAL_STATE = AIS_LOCK;
4048 else if (aip->CURRENT_STATE == AIS_FLIN)
4049 aip->GOAL_STATE = AIS_LOCK;
4050
4051 #if DXX_BUILD_DESCENT == 1
4052 if ((aip->behavior != ai_behavior::AIB_FOLLOW_PATH) && (aip->behavior != ai_behavior::AIB_RUN_FROM))
4053 do_firing_stuff(obj, player_info.powerup_flags, player_visibility);
4054
4055 if (player_visibility.visibility == player_visibility_state::visible_and_in_field_of_view && aip->behavior != ai_behavior::AIB_FOLLOW_PATH && aip->behavior != ai_behavior::AIB_RUN_FROM && get_robot_id(obj) != robot_id::brain)
4056 {
4057 if (robptr.attack_type == 0)
4058 ailp.mode = ai_mode::AIM_CHASE_OBJECT;
4059 }
4060 else if (!player_is_visible(player_visibility.visibility)
4061 && (aip->behavior == ai_behavior::AIB_NORMAL)
4062 && (ailp.mode == ai_mode::AIM_FOLLOW_PATH)
4063 && (aip->behavior != ai_behavior::AIB_RUN_FROM))
4064 {
4065 ailp.mode = ai_mode::AIM_STILL;
4066 aip->hide_index = -1;
4067 aip->path_length = 0;
4068 }
4069 #elif DXX_BUILD_DESCENT == 2
4070 if (aip->behavior != ai_behavior::AIB_RUN_FROM)
4071 do_firing_stuff(obj, player_info.powerup_flags, player_visibility);
4072
4073 if (player_visibility.visibility == player_visibility_state::visible_and_in_field_of_view &&
4074 aip->behavior != ai_behavior::AIB_SNIPE &&
4075 aip->behavior != ai_behavior::AIB_FOLLOW &&
4076 aip->behavior != ai_behavior::AIB_RUN_FROM &&
4077 get_robot_id(obj) != robot_id::brain &&
4078 robot_is_companion(robptr) != 1 &&
4079 robot_is_thief(robptr) != 1)
4080 {
4081 if (robptr.attack_type == 0)
4082 ailp.mode = ai_mode::AIM_CHASE_OBJECT;
4083 // This should not just be distance based, but also time-since-player-seen based.
4084 }
4085 else if ((dist_to_player > F1_0 * (20 * (2 * underlying_value(Difficulty_level) + robptr.pursuit)))
4086 && (GameTime64 - ailp.time_player_seen > (F1_0 / 2 * (underlying_value(Difficulty_level) + robptr.pursuit)))
4087 && !player_is_visible(player_visibility.visibility)
4088 && (aip->behavior == ai_behavior::AIB_NORMAL)
4089 && (ailp.mode == ai_mode::AIM_FOLLOW_PATH))
4090 {
4091 ailp.mode = ai_mode::AIM_STILL;
4092 aip->hide_index = -1;
4093 aip->path_length = 0;
4094 }
4095 #endif
4096
4097 ai_multi_send_robot_position(obj, -1);
4098
4099 break;
4100 }
4101
4102 #if DXX_BUILD_DESCENT == 1
4103 case ai_mode::AIM_HIDE:
4104 #elif DXX_BUILD_DESCENT == 2
4105 case ai_mode::AIM_BEHIND:
4106 #endif
4107 if (!ai_multiplayer_awareness(obj, 71)) {
4108 if (maybe_ai_do_actual_firing_stuff(obj)) {
4109 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
4110 ai_do_actual_firing_stuff(Robot_info, vmobjptridx, obj, aip, ailp, robptr, dist_to_player, gun_point, player_visibility, object_animates, player_info, aip->CURRENT_GUN);
4111 }
4112 return;
4113 }
4114
4115 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
4116
4117 #if DXX_BUILD_DESCENT == 1
4118 ai_follow_path(Robot_info, obj, player_visibility.visibility, nullptr);
4119 #elif DXX_BUILD_DESCENT == 2
4120 if (player_visibility.visibility == player_visibility_state::visible_and_in_field_of_view)
4121 {
4122 // Get behind the player.
4123 // Method:
4124 // If vec_to_player dot player_rear_vector > 0, behind is goal.
4125 // Else choose goal with larger dot from left, right.
4126 vms_vector goal_vector;
4127 fix dot;
4128
4129 dot = vm_vec_build_dot(ConsoleObject->orient.fvec, vec_to_player);
4130 if (dot > 0) { // Remember, we're interested in the rear vector dot being < 0.
4131 goal_vector = vm_vec_build_negated(ConsoleObject->orient.fvec);
4132 } else {
4133 auto &orient = ConsoleObject->orient;
4134 constexpr unsigned choice_count = 15;
4135 const unsigned selector = (ConsoleObject->id ^ obj.get_unchecked_index() ^ ConsoleObject->segnum ^ obj->segnum) % (choice_count + 1);
4136 if (selector == 0)
4137 goal_vector = orient.rvec;
4138 else if (selector == choice_count)
4139 goal_vector = orient.uvec;
4140 else
4141 {
4142 vm_vec_scale_add2(goal_vector, orient.rvec, (choice_count - selector) * F1_0);
4143 goal_vector = vm_vec_copy_scale(orient.uvec, selector * F1_0);
4144 vm_vec_normalize_quick(goal_vector);
4145 }
4146 if (vm_vec_build_dot(goal_vector, vec_to_player) > 0)
4147 vm_vec_negate(goal_vector);
4148 }
4149
4150 vm_vec_scale(goal_vector, 2*(ConsoleObject->size + obj->size + (((objnum*4 + d_tick_count) & 63) << 12)));
4151 auto goal_point = vm_vec_build_add(ConsoleObject->pos, goal_vector);
4152 vm_vec_scale_add2(goal_point, make_random_vector(), F1_0*8);
4153 const auto vec_to_goal = vm_vec_normalized_quick(vm_vec_build_sub(goal_point, obj->pos));
4154 move_towards_vector(robptr, obj, vec_to_goal, 0);
4155 ai_turn_towards_vector(vec_to_player, obj, robptr.turn_time[Difficulty_level]);
4156 ai_do_actual_firing_stuff(Robot_info, vmobjptridx, obj, aip, ailp, robptr, dist_to_player, gun_point, player_visibility, object_animates, player_info, aip->CURRENT_GUN);
4157 }
4158 #endif
4159
4160 if (aip->GOAL_STATE != AIS_FLIN)
4161 aip->GOAL_STATE = AIS_LOCK;
4162 else if (aip->CURRENT_STATE == AIS_FLIN)
4163 aip->GOAL_STATE = AIS_LOCK;
4164
4165 ai_multi_send_robot_position(obj, -1);
4166 break;
4167
4168 case ai_mode::AIM_STILL:
4169 if ((dist_to_player < F1_0 * 120 + static_cast<int>(Difficulty_level) * F1_0 * 20) || (static_cast<unsigned>(ailp.player_awareness_type) >= static_cast<unsigned>(player_awareness_type_t::PA_WEAPON_ROBOT_COLLISION) - 1))
4170 {
4171 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
4172
4173 // turn towards vector if visible this time or last time, or rand
4174 // new!
4175 #if DXX_BUILD_DESCENT == 1
4176 if (player_is_visible(player_visibility.visibility) || player_is_visible(previous_visibility) || ((d_rand() > 0x4000) && !multiplayer))
4177 #elif DXX_BUILD_DESCENT == 2
4178 if (player_visibility.visibility == player_visibility_state::visible_and_in_field_of_view || previous_visibility == player_visibility_state::visible_and_in_field_of_view) // -- MK, 06/09/95: || ((d_rand() > 0x4000) && !multiplayer))
4179 #endif
4180 {
4181 if (!ai_multiplayer_awareness(obj, 71)) {
4182 if (maybe_ai_do_actual_firing_stuff(obj))
4183 ai_do_actual_firing_stuff(Robot_info, vmobjptridx, obj, aip, ailp, robptr, dist_to_player, gun_point, player_visibility, object_animates, player_info, aip->CURRENT_GUN);
4184 return;
4185 }
4186 ai_turn_towards_vector(vec_to_player, obj, robptr.turn_time[Difficulty_level]);
4187 ai_multi_send_robot_position(obj, -1);
4188 }
4189
4190 do_firing_stuff(obj, player_info.powerup_flags, player_visibility);
4191 #if DXX_BUILD_DESCENT == 1
4192 if (player_is_visible(player_visibility.visibility)) // Change, MK, 01/03/94 for Multiplayer reasons. If robots can't see you (even with eyes on back of head), then don't do evasion.
4193 #elif DXX_BUILD_DESCENT == 2
4194 if (player_visibility.visibility == player_visibility_state::visible_and_in_field_of_view) // Changed @mk, 09/21/95: Require that they be looking to evade. Change, MK, 01/03/95 for Multiplayer reasons. If robots can't see you (even with eyes on back of head), then don't do evasion.
4195 #endif
4196 {
4197 if (robptr.attack_type == 1) {
4198 aip->behavior = ai_behavior::AIB_NORMAL;
4199 if (!ai_multiplayer_awareness(obj, 80)) {
4200 if (maybe_ai_do_actual_firing_stuff(obj))
4201 ai_do_actual_firing_stuff(Robot_info, vmobjptridx, obj, aip, ailp, robptr, dist_to_player, gun_point, player_visibility, object_animates, player_info, aip->CURRENT_GUN);
4202 return;
4203 }
4204 ai_move_relative_to_player(Robot_info, obj, ailp, dist_to_player, 0, 0, player_visibility, player_info);
4205 ai_multi_send_robot_position(obj, ai_evaded ? (ai_evaded = 0, 1) : -1);
4206 } else {
4207 // Robots in hover mode are allowed to evade at half normal speed.
4208 if (!ai_multiplayer_awareness(obj, 81)) {
4209 if (maybe_ai_do_actual_firing_stuff(obj))
4210 ai_do_actual_firing_stuff(Robot_info, vmobjptridx, obj, aip, ailp, robptr, dist_to_player, gun_point, player_visibility, object_animates, player_info, aip->CURRENT_GUN);
4211 return;
4212 }
4213 ai_move_relative_to_player(Robot_info, obj, ailp, dist_to_player, 0, 1, player_visibility, player_info);
4214 if (ai_evaded) {
4215 ai_multi_send_robot_position(obj, -1);
4216 ai_evaded = 0;
4217 }
4218 else
4219 ai_multi_send_robot_position(obj, -1);
4220 }
4221 } else if ((obj->segnum != aip->hide_segment) && (dist_to_player > F1_0*80) && (!multiplayer)) {
4222 // If pretty far from the player, player cannot be
4223 // seen (obstructed) and in chase mode, switch to
4224 // follow path mode.
4225 // This has one desirable benefit of avoiding physics retries.
4226 if (aip->behavior == ai_behavior::AIB_STATION) {
4227 ailp.goal_segment = aip->hide_segment;
4228 create_path_to_station(obj, robptr, 15);
4229 }
4230 break;
4231 }
4232 }
4233
4234 break;
4235 case ai_mode::AIM_OPEN_DOOR: { // trying to open a door.
4236 assert(get_robot_id(obj) == robot_id::brain); // Make sure this guy is allowed to be in this mode.
4237
4238 if (!ai_multiplayer_awareness(obj, 62))
4239 return;
4240 auto &vcvertptr = Vertices.vcptr;
4241 const auto center_point{compute_center_point_on_side(vcvertptr, vcsegptr(obj->segnum), aip->GOALSIDE)};
4242 const auto goal_vector = vm_vec_normalized_quick(vm_vec_build_sub(center_point, obj->pos));
4243 ai_turn_towards_vector(goal_vector, obj, robptr.turn_time[Difficulty_level]);
4244 move_towards_vector(robptr, obj, goal_vector, 0);
4245 ai_multi_send_robot_position(obj, -1);
4246
4247 break;
4248 }
4249
4250 #if DXX_BUILD_DESCENT == 2
4251 case ai_mode::AIM_SNIPE_WAIT:
4252 break;
4253 case ai_mode::AIM_SNIPE_RETREAT:
4254 // -- if (ai_multiplayer_awareness(obj, 53))
4255 // -- if (ailp->next_fire < -F1_0)
4256 // -- ai_do_actual_firing_stuff(obj, aip, ailp, robptr, &vec_to_player, dist_to_player, &gun_point, player_visibility, object_animates, aip->CURRENT_GUN);
4257 break;
4258 case ai_mode::AIM_SNIPE_RETREAT_BACKWARDS:
4259 case ai_mode::AIM_SNIPE_ATTACK:
4260 case ai_mode::AIM_SNIPE_FIRE:
4261 if (ai_multiplayer_awareness(obj, 53)) {
4262 ai_do_actual_firing_stuff(Robot_info, vmobjptridx, obj, aip, ailp, robptr, dist_to_player, gun_point, player_visibility, object_animates, player_info, aip->CURRENT_GUN);
4263 if (robot_is_thief(robptr))
4264 ai_move_relative_to_player(Robot_info, obj, ailp, dist_to_player, 0, 0, player_visibility, player_info);
4265 break;
4266 }
4267 break;
4268
4269 case ai_mode::AIM_THIEF_WAIT:
4270 case ai_mode::AIM_THIEF_ATTACK:
4271 case ai_mode::AIM_THIEF_RETREAT:
4272 case ai_mode::AIM_WANDER: // Used for Buddy Bot
4273 break;
4274 #endif
4275
4276 default:
4277 ailp.mode = ai_mode::AIM_CHASE_OBJECT;
4278 break;
4279 } // end: switch (ailp->mode)
4280
4281 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4282 // If the robot can see you, increase his awareness of you.
4283 // This prevents the problem of a robot looking right at you but doing nothing.
4284 // Assert(player_visibility != -1); // Means it didn't get initialized!
4285 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
4286 if (player_visibility.visibility == player_visibility_state::visible_and_in_field_of_view)
4287 {
4288 #if DXX_BUILD_DESCENT == 1
4289 if (ailp.player_awareness_type == player_awareness_type_t::PA_NONE)
4290 ailp.player_awareness_type = player_awareness_type_t::PA_PLAYER_COLLISION;
4291 #elif DXX_BUILD_DESCENT == 2
4292 if (aip->behavior != ai_behavior::AIB_FOLLOW && !robot_is_thief(robptr))
4293 {
4294 if (ailp.player_awareness_type == player_awareness_type_t::PA_NONE && (aip->SUB_FLAGS & SUB_FLAGS_CAMERA_AWAKE))
4295 aip->SUB_FLAGS &= ~SUB_FLAGS_CAMERA_AWAKE;
4296 else if (ailp.player_awareness_type == player_awareness_type_t::PA_NONE)
4297 ailp.player_awareness_type = player_awareness_type_t::PA_PLAYER_COLLISION;
4298 }
4299 #endif
4300 }
4301
4302 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4303 if (!object_animates) {
4304 aip->CURRENT_STATE = aip->GOAL_STATE;
4305 }
4306
4307 assert(static_cast<unsigned>(ailp.player_awareness_type) <= AIE_MAX);
4308 Assert(aip->CURRENT_STATE < AIS_MAX);
4309 Assert(aip->GOAL_STATE < AIS_MAX);
4310
4311 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4312 if (ailp.player_awareness_type != player_awareness_type_t::PA_NONE) {
4313 const auto i = static_cast<unsigned>(ailp.player_awareness_type) - 1;
4314 if (ailp.player_awareness_type == player_awareness_type_t::PA_WEAPON_ROBOT_COLLISION)
4315 {
4316 // Decrease awareness, else this robot will flinch every frame.
4317 ailp.player_awareness_type = player_awareness_type_t::PA_PLAYER_COLLISION;
4318 ailp.player_awareness_time = F1_0*3;
4319 }
4320
4321 auto new_goal_state = (i < Ai_transition_table.size())
4322 ? Ai_transition_table[i][aip->CURRENT_STATE][aip->GOAL_STATE]
4323 : AIS_REST;
4324 if (new_goal_state == AIS_ERR_)
4325 new_goal_state = AIS_REST;
4326
4327 if (aip->CURRENT_STATE == AIS_NONE)
4328 aip->CURRENT_STATE = AIS_REST;
4329
4330 aip->GOAL_STATE = new_goal_state;
4331
4332 }
4333
4334 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4335 // If new state = fire, then set all gun states to fire.
4336 if (aip->GOAL_STATE == AIS_FIRE)
4337 {
4338 std::fill_n(ailp.goal_state.begin(), robptr.n_guns, AIS_FIRE);
4339 }
4340
4341 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4342 // Hack by mk on 01/04/94, if a guy hasn't animated to the firing state, but his next_fire says ok to fire, bash him there
4343 if (ready_to_fire_any_weapon(robptr, ailp, 0) && (aip->GOAL_STATE == AIS_FIRE))
4344 aip->CURRENT_STATE = AIS_FIRE;
4345
4346 if (aip->GOAL_STATE != AIS_FLIN && get_robot_id(obj) != robot_id::brain)
4347 {
4348 switch (aip->CURRENT_STATE) {
4349 case AIS_NONE:
4350 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
4351
4352 {
4353 const fix dot = vm_vec_build_dot(obj->orient.fvec, vec_to_player);
4354 if (dot >= F1_0/2)
4355 if (aip->GOAL_STATE == AIS_REST)
4356 aip->GOAL_STATE = AIS_SRCH;
4357 }
4358 break;
4359 case AIS_REST:
4360 if (aip->GOAL_STATE == AIS_REST) {
4361 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
4362 if (ready_to_fire_any_weapon(robptr, ailp, 0) && player_is_visible(player_visibility.visibility))
4363 {
4364 aip->GOAL_STATE = AIS_FIRE;
4365 }
4366 }
4367 break;
4368 case AIS_SRCH:
4369 if (!ai_multiplayer_awareness(obj, 60))
4370 return;
4371
4372 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
4373
4374 #if DXX_BUILD_DESCENT == 1
4375 if (player_is_visible(player_visibility.visibility))
4376 {
4377 ai_turn_towards_vector(vec_to_player, obj, robptr.turn_time[Difficulty_level]);
4378 ai_multi_send_robot_position(obj, -1);
4379 } else if (!multiplayer)
4380 ai_turn_randomly(vec_to_player, obj, robptr.turn_time[Difficulty_level], previous_visibility);
4381 #elif DXX_BUILD_DESCENT == 2
4382 if (player_visibility.visibility == player_visibility_state::visible_and_in_field_of_view)
4383 {
4384 ai_turn_towards_vector(vec_to_player, obj, robptr.turn_time[Difficulty_level]);
4385 ai_multi_send_robot_position(obj, -1);
4386 }
4387 #endif
4388 break;
4389 case AIS_LOCK:
4390 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
4391
4392 if (!multiplayer || player_is_visible(player_visibility.visibility))
4393 {
4394 if (!ai_multiplayer_awareness(obj, 68))
4395 return;
4396
4397 #if DXX_BUILD_DESCENT == 1
4398 if (player_is_visible(player_visibility.visibility))
4399 {
4400 ai_turn_towards_vector(vec_to_player, obj, robptr.turn_time[Difficulty_level]);
4401 ai_multi_send_robot_position(obj, -1);
4402 }
4403 else if (!multiplayer)
4404 ai_turn_randomly(vec_to_player, obj, robptr.turn_time[Difficulty_level], previous_visibility);
4405 #elif DXX_BUILD_DESCENT == 2
4406 if (player_visibility.visibility == player_visibility_state::visible_and_in_field_of_view)
4407 { // @mk, 09/21/95, require that they be looking towards you to turn towards you.
4408 ai_turn_towards_vector(vec_to_player, obj, robptr.turn_time[Difficulty_level]);
4409 ai_multi_send_robot_position(obj, -1);
4410 }
4411 #endif
4412 }
4413 break;
4414 case AIS_FIRE:
4415 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
4416
4417 #if DXX_BUILD_DESCENT == 1
4418 if (player_is_visible(player_visibility.visibility))
4419 {
4420 if (!ai_multiplayer_awareness(obj, (ROBOT_FIRE_AGITATION-1)))
4421 {
4422 if (multiplayer) {
4423 ai_do_actual_firing_stuff(Robot_info, vmobjptridx, obj, aip, ailp, robptr, dist_to_player, gun_point, player_visibility, object_animates, player_info, robot_gun_number::_0);
4424 return;
4425 }
4426 }
4427 ai_turn_towards_vector(vec_to_player, obj, robptr.turn_time[Difficulty_level]);
4428 ai_multi_send_robot_position(obj, -1);
4429 } else if (!multiplayer) {
4430 ai_turn_randomly(vec_to_player, obj, robptr.turn_time[Difficulty_level], previous_visibility);
4431 }
4432 #elif DXX_BUILD_DESCENT == 2
4433 if (player_visibility.visibility == player_visibility_state::visible_and_in_field_of_view)
4434 {
4435 if (!ai_multiplayer_awareness(obj, (ROBOT_FIRE_AGITATION-1))) {
4436 if (multiplayer) {
4437 ai_do_actual_firing_stuff(Robot_info, vmobjptridx, obj, aip, ailp, robptr, dist_to_player, gun_point, player_visibility, object_animates, player_info, aip->CURRENT_GUN);
4438 return;
4439 }
4440 }
4441 ai_turn_towards_vector(vec_to_player, obj, robptr.turn_time[Difficulty_level]);
4442 ai_multi_send_robot_position(obj, -1);
4443 }
4444 #endif
4445
4446 // Fire at player, if appropriate.
4447 ai_do_actual_firing_stuff(Robot_info, vmobjptridx, obj, aip, ailp, robptr, dist_to_player, gun_point, player_visibility, object_animates, player_info, aip->CURRENT_GUN);
4448
4449 break;
4450 case AIS_RECO:
4451 if (!(obj_ref & 3)) {
4452 compute_vis_and_vec(Robot_info, obj, player_info, vis_vec_pos, ailp, player_visibility, robptr);
4453 #if DXX_BUILD_DESCENT == 1
4454 if (player_is_visible(player_visibility.visibility))
4455 {
4456 if (!ai_multiplayer_awareness(obj, 69))
4457 return;
4458 ai_turn_towards_vector(vec_to_player, obj, robptr.turn_time[Difficulty_level]);
4459 ai_multi_send_robot_position(obj, -1);
4460 }
4461 else if (!multiplayer) {
4462 ai_turn_randomly(vec_to_player, obj, robptr.turn_time[Difficulty_level], previous_visibility);
4463 }
4464 #elif DXX_BUILD_DESCENT == 2
4465 if (player_visibility.visibility == player_visibility_state::visible_and_in_field_of_view)
4466 {
4467 if (!ai_multiplayer_awareness(obj, 69))
4468 return;
4469 ai_turn_towards_vector(vec_to_player, obj, robptr.turn_time[Difficulty_level]);
4470 ai_multi_send_robot_position(obj, -1);
4471 }
4472 #endif
4473 }
4474 break;
4475 case AIS_FLIN:
4476 break;
4477 default:
4478 aip->GOAL_STATE = AIS_REST;
4479 aip->CURRENT_STATE = AIS_REST;
4480 break;
4481 }
4482 } // end of: if (aip->GOAL_STATE != AIS_FLIN)
4483
4484 // Switch to next gun for next fire.
4485 if (!player_is_visible(player_visibility.visibility))
4486 {
4487 aip->CURRENT_GUN = robot_advance_current_gun_prefer_second(robptr, aip->CURRENT_GUN);
4488 }
4489
4490 }
4491
4492 // ----------------------------------------------------------------------------
4493 void ai_do_cloak_stuff(void)
4494 {
4495 range_for (auto &i, Ai_cloak_info) {
4496 i.last_time = {GameTime64};
4497 #if DXX_BUILD_DESCENT == 2
4498 i.last_segment = ConsoleObject->segnum;
4499 #endif
4500 i.last_position = ConsoleObject->pos;
4501 }
4502
4503 // Make work for control centers.
4504 Believed_player_pos = Ai_cloak_info[0].last_position;
4505 #if DXX_BUILD_DESCENT == 2
4506 Believed_player_seg = Ai_cloak_info[0].last_segment;
4507 #endif
4508 }
4509
4510 // --------------------------------------------------------------------------------------------------------------------
4511 // Call this each time the player starts a new ship.
4512 void init_ai_for_ship()
4513 {
4514 ai_do_cloak_stuff();
4515 }
4516
4517 namespace {
4518
4519 // ----------------------------------------------------------------------------
4520 // Returns false if awareness is considered too puny to add, else returns true.
4521 static int add_awareness_event(const object_base &objp, player_awareness_type_t type, d_level_unique_robot_awareness_state &awareness)
4522 {
4523 // If player cloaked and hit a robot, then increase awareness
4524 if (type == player_awareness_type_t::PA_WEAPON_ROBOT_COLLISION ||
4525 type == player_awareness_type_t::PA_WEAPON_WALL_COLLISION ||
4526 type == player_awareness_type_t::PA_PLAYER_COLLISION)
4527 ai_do_cloak_stuff();
4528
4529 if (awareness.Num_awareness_events < awareness.Awareness_events.size())
4530 {
4531 if (type == player_awareness_type_t::PA_WEAPON_WALL_COLLISION ||
4532 type == player_awareness_type_t::PA_WEAPON_ROBOT_COLLISION)
4533 if (objp.type == OBJ_WEAPON && get_weapon_id(objp) == weapon_id_type::VULCAN_ID)
4534 if (d_rand() > 3276)
4535 return 0; // For vulcan cannon, only about 1/10 actually cause awareness
4536
4537 auto &e = awareness.Awareness_events[awareness.Num_awareness_events++];
4538 e.segnum = objp.segnum;
4539 e.pos = objp.pos;
4540 e.type = type;
4541 } else {
4542 //Int3(); // Hey -- Overflowed Awareness_events, make more or something
4543 // This just gets ignored, so you can just
4544 // continue.
4545 }
4546 return 1;
4547
4548 }
4549
4550 }
4551
4552 // ----------------------------------------------------------------------------------
4553 // Robots will become aware of the player based on something that occurred.
4554 // The object (probably player or weapon) which created the awareness is objp.
4555 void create_awareness_event(object &objp, player_awareness_type_t type, d_level_unique_robot_awareness_state &LevelUniqueRobotAwarenessState)
4556 {
4557 // If not in multiplayer, or in multiplayer with robots, do this, else unnecessary!
4558 if (!(Game_mode & GM_MULTI) || (Game_mode & GM_MULTI_ROBOTS))
4559 {
4560 if (add_awareness_event(objp, type, LevelUniqueRobotAwarenessState))
4561 {
4562 if (((d_rand() * (static_cast<unsigned>(type) + 4)) >> 15) > 4)
4563 Overall_agitation++;
4564 if (Overall_agitation > OVERALL_AGITATION_MAX)
4565 Overall_agitation = OVERALL_AGITATION_MAX;
4566 }
4567 }
4568 }
4569
4570 namespace {
4571
4572 // ----------------------------------------------------------------------------------
4573 static unsigned process_awareness_events(fvcsegptridx &vcsegptridx, d_level_unique_robot_awareness_state &LevelUniqueRobotAwarenessState, awareness_t &New_awareness)
4574 {
4575 unsigned result{0};
4576 if (!(Game_mode & GM_MULTI) || (Game_mode & GM_MULTI_ROBOTS))
4577 {
4578 const auto Num_awareness_events = std::exchange(LevelUniqueRobotAwarenessState.Num_awareness_events, 0);
4579 if (!Num_awareness_events)
4580 return Num_awareness_events;
4581 result = Num_awareness_events;
4582 New_awareness.fill(player_awareness_type_t::PA_NONE);
4583 const unsigned allowed_recursions_remaining =
4584 #if DXX_BUILD_DESCENT == 2
4585 !EMULATING_D1 ? 3 :
4586 #endif
4587 4;
4588 range_for (auto &i, partial_const_range(LevelUniqueRobotAwarenessState.Awareness_events, Num_awareness_events))
4589 pae_aux(vcsegptridx(i.segnum), i.type, New_awareness, allowed_recursions_remaining);
4590 }
4591 return result;
4592 }
4593
4594 // ----------------------------------------------------------------------------------
4595 static void set_player_awareness_all(fvmobjptr &vmobjptr, fvcsegptridx &vcsegptridx, d_level_unique_robot_awareness_state &LevelUniqueRobotAwarenessState)
4596 {
4597 awareness_t New_awareness;
4598
4599 if (!process_awareness_events(vcsegptridx, LevelUniqueRobotAwarenessState, New_awareness))
4600 return;
4601
4602 for (auto &obj : vmobjptr)
4603 {
4604 if (obj.type == OBJ_ROBOT && obj.control_source == object::control_type::ai)
4605 {
4606 auto &ailp = obj.ctype.ai_info.ail;
4607 auto &na = New_awareness[obj.segnum];
4608 if (ailp.player_awareness_type < na)
4609 {
4610 ailp.player_awareness_type = na;
4611 ailp.player_awareness_time = PLAYER_AWARENESS_INITIAL_TIME;
4612
4613 #if DXX_BUILD_DESCENT == 2
4614 // Clear the bit that says this robot is only awake because a camera woke it up.
4615 obj.ctype.ai_info.SUB_FLAGS &= ~SUB_FLAGS_CAMERA_AWAKE;
4616 #endif
4617 }
4618 }
4619 }
4620 }
4621
4622 }
4623
4624 // ----------------------------------------------------------------------------------
4625 // Do things which need to get done for all AI objects each frame.
4626 // This includes:
4627 // Setting player_awareness (a fix, time in seconds which object is aware of player)
4628 void do_ai_frame_all(const d_robot_info_array &Robot_info)
4629 {
4630 auto &Objects = LevelUniqueObjectState.Objects;
4631 auto &vmobjptr = Objects.vmptr;
4632
4633 set_player_awareness_all(vmobjptr, vcsegptridx, LevelUniqueRobotAwarenessState);
4634
4635 #if DXX_BUILD_DESCENT == 2
4636 auto &BossUniqueState = LevelUniqueObjectState.BossState;
4637 auto &vmobjptridx = Objects.vmptridx;
4638 if (Ai_last_missile_camera)
4639 {
4640 // Clear if supposed misisle camera is not a weapon, or just every so often, just in case.
4641 if (((d_tick_count & 0x0f) == 0) || (Ai_last_missile_camera->type != OBJ_WEAPON)) {
4642 Ai_last_missile_camera = nullptr;
4643 for (auto &obj : vmobjptr)
4644 {
4645 if (obj.type == OBJ_ROBOT)
4646 obj.ctype.ai_info.SUB_FLAGS &= ~SUB_FLAGS_CAMERA_AWAKE;
4647 }
4648 }
4649 }
4650
4651 // (Moved here from do_d2_boss_stuff() because that only gets called if robot aware of player.)
4652 if (BossUniqueState.Boss_dying) {
4653 range_for (const auto &&objp, vmobjptridx)
4654 {
4655 if (objp->type == OBJ_ROBOT)
4656 if (Robot_info[get_robot_id(objp)].boss_flag != boss_robot_id::None)
4657 do_boss_dying_frame(Robot_info, objp);
4658 }
4659 }
4660 #endif
4661 }
4662
4663
4664 // Initializations to be performed for all robots for a new level.
4665 void init_robots_for_level(void)
4666 {
4667 auto &BossUniqueState = LevelUniqueObjectState.BossState;
4668 BossUniqueState.Boss_dying_start_time = 0;
4669 Overall_agitation = 0;
4670 #if DXX_BUILD_DESCENT == 2
4671 GameUniqueState.Final_boss_countdown_time = 0;
4672 Ai_last_missile_camera = nullptr;
4673 #endif
4674 }
4675
4676 namespace {
4677
4678 // Following functions convert ai_local/ai_cloak_info to ai_local/ai_cloak_info_rw to be written to/read from Savegames. Convertin back is not done here - reading is done specifically together with swapping (if necessary). These structs differ in terms of timer values (fix/fix64). as we reset GameTime64 for writing so it can fit into fix it's not necessary to increment savegame version. But if we once store something else into object which might be useful after restoring, it might be handy to increment Savegame version and actually store these new infos.
4679 static void state_ai_local_to_ai_local_rw(const ai_local *ail, ai_local_rw *ail_rw)
4680 {
4681 ail_rw->player_awareness_type = static_cast<int8_t>(ail->player_awareness_type);
4682 ail_rw->retry_count = ail->retry_count;
4683 ail_rw->consecutive_retries = ail->consecutive_retries;
4684 ail_rw->mode = static_cast<uint8_t>(ail->mode);
4685 ail_rw->previous_visibility = static_cast<int8_t>(ail->previous_visibility);
4686 ail_rw->rapidfire_count = ail->rapidfire_count;
4687 ail_rw->goal_segment = underlying_value(ail->goal_segment);
4688 #if DXX_BUILD_DESCENT == 1
4689 ail_rw->last_see_time = 0;
4690 ail_rw->last_attack_time = 0;
4691 #elif DXX_BUILD_DESCENT == 2
4692 ail_rw->next_fire2 = ail->next_fire2;
4693 #endif
4694 ail_rw->next_action_time = ail->next_action_time;
4695 ail_rw->next_fire = ail->next_fire;
4696 ail_rw->player_awareness_time = ail->player_awareness_time;
4697 const auto gametime{GameTime64};
4698 ail_rw->time_player_seen = build_savegametime_from_gametime(gametime, ail->time_player_seen);
4699 ail_rw->time_player_sound_attacked = build_savegametime_from_gametime(gametime, ail->time_player_sound_attacked);
4700 ail_rw->next_misc_sound_time = build_savegametime_from_gametime(gametime, ail->next_misc_sound_time);
4701 ail_rw->time_since_processed = ail->time_since_processed;
4702 for (uint8_t i = 0; i < MAX_SUBMODELS; i++)
4703 {
4704 ail_rw->goal_angles[i].p = ail->goal_angles[i].p;
4705 ail_rw->goal_angles[i].b = ail->goal_angles[i].b;
4706 ail_rw->goal_angles[i].h = ail->goal_angles[i].h;
4707 ail_rw->delta_angles[i].p = ail->delta_angles[i].p;
4708 ail_rw->delta_angles[i].b = ail->delta_angles[i].b;
4709 ail_rw->delta_angles[i].h = ail->delta_angles[i].h;
4710 ail_rw->goal_state[i] = ail->goal_state[(robot_gun_number{i})];
4711 ail_rw->achieved_state[i] = ail->achieved_state[(robot_gun_number{i})];
4712 }
4713 }
4714
4715 static void state_ai_cloak_info_to_ai_cloak_info_rw(const ai_cloak_info *const aic, ai_cloak_info_rw *const aic_rw)
4716 {
4717 aic_rw->last_time = build_savegametime_from_gametime(GameTime64, aic->last_time);
4718 #if DXX_BUILD_DESCENT == 2
4719 aic_rw->last_segment = aic->last_segment;
4720 #endif
4721 aic_rw->last_position.x = aic->last_position.x;
4722 aic_rw->last_position.y = aic->last_position.y;
4723 aic_rw->last_position.z = aic->last_position.z;
4724 }
4725
4726 }
4727
4728 }
4729
4730 namespace dcx {
4731
4732 DEFINE_SERIAL_VMS_VECTOR_TO_MESSAGE();
4733 DEFINE_SERIAL_UDT_TO_MESSAGE(point_seg, p, (p.segnum, serial::pad<2>(), p.point));
4734 ASSERT_SERIAL_UDT_MESSAGE_SIZE(point_seg, 16);
4735
4736 DEFINE_SERIAL_MUTABLE_UDT_TO_MESSAGE(point_seg_array_t, p, (static_cast<std::array<point_seg, MAX_POINT_SEGS> &>(p)));
4737 DEFINE_SERIAL_CONST_UDT_TO_MESSAGE(point_seg_array_t, p, (static_cast<const std::array<point_seg, MAX_POINT_SEGS> &>(p)));
4738
4739 }
4740
4741 namespace dsx {
4742
4743 void ai_save_state(PHYSFS_File *fp)
4744 {
4745 auto &BossUniqueState = LevelUniqueObjectState.BossState;
4746 #if DXX_BUILD_DESCENT == 2
4747 auto &Boss_gate_segs = LevelSharedBossState.Gate_segs;
4748 auto &Boss_teleport_segs = LevelSharedBossState.Teleport_segs;
4749 auto &BuddyState = LevelUniqueObjectState.BuddyState;
4750 #endif
4751 auto &Objects = LevelUniqueObjectState.Objects;
4752 fix tmptime32{0};
4753
4754 const int Ai_initialized = 0;
4755 PHYSFSX_writeBytes(fp, &Ai_initialized, sizeof(int));
4756 PHYSFSX_writeBytes(fp, &Overall_agitation, sizeof(int));
4757 {
4758 ai_local_rw zero{};
4759 range_for (const auto &i, Objects)
4760 {
4761 ai_local_rw ail_rw;
4762 PHYSFSX_writeBytes(fp, i.type == OBJ_ROBOT ? (state_ai_local_to_ai_local_rw(&i.ctype.ai_info.ail, &ail_rw), &ail_rw) : &zero, sizeof(ail_rw));
4763 }
4764 }
4765 PHYSFSX_serialize_write(fp, Point_segs);
4766 //PHYSFSX_writeBytes(fp, Ai_cloak_info, sizeof(ai_cloak_info) * MAX_AI_CLOAK_INFO);
4767 range_for (auto &i, Ai_cloak_info)
4768 {
4769 ai_cloak_info_rw aic_rw;
4770 state_ai_cloak_info_to_ai_cloak_info_rw(&i, &aic_rw);
4771 PHYSFSX_writeBytes(fp, &aic_rw, sizeof(aic_rw));
4772 }
4773 const auto gametime{GameTime64};
4774 {
4775 const auto Boss_cloak_start_time = BossUniqueState.Boss_cloak_start_time;
4776 tmptime32 = build_savegametime_from_gametime(gametime, Boss_cloak_start_time);
4777 PHYSFSX_writeBytes(fp, &tmptime32, sizeof(fix));
4778 tmptime32 = build_savegametime_from_gametime(gametime, Boss_cloak_start_time + Boss_cloak_duration);
4779 PHYSFSX_writeBytes(fp, &tmptime32, sizeof(fix));
4780 }
4781 {
4782 const auto Last_teleport_time = BossUniqueState.Last_teleport_time;
4783 tmptime32 = build_savegametime_from_gametime(gametime, Last_teleport_time);
4784 PHYSFSX_writeBytes(fp, &tmptime32, sizeof(fix));
4785 }
4786 {
4787 const fix Boss_teleport_interval = LevelSharedBossState.Boss_teleport_interval;
4788 PHYSFSX_writeBytes(fp, &Boss_teleport_interval, sizeof(fix));
4789 const fix Boss_cloak_interval = LevelSharedBossState.Boss_cloak_interval;
4790 PHYSFSX_writeBytes(fp, &Boss_cloak_interval, sizeof(fix));
4791 }
4792 PHYSFSX_writeBytes(fp, &Boss_cloak_duration, sizeof(fix));
4793 tmptime32 = build_savegametime_from_gametime(gametime, BossUniqueState.Last_gate_time);
4794 PHYSFSX_writeBytes(fp, &tmptime32, sizeof(fix));
4795 PHYSFSX_writeBytes(fp, &GameUniqueState.Boss_gate_interval, sizeof(fix));
4796 {
4797 const auto Boss_dying_start_time = BossUniqueState.Boss_dying_start_time;
4798 if (Boss_dying_start_time == 0) // if Boss not dead, yet we expect this to be 0, so do not convert!
4799 {
4800 tmptime32 = 0;
4801 }
4802 else
4803 {
4804 tmptime32 = build_savegametime_from_gametime(gametime, Boss_dying_start_time);
4805 if (tmptime32 == 0) // now if our converted value went 0 we should do something against it
4806 tmptime32 = -1;
4807 }
4808 PHYSFSX_writeBytes(fp, &tmptime32, sizeof(fix));
4809 }
4810 {
4811 const int boss_dying = BossUniqueState.Boss_dying;
4812 PHYSFSX_writeBytes(fp, &boss_dying, sizeof(int));
4813 }
4814 const int boss_dying_sound_playing = BossUniqueState.Boss_dying_sound_playing;
4815 PHYSFSX_writeBytes(fp, &boss_dying_sound_playing, sizeof(int));
4816 #if DXX_BUILD_DESCENT == 1
4817 const int boss_hit_this_frame = BossUniqueState.Boss_hit_this_frame;
4818 PHYSFSX_writeBytes(fp, &boss_hit_this_frame, sizeof(int));
4819 const int Boss_been_hit = 0;
4820 PHYSFSX_writeBytes(fp, &Boss_been_hit, sizeof(int));
4821 #elif DXX_BUILD_DESCENT == 2
4822 tmptime32 = build_savegametime_from_gametime(gametime, BossUniqueState.Boss_hit_time);
4823 PHYSFSX_writeBytes(fp, &tmptime32, sizeof(fix));
4824 PHYSFS_writeSLE32(fp, -1);
4825 tmptime32 = build_savegametime_from_gametime(gametime, BuddyState.Escort_last_path_created);
4826 PHYSFSX_writeBytes(fp, &tmptime32, sizeof(fix));
4827 {
4828 const uint32_t Escort_goal_object = BuddyState.Escort_goal_object;
4829 PHYSFSX_writeBytes(fp, &Escort_goal_object, sizeof(Escort_goal_object));
4830 }
4831 {
4832 const uint32_t Escort_special_goal = BuddyState.Escort_special_goal;
4833 PHYSFSX_writeBytes(fp, &Escort_special_goal, sizeof(Escort_special_goal));
4834 }
4835 {
4836 const int egi = BuddyState.Escort_goal_reachable == d_unique_buddy_state::Escort_goal_reachability::unreachable ? -2 : BuddyState.Escort_goal_objidx.get_unchecked_index();
4837 PHYSFSX_writeBytes(fp, &egi, sizeof(int));
4838 }
4839 {
4840 auto &Stolen_items = LevelUniqueObjectState.ThiefState.Stolen_items;
4841 PHYSFSX_writeBytes(fp, &Stolen_items, sizeof(Stolen_items[0]) * Stolen_items.size());
4842 }
4843
4844 {
4845 int temp;
4846 temp = Point_segs_free_ptr - Point_segs;
4847 PHYSFSX_writeBytes(fp, &temp, sizeof(int));
4848 }
4849
4850 unsigned Num_boss_teleport_segs = Boss_teleport_segs.size();
4851 PHYSFSX_writeBytes(fp, &Num_boss_teleport_segs, sizeof(Num_boss_teleport_segs));
4852 unsigned Num_boss_gate_segs = Boss_gate_segs.size();
4853 PHYSFSX_writeBytes(fp, &Num_boss_gate_segs, sizeof(Num_boss_gate_segs));
4854 /* Boss special segment arrays are an array of
4855 * `valptridx<segment>::idx<vc>`, which is not POD because it is not
4856 * default-constructible. Starting in gcc-15, this causes such arrays to
4857 * fail the `std::is_trivial` test in `PHYSFSX_check_writeBytes`. To avoid
4858 * this failure, copy the elements individually into a POD std::array, then
4859 * write that std::array to the file. This extra copy is small, and
4860 * happens only when a save file is written, so the overhead is not worth
4861 * finding a clever way to perform the write directly from the special
4862 * segment array. Further, gcc will normally optimize the call of
4863 * `std::ranges::copy_n` into a call to `memcpy`.
4864 */
4865 const auto build_pod_segs{[](const d_level_shared_boss_state::special_segment_array_t &src, const std::size_t count) {
4866 std::array<uint16_t, 100> pod_gate_segs;
4867 #ifndef __clang__
4868 /* clang-17 cannot perform constant evaluation on `src.max_size()`,
4869 * even though `max_size()` does not depend on what instance `src`
4870 * references.
4871 *
4872 * <clang-17: untested
4873 * clang-17: fails
4874 * >clang-17: untested
4875 * <gcc-12: untested
4876 * gcc-12, gcc-13, gcc-14, gcc-15: works
4877 * >gcc-15: untested
4878 ```
4879 similar/main/ai.cpp:4867:17: error: static assertion expression is not an integral constant expression
4880 4867 | static_assert(pod_gate_segs.max_size() == src.max_size());
4881 | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4882 similar/main/ai.cpp:4867:45: note: function parameter 'src' with unknown value cannot be used in a constant expression
4883 4867 | static_assert(pod_gate_segs.max_size() == src.max_size());
4884 | ^
4885 ```
4886 */
4887 static_assert(pod_gate_segs.max_size() == src.max_size());
4888 #endif
4889 /* Construct a temporary `std::span` from the output for the side
4890 * effect of provoking a debug version of the standard library to check
4891 * that the output array is at least `count` elements long.
4892 */
4893 std::ranges::copy_n(src.begin(), count, std::span(pod_gate_segs).first(count).begin());
4894 return pod_gate_segs;
4895 }};
4896
4897 if (Num_boss_gate_segs)
4898 {
4899 const auto pod_segs{build_pod_segs(Boss_gate_segs, Num_boss_gate_segs)};
4900 PHYSFSX_writeBytes(fp, pod_segs.data(), sizeof(uint16_t) * Num_boss_gate_segs);
4901 }
4902
4903 if (Num_boss_teleport_segs)
4904 {
4905 const auto pod_segs{build_pod_segs(Boss_teleport_segs, Num_boss_teleport_segs)};
4906 PHYSFSX_writeBytes(fp, pod_segs.data(), sizeof(uint16_t) * Num_boss_teleport_segs);
4907 }
4908 #endif
4909 }
4910
4911 }
4912
4913 namespace dcx {
4914
4915 static void PHYSFSX_readAngleVecX(PHYSFS_File *file, vms_angvec &v, const physfsx_endian swap)
4916 {
4917 v.p = {PHYSFSX_readSXE16(file, swap)};
4918 v.b = {PHYSFSX_readSXE16(file, swap)};
4919 v.h = {PHYSFSX_readSXE16(file, swap)};
4920 }
4921
4922 }
4923
4924 namespace dsx {
4925 namespace {
4926
4927 static void ai_local_read_swap(ai_local *ail, const physfsx_endian swap, const NamedPHYSFS_File fp)
4928 {
4929 {
4930 fix tmptime32{0};
4931
4932 #if DXX_BUILD_DESCENT == 1
4933 ail->player_awareness_type = static_cast<player_awareness_type_t>(PHYSFSX_readByte(fp));
4934 ail->retry_count = PHYSFSX_readByte(fp);
4935 ail->consecutive_retries = PHYSFSX_readByte(fp);
4936 ail->mode = static_cast<ai_mode>(PHYSFSX_readByte(fp));
4937 ail->previous_visibility = static_cast<player_visibility_state>(PHYSFSX_readByte(fp));
4938 ail->rapidfire_count = PHYSFSX_readByte(fp);
4939 ail->goal_segment = read_untrusted_segnum_xe16(fp, swap);
4940 PHYSFSX_skipBytes<8>(fp);
4941 ail->next_action_time = {PHYSFSX_readSXE32(fp, swap)};
4942 ail->next_fire = {PHYSFSX_readSXE32(fp, swap)};
4943 #elif DXX_BUILD_DESCENT == 2
4944 ail->player_awareness_type = static_cast<player_awareness_type_t>(PHYSFSX_readSXE32(fp, swap));
4945 ail->retry_count = PHYSFSX_readSXE32(fp, swap);
4946 ail->consecutive_retries = PHYSFSX_readSXE32(fp, swap);
4947 ail->mode = static_cast<ai_mode>(PHYSFSX_readSXE32(fp, swap));
4948 ail->previous_visibility = static_cast<player_visibility_state>(PHYSFSX_readSXE32(fp, swap));
4949 ail->rapidfire_count = PHYSFSX_readSXE32(fp, swap);
4950 ail->goal_segment = read_untrusted_segnum_xe32(fp, swap);
4951 ail->next_action_time = {PHYSFSX_readSXE32(fp, swap)};
4952 ail->next_fire = {PHYSFSX_readSXE32(fp, swap)};
4953 ail->next_fire2 = {PHYSFSX_readSXE32(fp, swap)};
4954 #endif
4955 ail->player_awareness_time = {PHYSFSX_readSXE32(fp, swap)};
4956 tmptime32 = {PHYSFSX_readSXE32(fp, swap)};
4957 ail->time_player_seen = static_cast<fix64>(tmptime32);
4958 tmptime32 = {PHYSFSX_readSXE32(fp, swap)};
4959 ail->time_player_sound_attacked = static_cast<fix64>(tmptime32);
4960 tmptime32 = {PHYSFSX_readSXE32(fp, swap)};
4961 ail->next_misc_sound_time = static_cast<fix64>(tmptime32);
4962 ail->time_since_processed = {PHYSFSX_readSXE32(fp, swap)};
4963
4964 range_for (auto &j, ail->goal_angles)
4965 PHYSFSX_readAngleVecX(fp, j, swap);
4966 range_for (auto &j, ail->delta_angles)
4967 PHYSFSX_readAngleVecX(fp, j, swap);
4968 range_for (auto &j, ail->goal_state)
4969 j = build_ai_state_from_untrusted(PHYSFSX_readByte(fp)).value();
4970 range_for (auto &j, ail->achieved_state)
4971 j = build_ai_state_from_untrusted(PHYSFSX_readByte(fp)).value();
4972 }
4973 }
4974
4975 }
4976
4977 }
4978
4979 namespace dcx {
4980
4981 static void PHYSFSX_readVectorX(PHYSFS_File *file, vms_vector &v, const physfsx_endian swap)
4982 {
4983 v.x = {PHYSFSX_readSXE32(file, swap)};
4984 v.y = {PHYSFSX_readSXE32(file, swap)};
4985 v.z = {PHYSFSX_readSXE32(file, swap)};
4986 }
4987
4988 }
4989
4990 namespace dsx {
4991 namespace {
4992
4993 static void ai_cloak_info_read_n_swap(ai_cloak_info *ci, int n, const physfsx_endian swap, const NamedPHYSFS_File fp)
4994 {
4995 int i;
4996 for (i = 0; i < n; i++, ci++)
4997 {
4998 const fix tmptime32{PHYSFSX_readSXE32(fp, swap)};
4999 ci->last_time = fix64{tmptime32};
5000 #if DXX_BUILD_DESCENT == 2
5001 ci->last_segment = read_untrusted_segnum_xe32(fp, swap);
5002 #endif
5003 PHYSFSX_readVectorX(fp, ci->last_position, swap);
5004 }
5005 }
5006
5007 }
5008
5009 int ai_restore_state(const d_robot_info_array &Robot_info, const NamedPHYSFS_File fp, int version, const physfsx_endian swap)
5010 {
5011 auto &BossUniqueState = LevelUniqueObjectState.BossState;
5012 #if DXX_BUILD_DESCENT == 2
5013 auto &Boss_gate_segs = LevelSharedBossState.Gate_segs;
5014 auto &Boss_teleport_segs = LevelSharedBossState.Teleport_segs;
5015 auto &BuddyState = LevelUniqueObjectState.BuddyState;
5016 #endif
5017 auto &Objects = LevelUniqueObjectState.Objects;
5018 auto &vmobjptridx = Objects.vmptridx;
5019
5020 PHYSFSX_skipBytes<4>(fp);
5021 Overall_agitation = {PHYSFSX_readSXE32(fp, swap)};
5022 range_for (object &obj, Objects)
5023 {
5024 ai_local discard;
5025 ai_local_read_swap(obj.type == OBJ_ROBOT ? &obj.ctype.ai_info.ail : &discard, swap, fp);
5026 }
5027 PHYSFSX_serialize_read(fp, Point_segs);
5028 ai_cloak_info_read_n_swap(Ai_cloak_info.data(), Ai_cloak_info.size(), swap, fp);
5029 BossUniqueState.Boss_cloak_start_time = fix64{fix{PHYSFSX_readSXE32(fp, swap)}};
5030 PHYSFSX_skipBytes<4>(fp);
5031 BossUniqueState.Last_teleport_time = fix64{fix{PHYSFSX_readSXE32(fp, swap)}};
5032
5033 // If boss teleported, set the looping 'see' sound -kreatordxx
5034 // Also make sure any bosses that were generated/released during the game have teleport segs
5035 #if DXX_USE_EDITOR
5036 if (!EditorWindow)
5037 #endif
5038 range_for (const auto &&o, vmobjptridx)
5039 {
5040 if (o->type == OBJ_ROBOT)
5041 {
5042 const auto boss_id = Robot_info[get_robot_id(o)].boss_flag;
5043 if (boss_id != boss_robot_id::None)
5044 {
5045 const auto Last_teleport_time = BossUniqueState.Last_teleport_time;
5046 if (Last_teleport_time != 0 && Last_teleport_time != BossUniqueState.Boss_cloak_start_time)
5047 boss_link_see_sound(Robot_info, o);
5048 boss_init_all_segments(Segments, o);
5049 }
5050 }
5051 }
5052
5053 #if DXX_BUILD_DESCENT == 1
5054 PHYSFSX_skipBytes<12>(fp);
5055 #elif DXX_BUILD_DESCENT == 2
5056 LevelSharedBossState.Boss_teleport_interval = {PHYSFSX_readSXE32(fp, swap)};
5057 LevelSharedBossState.Boss_cloak_interval = {PHYSFSX_readSXE32(fp, swap)};
5058 PHYSFSX_skipBytes<4>(fp);
5059 #endif
5060 BossUniqueState.Last_gate_time = fix64{fix{PHYSFSX_readSXE32(fp, swap)}};
5061 GameUniqueState.Boss_gate_interval = {PHYSFSX_readSXE32(fp, swap)};
5062 BossUniqueState.Boss_dying_start_time = fix64{fix{PHYSFSX_readSXE32(fp, swap)}};
5063 BossUniqueState.Boss_dying = PHYSFSX_readSXE32(fp, swap);
5064 BossUniqueState.Boss_dying_sound_playing = PHYSFSX_readSXE32(fp, swap);
5065 #if DXX_BUILD_DESCENT == 1
5066 (void)version;
5067 BossUniqueState.Boss_hit_this_frame = PHYSFSX_readSXE32(fp, swap);
5068 PHYSFSX_skipBytes<4>(fp);
5069 #elif DXX_BUILD_DESCENT == 2
5070 BossUniqueState.Boss_hit_time = fix64{fix{PHYSFSX_readSXE32(fp, swap)}};
5071
5072 if (version >= 8) {
5073 PHYSFSX_skipBytes<4>(fp);
5074 BuddyState.Escort_last_path_created = fix64{fix{PHYSFSX_readSXE32(fp, swap)}};
5075 BuddyState.Escort_goal_object = static_cast<escort_goal_t>(PHYSFSX_readSXE32(fp, swap));
5076 BuddyState.Escort_special_goal = static_cast<escort_goal_t>(PHYSFSX_readSXE32(fp, swap));
5077 if (const auto o{vcobjidx_t::check_nothrow_index(PHYSFSX_readUXE32(fp, swap))})
5078 {
5079 BuddyState.Escort_goal_objidx = *o;
5080 BuddyState.Escort_goal_reachable = d_unique_buddy_state::Escort_goal_reachability::reachable;
5081 }
5082 else
5083 {
5084 BuddyState.Escort_goal_objidx = object_none;
5085 BuddyState.Escort_goal_reachable = d_unique_buddy_state::Escort_goal_reachability::unreachable;
5086 }
5087 {
5088 auto &Stolen_items = LevelUniqueObjectState.ThiefState.Stolen_items;
5089 PHYSFSX_readBytes(fp, &Stolen_items, sizeof(Stolen_items[0]) * Stolen_items.size());
5090 }
5091 } else {
5092 BuddyState.Escort_last_path_created = 0;
5093 BuddyState.Escort_goal_object = ESCORT_GOAL_UNSPECIFIED;
5094 BuddyState.Escort_special_goal = ESCORT_GOAL_UNSPECIFIED;
5095 BuddyState.Escort_goal_objidx = object_none;
5096 BuddyState.Escort_goal_reachable = d_unique_buddy_state::Escort_goal_reachability::unreachable;
5097
5098 LevelUniqueObjectState.ThiefState.Stolen_items.fill(LevelUniqueObjectState.ThiefState.stolen_item_type_none);
5099 }
5100
5101 if (version >= 15) {
5102 unsigned temp;
5103 temp = PHYSFSX_readSXE32(fp, swap);
5104 if (temp > Point_segs.size())
5105 throw std::out_of_range("too many points");
5106 Point_segs_free_ptr = Point_segs.begin() + temp;
5107 } else
5108 ai_reset_all_paths();
5109
5110 if (version >= 21) {
5111 const xrange Num_boss_teleport_segs = static_cast<unsigned>(PHYSFSX_readSXE32(fp, swap));
5112 const xrange Num_boss_gate_segs = static_cast<unsigned>(PHYSFSX_readSXE32(fp, swap));
5113
5114 Boss_gate_segs.clear();
5115 for (const auto i : Num_boss_gate_segs)
5116 {
5117 (void)i;
5118 const segnum_t s{PHYSFSX_readUXE16(fp, swap)};
5119 Boss_gate_segs.emplace_back(s);
5120 }
5121
5122 Boss_teleport_segs.clear();
5123 for (const auto i : Num_boss_teleport_segs)
5124 {
5125 (void)i;
5126 const segnum_t s{PHYSFSX_readUXE16(fp, swap)};
5127 Boss_teleport_segs.emplace_back(s);
5128 }
5129 }
5130 #endif
5131
5132 return 1;
5133 }
5134
5135 }