Merge branch 'terencehill/bot_waypoints' into 'master'
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / bot / default / havocbot / havocbot.qc
1 #include "havocbot.qh"
2
3 #include "roles.qh"
4
5 #include <server/defs.qh>
6 #include <server/miscfunctions.qh>
7 #include "../cvars.qh"
8
9 #include "../aim.qh"
10 #include "../bot.qh"
11 #include "../navigation.qh"
12 #include "../scripting.qh"
13 #include "../waypoints.qh"
14
15 #include <common/constants.qh>
16 #include <common/impulses/all.qh>
17 #include <common/net_linked.qh>
18 #include <common/physics/player.qh>
19 #include <common/state.qh>
20 #include <common/items/_mod.qh>
21 #include <common/wepent.qh>
22
23 #include <common/mapobjects/func/ladder.qh>
24 #include <common/mapobjects/teleporters.qh>
25 #include <common/mapobjects/trigger/jumppads.qh>
26
27 #include <lib/warpzone/common.qh>
28
29 void havocbot_ai(entity this)
30 {
31         if(this.draggedby)
32                 return;
33
34         this.bot_aimdir_executed = false;
35         // lock aim if teleported or passing through a warpzone
36         if (this.lastteleporttime && !this.jumppadcount)
37                 this.bot_aimdir_executed = true;
38
39         if(bot_execute_commands(this))
40                 return;
41
42         if (bot_strategytoken == this && !bot_strategytoken_taken)
43         {
44                 if(this.havocbot_blockhead)
45                 {
46                         this.havocbot_blockhead = false;
47                 }
48                 else
49                 {
50                         if (!this.jumppadcount && !STAT(FROZEN, this))
51                                 this.havocbot_role(this); // little too far down the rabbit hole
52                 }
53
54                 // if we don't have a goal and we're under water look for a waypoint near the "shore" and push it
55                 if(!(IS_DEAD(this) || STAT(FROZEN, this)))
56                 if(!this.goalcurrent)
57                 if(this.waterlevel == WATERLEVEL_SWIMMING || (this.aistatus & AI_STATUS_OUT_WATER))
58                 {
59                         // Look for the closest waypoint out of water
60                         entity newgoal = NULL;
61                         IL_EACH(g_waypoints, vdist(it.origin - this.origin, <=, 10000),
62                         {
63                                 if(it.origin.z < this.origin.z)
64                                         continue;
65
66                                 if(it.origin.z - this.origin.z - this.view_ofs.z > 100)
67                                         continue;
68
69                                 if (pointcontents(it.origin + it.maxs + '0 0 1') != CONTENT_EMPTY)
70                                         continue;
71
72                                 traceline(this.origin + this.view_ofs, ((it.absmin + it.absmax) * 0.5), true, this);
73
74                                 if(trace_fraction < 1)
75                                         continue;
76
77                                 if(!newgoal || vlen2(it.origin - this.origin) < vlen2(newgoal.origin - this.origin))
78                                         newgoal = it;
79                         });
80
81                         if(newgoal)
82                         {
83                         //      te_wizspike(newgoal.origin);
84                                 navigation_pushroute(this, newgoal);
85                         }
86                 }
87
88                 // token has been used this frame
89                 bot_strategytoken_taken = true;
90         }
91
92         if(IS_DEAD(this) || STAT(FROZEN, this))
93         {
94                 if (this.goalcurrent)
95                         navigation_clearroute(this);
96                 return;
97         }
98
99         havocbot_chooseenemy(this);
100
101         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
102         {
103                 .entity weaponentity = weaponentities[slot];
104                 if(this.(weaponentity).m_weapon != WEP_Null || slot == 0)
105                 if(this.(weaponentity).bot_chooseweapontime < time)
106                 {
107                         this.(weaponentity).bot_chooseweapontime = time + autocvar_bot_ai_chooseweaponinterval;
108                         havocbot_chooseweapon(this, weaponentity);
109                 }
110         }
111         havocbot_aim(this);
112         lag_update(this);
113
114         if (this.bot_aimtarg)
115         {
116                 this.aistatus |= AI_STATUS_ATTACKING;
117                 this.aistatus &= ~AI_STATUS_ROAMING;
118
119                 if(STAT(WEAPONS, this))
120                 {
121                         if (autocvar_bot_nofire || IS_INDEPENDENT_PLAYER(this))
122                         {
123                                 PHYS_INPUT_BUTTON_ATCK(this) = false;
124                                 PHYS_INPUT_BUTTON_ATCK2(this) = false;
125                         }
126                         else
127                         {
128                                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
129                                 {
130                                         .entity weaponentity = weaponentities[slot];
131                                         Weapon w = this.(weaponentity).m_weapon;
132                                         if(w == WEP_Null && slot != 0)
133                                                 continue;
134                                         w.wr_aim(w, this, weaponentity);
135                                         if(PHYS_INPUT_BUTTON_ATCK(this) || PHYS_INPUT_BUTTON_ATCK2(this)) // TODO: what if we didn't fire this weapon, but the previous?
136                                                 this.(weaponentity).lastfiredweapon = this.(weaponentity).m_weapon.m_id;
137                                 }
138                         }
139                 }
140                 else
141                 {
142                         if(IS_PLAYER(this.bot_aimtarg))
143                                 bot_aimdir(this, this.bot_aimtarg.origin + this.bot_aimtarg.view_ofs - this.origin - this.view_ofs, 0);
144                 }
145         }
146         else if (this.goalcurrent)
147         {
148                 this.aistatus |= AI_STATUS_ROAMING;
149                 this.aistatus &= ~AI_STATUS_ATTACKING;
150         }
151
152         havocbot_movetogoal(this);
153         if (!this.bot_aimdir_executed && this.goalcurrent)
154         {
155                 // Heading
156                 vector dir = get_closer_dest(this.goalcurrent, this.origin);
157                 dir -= this.origin + this.view_ofs;
158                 dir.z = 0;
159                 bot_aimdir(this, dir, 0);
160         }
161
162         // if the bot is not attacking, consider reloading weapons
163         if (!(this.aistatus & AI_STATUS_ATTACKING))
164         {
165                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
166                 {
167                         .entity weaponentity = weaponentities[slot];
168
169                         if(this.(weaponentity).m_weapon == WEP_Null && slot != 0)
170                                 continue;
171
172                         // we are currently holding a weapon that's not fully loaded, reload it
173                         if(skill >= 2) // bots can only reload the held weapon on purpose past this skill
174                         if(this.(weaponentity).clip_load < this.(weaponentity).clip_size)
175                                 CS(this).impulse = IMP_weapon_reload.impulse; // not sure if this is done right
176
177                         // if we're not reloading a weapon, switch to any weapon in our invnetory that's not fully loaded to reload it next
178                         // the code above executes next frame, starting the reloading then
179                         if(skill >= 5) // bots can only look for unloaded weapons past this skill
180                         if(this.(weaponentity).clip_load >= 0) // only if we're not reloading a weapon already
181                         {
182                                 FOREACH(Weapons, it != WEP_Null, {
183                                         if((STAT(WEAPONS, this) & (it.m_wepset)) && (it.spawnflags & WEP_FLAG_RELOADABLE) && (this.(weaponentity).weapon_load[it.m_id] < it.reloading_ammo))
184                                         {
185                                                 this.(weaponentity).m_switchweapon = it;
186                                                 break;
187                                         }
188                                 });
189                         }
190                 }
191         }
192 }
193
194 void havocbot_keyboard_movement(entity this, vector destorg)
195 {
196         if(time <= this.havocbot_keyboardtime)
197                 return;
198
199         float sk = skill + this.bot_moveskill;
200         this.havocbot_keyboardtime =
201                 max(
202                         this.havocbot_keyboardtime
203                                 + 0.05 / max(1, sk + this.havocbot_keyboardskill)
204                                 + random() * 0.025 / max(0.00025, skill + this.havocbot_keyboardskill)
205                 , time);
206         vector keyboard = CS(this).movement / autocvar_sv_maxspeed;
207
208         float trigger = autocvar_bot_ai_keyboard_threshold;
209
210         // categorize forward movement
211         // at skill < 1.5 only forward
212         // at skill < 2.5 only individual directions
213         // at skill < 4.5 only individual directions, and forward diagonals
214         // at skill >= 4.5, all cases allowed
215         if (keyboard.x > trigger)
216         {
217                 keyboard.x = 1;
218                 if (sk < 2.5)
219                         keyboard.y = 0;
220         }
221         else if (keyboard.x < -trigger && sk > 1.5)
222         {
223                 keyboard.x = -1;
224                 if (sk < 4.5)
225                         keyboard.y = 0;
226         }
227         else
228         {
229                 keyboard.x = 0;
230                 if (sk < 1.5)
231                         keyboard.y = 0;
232         }
233         if (sk < 4.5)
234                 keyboard.z = 0;
235
236         if (keyboard.y > trigger)
237                 keyboard.y = 1;
238         else if (keyboard.y < -trigger)
239                 keyboard.y = -1;
240         else
241                 keyboard.y = 0;
242
243         if (keyboard.z > trigger)
244                 keyboard.z = 1;
245         else if (keyboard.z < -trigger)
246                 keyboard.z = -1;
247         else
248                 keyboard.z = 0;
249
250         // make sure bots don't get stuck if havocbot_keyboardtime is very high
251         if (keyboard == '0 0 0')
252                 this.havocbot_keyboardtime = min(this.havocbot_keyboardtime, time + 0.2);
253
254         this.havocbot_keyboard = keyboard * autocvar_sv_maxspeed;
255         if (this.havocbot_ducktime > time)
256                 PHYS_INPUT_BUTTON_CROUCH(this) = true;
257
258         keyboard = this.havocbot_keyboard;
259         float blend = bound(0, vlen(destorg - this.origin) / autocvar_bot_ai_keyboard_distance, 1); // When getting close move with 360 degree
260         //dprint("movement ", vtos(CS(this).movement), " keyboard ", vtos(keyboard), " blend ", ftos(blend), "\n");
261         CS(this).movement = CS(this).movement + (keyboard - CS(this).movement) * blend;
262 }
263
264 void havocbot_bunnyhop(entity this, vector dir)
265 {
266         // Don't jump when attacking
267         if(this.aistatus & AI_STATUS_ATTACKING)
268                 return;
269
270         if(IS_PLAYER(this.goalcurrent))
271                 return;
272
273         if((this.aistatus & AI_STATUS_RUNNING) && vdist(this.velocity, <, autocvar_sv_maxspeed * 0.75)
274                 || (this.aistatus & AI_STATUS_DANGER_AHEAD))
275         {
276                 this.aistatus &= ~AI_STATUS_RUNNING;
277                 PHYS_INPUT_BUTTON_JUMP(this) = false;
278                 this.bot_canruntogoal = 0;
279                 this.bot_timelastseengoal = 0;
280                 return;
281         }
282
283         if(this.waterlevel > WATERLEVEL_WETFEET || IS_DUCKED(this))
284         {
285                 this.aistatus &= ~AI_STATUS_RUNNING;
286                 return;
287         }
288
289         if(this.bot_lastseengoal != this.goalcurrent && !(this.aistatus & AI_STATUS_RUNNING))
290         {
291                 this.bot_canruntogoal = 0;
292                 this.bot_timelastseengoal = 0;
293         }
294
295         vector gco = get_closer_dest(this.goalcurrent, this.origin);
296
297         // Run only to visible goals
298         if(IS_ONGROUND(this))
299         if(vdist(vec2(this.velocity), >=, autocvar_sv_maxspeed))
300         if(checkpvs(this.origin + this.view_ofs, this.goalcurrent))
301         {
302                 this.bot_lastseengoal = this.goalcurrent;
303
304                 // seen it before
305                 if(this.bot_timelastseengoal)
306                 {
307                         // for a period of time
308                         if(time - this.bot_timelastseengoal > autocvar_bot_ai_bunnyhop_firstjumpdelay)
309                         {
310                                 bool checkdistance = true;
311
312                                 // don't run if it is too close
313                                 if(this.bot_canruntogoal==0)
314                                 {
315                                         if(vdist(this.origin - gco, >, autocvar_bot_ai_bunnyhop_startdistance))
316                                                 this.bot_canruntogoal = 1;
317                                         else
318                                                 this.bot_canruntogoal = -1;
319                                 }
320
321                                 if(this.bot_canruntogoal != 1)
322                                         return;
323
324                                 if(this.aistatus & AI_STATUS_ROAMING)
325                                 if(this.goalcurrent.classname == "waypoint")
326                                 if (!(this.goalcurrent.wpflags & WAYPOINTFLAG_PERSONAL))
327                                 if(fabs(gco.z - this.origin.z) < this.maxs.z - this.mins.z)
328                                 if (this.goalstack01 && !wasfreed(this.goalstack01))
329                                 if (!(this.goalstack01.wpflags & WAYPOINTFLAG_JUMP))
330                                 {
331                                         vector gno = (this.goalstack01.absmin + this.goalstack01.absmax) * 0.5;
332                                         vector deviation = vectoangles(gno - this.origin) - vectoangles(gco - this.origin);
333                                         while (deviation.y < -180) deviation.y = deviation.y + 360;
334                                         while (deviation.y > 180) deviation.y = deviation.y - 360;
335
336                                         if(fabs(deviation.y) < 20)
337                                         if(vlen2(this.origin - gco) < vlen2(this.origin - gno))
338                                         if(fabs(gno.z - gco.z) < this.maxs.z - this.mins.z)
339                                         {
340                                                 if(vdist(gco - gno, >, autocvar_bot_ai_bunnyhop_startdistance))
341                                                 if(checkpvs(this.origin + this.view_ofs, this.goalstack01))
342                                                 {
343                                                         checkdistance = false;
344                                                 }
345                                         }
346                                 }
347
348                                 if(checkdistance)
349                                 {
350                                         this.aistatus &= ~AI_STATUS_RUNNING;
351                                         // increase stop distance in case the goal is on a slope or a lower platform
352                                         if(vdist(this.origin - gco, >, autocvar_bot_ai_bunnyhop_stopdistance + (this.origin.z - gco.z)))
353                                                 PHYS_INPUT_BUTTON_JUMP(this) = true;
354                                 }
355                                 else
356                                 {
357                                         this.aistatus |= AI_STATUS_RUNNING;
358                                         PHYS_INPUT_BUTTON_JUMP(this) = true;
359                                 }
360                         }
361                 }
362                 else
363                 {
364                         this.bot_timelastseengoal = time;
365                 }
366         }
367         else
368         {
369                 this.bot_timelastseengoal = 0;
370         }
371 }
372
373 // return true when bot isn't getting closer to the current goal
374 bool havocbot_checkgoaldistance(entity this, vector gco)
375 {
376         if (this.bot_stop_moving_timeout > time)
377                 return false;
378         float curr_dist_z = max(20, fabs(this.origin.z - gco.z));
379         float curr_dist_2d = max(20, vlen(vec2(this.origin - gco)));
380         float distance_time = this.goalcurrent_distance_time;
381         if(distance_time < 0)
382                 distance_time = -distance_time;
383         if(curr_dist_z >= this.goalcurrent_distance_z && curr_dist_2d >= this.goalcurrent_distance_2d)
384         {
385                 if(!distance_time)
386                         this.goalcurrent_distance_time = time;
387                 else if (time - distance_time > 0.5)
388                         return true;
389         }
390         else
391         {
392                 // reduce it a little bit so it works even with very small approaches to the goal
393                 this.goalcurrent_distance_z = max(20, curr_dist_z - 10);
394                 this.goalcurrent_distance_2d = max(20, curr_dist_2d - 10);
395                 this.goalcurrent_distance_time = 0;
396         }
397         return false;
398 }
399
400 entity havocbot_select_an_item_of_group(entity this, int gr)
401 {
402         entity selected = NULL;
403         float selected_dist2 = 0;
404         // select farthest item of this group from bot's position
405         IL_EACH(g_items, it.item_group == gr && it.solid,
406         {
407                 float dist2 = vlen2(this.origin - it.origin);
408                 if (dist2 < 600 ** 2 && dist2 > selected_dist2)
409                 {
410                         selected = it;
411                         selected_dist2 = vlen2(this.origin - selected.origin);
412                 }
413         });
414
415         if (!selected)
416                 return NULL;
417
418         set_tracewalk_dest(selected, this.origin, false);
419         if (!tracewalk(this, this.origin, STAT(PL_MIN, this), STAT(PL_MAX, this),
420                 tracewalk_dest, tracewalk_dest_height, bot_navigation_movemode))
421         {
422                 return NULL;
423         }
424
425         return selected;
426 }
427
428 void havocbot_movetogoal(entity this)
429 {
430         vector diff;
431         vector dir;
432         vector flatdir;
433         vector evadeobstacle;
434         vector evadelava;
435         float dodge_enemy_factor = 1;
436         float maxspeed;
437         //float dist;
438         vector dodge;
439         //if (this.goalentity)
440         //      te_lightning2(this, this.origin, (this.goalentity.absmin + this.goalentity.absmax) * 0.5);
441         CS(this).movement = '0 0 0';
442         maxspeed = autocvar_sv_maxspeed;
443
444         PHYS_INPUT_BUTTON_CROUCH(this) = boolean(this.goalcurrent.wpflags & WAYPOINTFLAG_CROUCH);
445
446         PHYS_INPUT_BUTTON_JETPACK(this) = false;
447         // Jetpack navigation
448         if(this.navigation_jetpack_goal)
449         if(this.goalcurrent==this.navigation_jetpack_goal)
450         if(GetResource(this, RES_FUEL))
451         {
452                 if(autocvar_bot_debug_goalstack)
453                 {
454                         debuggoalstack(this);
455                         te_wizspike(this.navigation_jetpack_point);
456                 }
457
458                 // Take off
459                 if (!(this.aistatus & AI_STATUS_JETPACK_FLYING))
460                 {
461                         // Brake almost completely so it can get a good direction
462                         if(vdist(this.velocity, >, 10))
463                                 return;
464                         this.aistatus |= AI_STATUS_JETPACK_FLYING;
465                 }
466
467                 makevectors(this.v_angle.y * '0 1 0');
468                 dir = normalize(this.navigation_jetpack_point - this.origin);
469
470                 // Landing
471                 if(this.aistatus & AI_STATUS_JETPACK_LANDING)
472                 {
473                         // Calculate brake distance in xy
474                         float d = vlen(vec2(this.origin - (this.goalcurrent.absmin + this.goalcurrent.absmax) * 0.5));
475                         float vel2 = vlen2(vec2(this.velocity));
476                         float db = (vel2 / (autocvar_g_jetpack_acceleration_side * 2)) + 100;
477                         //LOG_INFOF("distance %d, velocity %d, brake at %d ", ceil(d), ceil(v), ceil(db));
478                         if(d < db || d < 500)
479                         {
480                                 // Brake
481                                 if (vel2 > (maxspeed * 0.3) ** 2)
482                                 {
483                                         CS(this).movement_x = dir * v_forward * -maxspeed;
484                                         return;
485                                 }
486                                 // Switch to normal mode
487                                 this.navigation_jetpack_goal = NULL;
488                                 this.aistatus &= ~AI_STATUS_JETPACK_LANDING;
489                                 this.aistatus &= ~AI_STATUS_JETPACK_FLYING;
490                                 return;
491                         }
492                 }
493                 else if(checkpvs(this.origin,this.goalcurrent))
494                 {
495                         // If I can see the goal switch to landing code
496                         this.aistatus &= ~AI_STATUS_JETPACK_FLYING;
497                         this.aistatus |= AI_STATUS_JETPACK_LANDING;
498                         return;
499                 }
500
501                 // Flying
502                 PHYS_INPUT_BUTTON_JETPACK(this) = true;
503                 if(this.navigation_jetpack_point.z - STAT(PL_MAX, this).z + STAT(PL_MIN, this).z < this.origin.z)
504                 {
505                         CS(this).movement_x = dir * v_forward * maxspeed;
506                         CS(this).movement_y = dir * v_right * maxspeed;
507                 }
508                 return;
509         }
510
511         // Handling of jump pads
512         if(this.jumppadcount)
513         {
514                 if(this.goalcurrent.wpflags & WAYPOINTFLAG_TELEPORT)
515                 {
516                         this.aistatus |= AI_STATUS_OUT_JUMPPAD;
517                         if(navigation_poptouchedgoals(this))
518                                 return;
519                 }
520                 else if(this.aistatus & AI_STATUS_OUT_JUMPPAD)
521                 {
522                         // If got stuck on the jump pad try to reach the farthest visible waypoint
523                         // but with some randomness so it can try out different paths
524                         if(!this.goalcurrent)
525                         {
526                                 entity newgoal = NULL;
527                                 IL_EACH(g_waypoints, vdist(it.origin - this.origin, <=, 1000),
528                                 {
529                                         if(it.wpflags & WAYPOINTFLAG_TELEPORT)
530                                         if(it.origin.z < this.origin.z - 100 && vdist(vec2(it.origin - this.origin), <, 100))
531                                                 continue;
532
533                                         traceline(this.origin + this.view_ofs, ((it.absmin + it.absmax) * 0.5), true, this);
534
535                                         if(trace_fraction < 1)
536                                                 continue;
537
538                                         if(!newgoal || ((random() < 0.8) && vlen2(it.origin - this.origin) > vlen2(newgoal.origin - this.origin)))
539                                                 newgoal = it;
540                                 });
541
542                                 if(newgoal)
543                                 {
544                                         this.ignoregoal = this.goalcurrent;
545                                         this.ignoregoaltime = time + autocvar_bot_ai_ignoregoal_timeout;
546                                         navigation_clearroute(this);
547                                         navigation_routetogoal(this, newgoal, this.origin);
548                                         if(autocvar_bot_debug_goalstack)
549                                                 debuggoalstack(this);
550                                         this.aistatus &= ~AI_STATUS_OUT_JUMPPAD;
551                                 }
552                         }
553                         else //if (this.goalcurrent)
554                         {
555                                 if (this.goalcurrent.bot_pickup)
556                                 {
557                                         entity jumppad_wp = this.goalcurrent_prev;
558                                         navigation_poptouchedgoals(this);
559                                         if(!this.goalcurrent && jumppad_wp.wp00)
560                                         {
561                                                 // head to the jumppad destination once bot reaches the goal item
562                                                 navigation_pushroute(this, jumppad_wp.wp00);
563                                         }
564                                 }
565                                 vector gco = (this.goalcurrent.absmin + this.goalcurrent.absmax) * 0.5;
566                                 if (this.origin.z > gco.z && vdist(vec2(this.velocity), <, autocvar_sv_maxspeed))
567                                 {
568                                         if (this.velocity.z < 0)
569                                                 this.aistatus &= ~AI_STATUS_OUT_JUMPPAD;
570                                 }
571                                 else if(havocbot_checkgoaldistance(this, gco))
572                                 {
573                                         navigation_clearroute(this);
574                                         navigation_goalrating_timeout_force(this);
575                                 }
576                                 else
577                                         return;
578                         }
579                 }
580                 else //if (!(this.aistatus & AI_STATUS_OUT_JUMPPAD))
581                 {
582                         if(this.velocity.z > 0 && this.origin.z - this.lastteleport_origin.z > (this.maxs.z - this.mins.z) * 0.5)
583                         {
584                                 vector velxy = this.velocity; velxy_z = 0;
585                                 if(vdist(velxy, <, autocvar_sv_maxspeed * 0.2))
586                                 {
587                                         LOG_TRACE("Warning: ", this.netname, " got stuck on a jumppad (velocity in xy is ", vtos(velxy), "), trying to get out of it now");
588                                         this.aistatus |= AI_STATUS_OUT_JUMPPAD;
589                                 }
590                                 return;
591                         }
592
593                         // Don't chase players while using a jump pad
594                         if(IS_PLAYER(this.goalcurrent) || IS_PLAYER(this.goalstack01))
595                                 return;
596                 }
597         }
598         else if(this.aistatus & AI_STATUS_OUT_JUMPPAD)
599                 this.aistatus &= ~AI_STATUS_OUT_JUMPPAD;
600
601         // If there is a trigger_hurt right below try to use the jetpack or make a rocketjump
602         if (skill > 6 && !(IS_ONGROUND(this)))
603         {
604                 #define ROCKETJUMP_DAMAGE() WEP_CVAR(devastator, damage) * 0.8 \
605                         * ((this.strength_finished > time) ? autocvar_g_balance_powerup_strength_selfdamage : 1) \
606                         * ((this.invincible_finished > time) ? autocvar_g_balance_powerup_invincible_takedamage : 1)
607
608                 tracebox(this.origin, this.mins, this.maxs, this.origin + '0 0 -65536', MOVE_NOMONSTERS, this);
609                 if(tracebox_hits_trigger_hurt(this.origin, this.mins, this.maxs, trace_endpos ))
610                 if(this.items & IT_JETPACK)
611                 {
612                         tracebox(this.origin, this.mins, this.maxs, this.origin + '0 0 65536', MOVE_NOMONSTERS, this);
613                         if(tracebox_hits_trigger_hurt(this.origin, this.mins, this.maxs, trace_endpos + '0 0 1' ))
614                         {
615                                 if(this.velocity.z<0)
616                                         PHYS_INPUT_BUTTON_JETPACK(this) = true;
617                         }
618                         else
619                                 PHYS_INPUT_BUTTON_JETPACK(this) = true;
620
621                         // If there is no goal try to move forward
622
623                         if(this.goalcurrent==NULL)
624                                 dir = v_forward;
625                         else
626                                 dir = normalize(( ( this.goalcurrent.absmin + this.goalcurrent.absmax ) * 0.5 ) - this.origin);
627
628                         vector xyvelocity = this.velocity; xyvelocity_z = 0;
629                         float xyspeed = xyvelocity * dir;
630
631                         if(xyspeed < (maxspeed / 2))
632                         {
633                                 makevectors(this.v_angle.y * '0 1 0');
634                                 tracebox(this.origin, this.mins, this.maxs, this.origin + (dir * maxspeed * 3), MOVE_NOMONSTERS, this);
635                                 if(trace_fraction==1)
636                                 {
637                                         CS(this).movement_x = dir * v_forward * maxspeed;
638                                         CS(this).movement_y = dir * v_right * maxspeed;
639                                         if (skill < 10)
640                                                 havocbot_keyboard_movement(this, this.origin + dir * 100);
641                                 }
642                         }
643
644                         this.havocbot_blockhead = true;
645
646                         return;
647                 }
648                 else if(!this.jumppadcount && !waypoint_is_hardwiredlink(this.goalcurrent_prev, this.goalcurrent)
649                         && !(this.goalcurrent_prev && this.goalcurrent_prev.wpflags & WAYPOINTFLAG_JUMP)
650                         && GetResource(this, RES_HEALTH) + GetResource(this, RES_ARMOR) > ROCKETJUMP_DAMAGE())
651                 {
652                         if(this.velocity.z < 0)
653                         {
654                                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
655                                 {
656                                         .entity weaponentity = weaponentities[slot];
657
658                                         if(this.(weaponentity).m_weapon == WEP_Null && slot != 0)
659                                                 continue;
660
661                                         if(client_hasweapon(this, WEP_DEVASTATOR, weaponentity, true, false))
662                                         {
663                                                 CS(this).movement_x = maxspeed;
664
665                                                 if(this.rocketjumptime)
666                                                 {
667                                                         if(time > this.rocketjumptime)
668                                                         {
669                                                                 PHYS_INPUT_BUTTON_ATCK2(this) = true;
670                                                                 this.rocketjumptime = 0;
671                                                         }
672                                                         return;
673                                                 }
674
675                                                 this.(weaponentity).m_switchweapon = WEP_DEVASTATOR;
676                                                 this.v_angle_x = 90;
677                                                 PHYS_INPUT_BUTTON_ATCK(this) = true;
678                                                 this.rocketjumptime = time + WEP_CVAR(devastator, detonatedelay);
679                                                 return;
680                                         }
681                                 }
682                         }
683                 }
684                 else
685                 {
686                         // If there is no goal try to move forward
687                         if(this.goalcurrent==NULL)
688                                 CS(this).movement_x = maxspeed;
689                 }
690         }
691
692         // If we are under water with no goals, swim up
693         if(this.waterlevel && !this.goalcurrent)
694         {
695                 dir = '0 0 0';
696                 if(this.waterlevel>WATERLEVEL_SWIMMING)
697                         dir.z = 1;
698                 else if(this.velocity.z >= 0 && !(this.waterlevel == WATERLEVEL_WETFEET && this.watertype == CONTENT_WATER))
699                         PHYS_INPUT_BUTTON_JUMP(this) = true;
700                 else
701                         PHYS_INPUT_BUTTON_JUMP(this) = false;
702                 makevectors(this.v_angle.y * '0 1 0');
703                 vector v = dir * maxspeed;
704                 CS(this).movement.x = v * v_forward;
705                 CS(this).movement.y = v * v_right;
706                 CS(this).movement.z = v * v_up;
707         }
708
709         // if there is nowhere to go, exit
710         if (this.goalcurrent == NULL)
711                 return;
712
713
714         bool locked_goal = false;
715         if((this.goalentity && wasfreed(this.goalentity))
716                 || (this.goalcurrent == this.goalentity && this.goalentity.tag_entity))
717         {
718                 navigation_clearroute(this);
719                 navigation_goalrating_timeout_force(this);
720                 return;
721         }
722         else if(this.goalentity.tag_entity)
723         {
724                 navigation_goalrating_timeout_expire(this, 2);
725         }
726         else if(this.goalentity.bot_pickup)
727         {
728                 if(this.goalentity.bot_pickup_respawning)
729                 {
730                         if(this.goalentity.solid) // item respawned
731                                 this.goalentity.bot_pickup_respawning = false;
732                         else if(time < this.goalentity.scheduledrespawntime - 10) // item already taken (by someone else)
733                         {
734                                 if(checkpvs(this.origin, this.goalentity))
735                                 {
736                                         this.goalentity.bot_pickup_respawning = false;
737                                         navigation_goalrating_timeout_expire(this, random());
738                                 }
739                                 locked_goal = true; // wait for item to respawn
740                         }
741                         else if(this.goalentity == this.goalcurrent)
742                                 locked_goal = true; // wait for item to respawn
743                 }
744                 else if(!this.goalentity.solid && !boxesoverlap(this.goalentity.absmin, this.goalentity.absmax, this.absmin, this.absmax))
745                 {
746                         if(checkpvs(this.origin, this.goalentity))
747                         {
748                                 navigation_goalrating_timeout_expire(this, random());
749                         }
750                 }
751         }
752         if (this.goalcurrent == this.goalentity && this.goalentity_lock_timeout > time)
753                 locked_goal = true;
754
755         if (navigation_shortenpath(this))
756         {
757                 if (vdist(this.origin - this.goalcurrent_prev.origin, <, 50)
758                         && navigation_goalrating_timeout_can_be_anticipated(this))
759                 {
760                         navigation_goalrating_timeout_force(this);
761                 }
762         }
763
764         bool goalcurrent_can_be_removed = false;
765         if (IS_PLAYER(this.goalcurrent) || IS_MONSTER(this.goalcurrent))
766         {
767                 bool freeze_state_changed = (boolean(STAT(FROZEN, this.goalentity)) != this.goalentity_shouldbefrozen);
768                 if (IS_DEAD(this.goalcurrent) || (this.goalentity == this.goalcurrent && freeze_state_changed))
769                 {
770                         goalcurrent_can_be_removed = true;
771                         // don't remove if not visible
772                         if (checkpvs(this.origin + this.view_ofs, this.goalcurrent))
773                         {
774                                 if (IS_DEAD(this.goalcurrent))
775                                 {
776                                         IL_EACH(g_items, it.enemy == this.goalcurrent && Item_IsLoot(it),
777                                         {
778                                                 if (vdist(it.origin - this.goalcurrent.death_origin, <, 50))
779                                                 {
780                                                         navigation_clearroute(this);
781                                                         navigation_pushroute(this, it);
782                                                         // loot can't be immediately rated since it isn't on ground yet
783                                                         // it will be rated after a second when on ground, meanwhile head to it
784                                                         navigation_goalrating_timeout_expire(this, 1);
785                                                         return;
786                                                 }
787                                         });
788                                 }
789                                 if (!Item_IsLoot(this.goalcurrent))
790                                 {
791                                         navigation_goalrating_timeout_force(this);
792                                         return;
793                                 }
794                         }
795                 }
796                 else if (!(STAT(FROZEN, this.goalentity)) && this.bot_tracewalk_time < time)
797                 {
798                         set_tracewalk_dest(this.goalcurrent, this.origin, true);
799                         if (!(trace_ent == this || tracewalk(this, this.origin, this.mins, this.maxs,
800                                 tracewalk_dest, tracewalk_dest_height, bot_navigation_movemode)))
801                         {
802                                 navigation_goalrating_timeout_force(this);
803                                 return;
804                         }
805                         this.bot_tracewalk_time = max(time, this.bot_tracewalk_time) + 0.25;
806                 }
807         }
808
809         if(!locked_goal)
810         {
811                 // optimize path finding by anticipating goalrating when bot is near a waypoint;
812                 // in this case path finding can start directly from a waypoint instead of
813                 // looking for all the reachable waypoints up to a certain distance
814                 if (navigation_poptouchedgoals(this))
815                 {
816                         if (this.goalcurrent)
817                         {
818                                 if (goalcurrent_can_be_removed)
819                                 {
820                                         // remove even if not visible
821                                         navigation_goalrating_timeout_force(this);
822                                         return;
823                                 }
824                                 else if (navigation_goalrating_timeout_can_be_anticipated(this))
825                                         navigation_goalrating_timeout_force(this);
826                         }
827                         else
828                         {
829                                 entity old_goal = this.goalcurrent_prev;
830                                 if (old_goal.item_group && this.item_group != old_goal.item_group)
831                                 {
832                                         // Avoid multiple costly calls of path finding code that selects one of the closest
833                                         // item of the group by telling the bot to head directly to the farthest item.
834                                         // Next time we let the bot select a goal as usual which can be another item
835                                         // of this group (the closest one) and so on
836                                         this.item_group = old_goal.item_group;
837                                         entity new_goal = havocbot_select_an_item_of_group(this, old_goal.item_group);
838                                         if (new_goal)
839                                                 navigation_pushroute(this, new_goal);
840                                 }
841                         }
842                 }
843         }
844
845         // if ran out of goals try to use an alternative goal or get a new strategy asap
846         if(this.goalcurrent == NULL)
847         {
848                 navigation_goalrating_timeout_force(this);
849                 return;
850         }
851
852
853         if(autocvar_bot_debug_goalstack)
854                 debuggoalstack(this);
855
856         bool bunnyhop_forbidden = false;
857         vector destorg = get_closer_dest(this.goalcurrent, this.origin);
858         if (this.jumppadcount && this.goalcurrent.wpflags & WAYPOINTFLAG_TELEPORT)
859         {
860                 // if bot used the jumppad, push towards jumppad origin until jumppad waypoint gets removed
861                 destorg = this.goalcurrent.origin;
862         }
863         else if (this.goalcurrent.wpisbox)
864         {
865                 // if bot is inside the teleport waypoint, head to teleport origin until teleport gets used
866                 // do it even if bot is on a ledge above a teleport/jumppad so it doesn't get stuck
867                 if (boxesoverlap(this.goalcurrent.absmin, this.goalcurrent.absmax, this.origin + eZ * this.mins.z, this.origin + eZ * this.maxs.z)
868                         || (this.absmin.z > destorg.z && destorg.x == this.origin.x && destorg.y == this.origin.y))
869                 {
870                         bunnyhop_forbidden = true;
871                         destorg = this.goalcurrent.origin;
872                         if(destorg.z > this.origin.z)
873                                 PHYS_INPUT_BUTTON_JUMP(this) = true;
874                 }
875         }
876
877         diff = destorg - this.origin;
878
879         if (time < this.bot_stop_moving_timeout
880                 || (this.goalcurrent == this.goalentity && time < this.goalentity_lock_timeout && vdist(diff, <, 10)))
881         {
882                 // stop if the locked goal has been reached
883                 destorg = this.origin;
884                 diff = dir = '0 0 0';
885         }
886         else if (IS_PLAYER(this.goalcurrent) || IS_MONSTER(this.goalcurrent))
887         {
888                 if (vdist(diff, <, 80))
889                 {
890                         // stop if too close to target player (even if frozen)
891                         destorg = this.origin;
892                         diff = dir = '0 0 0';
893                 }
894                 else
895                 {
896                         // move destorg out of target players, otherwise bot will consider them
897                         // an obstacle that needs to be jumped (especially if frozen)
898                         dir = normalize(diff);
899                         destorg -= dir * PL_MAX_CONST.x * M_SQRT2;
900                         diff = destorg - this.origin;
901                 }
902         }
903         else
904                 dir = normalize(diff);
905         flatdir = (diff.z == 0) ? dir : normalize(vec2(diff));
906
907         //if (this.bot_dodgevector_time < time)
908         {
909                 //this.bot_dodgevector_time = time + cvar("bot_ai_dodgeupdateinterval");
910                 //this.bot_dodgevector_jumpbutton = 1;
911                 evadeobstacle = '0 0 0';
912                 evadelava = '0 0 0';
913
914                 this.aistatus &= ~AI_STATUS_DANGER_AHEAD;
915                 makevectors(this.v_angle.y * '0 1 0');
916                 if (this.waterlevel > WATERLEVEL_WETFEET)
917                 {
918                         if (this.waterlevel > WATERLEVEL_SWIMMING)
919                         {
920                                 if(!this.goalcurrent)
921                                         this.aistatus |= AI_STATUS_OUT_WATER;
922                                 else if(destorg.z > this.origin.z)
923                                         PHYS_INPUT_BUTTON_JUMP(this) = true;
924                         }
925                         else
926                         {
927                                 if(this.velocity.z >= 0 && !(this.watertype == CONTENT_WATER && destorg.z < this.origin.z) &&
928                                         (this.aistatus & AI_STATUS_OUT_WATER))
929                                 {
930                                         PHYS_INPUT_BUTTON_JUMP(this) = true;
931                                         dir = flatdir;
932                                 }
933                                 else
934                                 {
935                                         PHYS_INPUT_BUTTON_JUMP(this) = false;
936                                         if (destorg.z > this.origin.z)
937                                                 dir = flatdir;
938                                 }
939                         }
940                 }
941                 else
942                 {
943                         float s;
944                         vector offset;
945                         if(this.aistatus & AI_STATUS_OUT_WATER)
946                                 this.aistatus &= ~AI_STATUS_OUT_WATER;
947
948                         // jump if going toward an obstacle that doesn't look like stairs we
949                         // can walk up directly
950                         vector deviation = '0 0 0';
951                         float current_speed = vlen(vec2(this.velocity));
952                         if (current_speed < maxspeed * 0.2)
953                                 current_speed = maxspeed * 0.2;
954                         else
955                         {
956                                 deviation = vectoangles(diff) - vectoangles(this.velocity);
957                                 while (deviation.y < -180) deviation.y += 360;
958                                 while (deviation.y > 180) deviation.y -= 360;
959                         }
960                         float turning = false;
961                         vector flat_diff = vec2(diff);
962                         offset = max(32, current_speed * cos(deviation.y * DEG2RAD) * 0.3) * flatdir;
963                         vector actual_destorg = this.origin + offset;
964                         if (this.goalcurrent_prev && (this.goalcurrent_prev.wpflags & WAYPOINTFLAG_JUMP))
965                         {
966                                 if (time > this.bot_stop_moving_timeout
967                                         && fabs(deviation.y) > 20 && current_speed > maxspeed * 0.4
968                                         && vdist(vec2(this.origin - this.goalcurrent_prev.origin), <, 50))
969                                 {
970                                         this.bot_stop_moving_timeout = time + 0.1;
971                                 }
972                                 if (current_speed > autocvar_sv_maxspeed * 0.9
973                                         && vlen2(flat_diff) < vlen2(vec2(this.goalcurrent_prev.origin - destorg))
974                                         && vdist(vec2(this.origin - this.goalcurrent_prev.origin), >, 50)
975                                         && vdist(vec2(this.origin - this.goalcurrent_prev.origin), <, 150)
976                                 )
977                                 {
978                                         PHYS_INPUT_BUTTON_JUMP(this) = true;
979                                         // avoid changing route while bot is jumping a gap
980                                         navigation_goalrating_timeout_extend_if_needed(this, 1.5);
981                                 }
982                         }
983                         else if (!this.goalstack01 || (this.goalcurrent.wpflags & (WAYPOINTFLAG_TELEPORT | WAYPOINTFLAG_LADDER)))
984                         {
985                                 if (vlen2(flat_diff) < vlen2(offset))
986                                 {
987                                         if (this.goalcurrent.wpflags & WAYPOINTFLAG_JUMP && this.goalstack01)
988                                         {
989                                                 // oblique warpzones need a jump otherwise bots gets stuck
990                                                 PHYS_INPUT_BUTTON_JUMP(this) = true;
991                                         }
992                                         else
993                                         {
994                                                 actual_destorg.x = destorg.x;
995                                                 actual_destorg.y = destorg.y;
996                                         }
997                                 }
998                         }
999                         else if (vdist(flat_diff, <, 32) && diff.z < -16) // destination is under the bot
1000                         {
1001                                 actual_destorg.x = destorg.x;
1002                                 actual_destorg.y = destorg.y;
1003                         }
1004                         else if (vlen2(flat_diff) < vlen2(offset))
1005                         {
1006                                 vector next_goal_org = (this.goalstack01.absmin + this.goalstack01.absmax) * 0.5;
1007                                 vector next_dir = normalize(vec2(next_goal_org - destorg));
1008                                 float dist = vlen(vec2(this.origin + offset - destorg));
1009                                 // if current and next goal are close to each other make sure
1010                                 // actual_destorg isn't set beyond next_goal_org
1011                                 if (dist ** 2 > vlen2(vec2(next_goal_org - destorg)))
1012                                         actual_destorg = next_goal_org;
1013                                 else
1014                                         actual_destorg = vec2(destorg) + dist * next_dir;
1015                                 actual_destorg.z = this.origin.z;
1016                                 turning = true;
1017                         }
1018
1019                         LABEL(jumpobstacle_check);
1020                         dir = flatdir = normalize(actual_destorg - this.origin);
1021
1022                         bool jump_forbidden = false;
1023                         if (!turning && fabs(deviation.y) > 50)
1024                                 jump_forbidden = true;
1025                         else if (IS_DUCKED(this))
1026                         {
1027                                 tracebox(this.origin, PL_MIN_CONST, PL_MAX_CONST, this.origin, false, this);
1028                                 if (trace_startsolid)
1029                                         jump_forbidden = true;
1030                         }
1031
1032                         if (!jump_forbidden)
1033                         {
1034                                 tracebox(this.origin, this.mins, this.maxs, actual_destorg, false, this);
1035                                 if (trace_fraction < 1 && trace_plane_normal.z < 0.7)
1036                                 {
1037                                         s = trace_fraction;
1038                                         tracebox(this.origin + stepheightvec, this.mins, this.maxs, actual_destorg + stepheightvec, false, this);
1039                                         if (trace_fraction < s + 0.01 && trace_plane_normal.z < 0.7)
1040                                         {
1041                                                 // found an obstacle
1042                                                 if (turning && fabs(deviation.y) > 5)
1043                                                 {
1044                                                         // check if the obstacle is still there without turning
1045                                                         actual_destorg = destorg;
1046                                                         turning = false;
1047                                                         this.bot_tracewalk_time = time + 0.25;
1048                                                         goto jumpobstacle_check;
1049                                                 }
1050                                                 s = trace_fraction;
1051                                                 // don't artificially reduce max jump height in real-time
1052                                                 // (jumpstepheightvec is reduced a bit to make the jumps easy in tracewalk)
1053                                                 vector jump_height = (IS_ONGROUND(this)) ? stepheightvec + jumpheight_vec : jumpstepheightvec;
1054                                                 tracebox(this.origin + jump_height, this.mins, this.maxs, actual_destorg + jump_height, false, this);
1055                                                 if (trace_fraction > s)
1056                                                         PHYS_INPUT_BUTTON_JUMP(this) = true;
1057                                                 else
1058                                                 {
1059                                                         jump_height = stepheightvec + jumpheight_vec / 2;
1060                                                         tracebox(this.origin + jump_height, this.mins, this.maxs, actual_destorg + jump_height, false, this);
1061                                                         if (trace_fraction > s)
1062                                                                 PHYS_INPUT_BUTTON_JUMP(this) = true;
1063                                                 }
1064                                         }
1065                                 }
1066                         }
1067
1068                         // if bot for some reason doesn't get close to the current goal find another one
1069                         if(!this.jumppadcount && !IS_PLAYER(this.goalcurrent))
1070                         if(!(locked_goal && this.goalcurrent_distance_z < 50 && this.goalcurrent_distance_2d < 50))
1071                         if(havocbot_checkgoaldistance(this, destorg))
1072                         {
1073                                 if(this.goalcurrent_distance_time < 0) // can't get close for the second time
1074                                 {
1075                                         navigation_clearroute(this);
1076                                         navigation_goalrating_timeout_force(this);
1077                                         return;
1078                                 }
1079
1080                                 set_tracewalk_dest(this.goalcurrent, this.origin, false);
1081                                 if (!tracewalk(this, this.origin, this.mins, this.maxs,
1082                                         tracewalk_dest, tracewalk_dest_height, bot_navigation_movemode))
1083                                 {
1084                                         navigation_clearroute(this);
1085                                         navigation_goalrating_timeout_force(this);
1086                                         return;
1087                                 }
1088
1089                                 // give bot only another chance to prevent bot getting stuck
1090                                 // in case it thinks it can walk but actually can't
1091                                 this.goalcurrent_distance_z = FLOAT_MAX;
1092                                 this.goalcurrent_distance_2d = FLOAT_MAX;
1093                                 this.goalcurrent_distance_time = -time; // mark second try
1094                         }
1095
1096                         // Check for water/slime/lava and dangerous edges
1097                         // (only when the bot is on the ground or jumping intentionally)
1098
1099                         if (skill + this.bot_moveskill <= 3 && time > this.bot_stop_moving_timeout
1100                                 && current_speed > maxspeed * 0.9 && fabs(deviation.y) > 70)
1101                         {
1102                                 this.bot_stop_moving_timeout = time + 0.4 + random() * 0.2;
1103                         }
1104
1105                         offset = (vdist(this.velocity, >, 32) ? this.velocity * 0.2 : flatdir * 32);
1106                         vector dst_ahead = this.origin + this.view_ofs + offset;
1107                         vector dst_down = dst_ahead - '0 0 3000';
1108                         traceline(this.origin + this.view_ofs, dst_ahead, true, NULL);
1109
1110                         bool unreachable = false;
1111                         s = CONTENT_SOLID;
1112                         if (trace_fraction == 1 && !this.jumppadcount
1113                                 && !waypoint_is_hardwiredlink(this.goalcurrent_prev, this.goalcurrent)
1114                                 && !(this.goalcurrent_prev && (this.goalcurrent_prev.wpflags & WAYPOINTFLAG_JUMP)))
1115                         if((IS_ONGROUND(this)) || (this.aistatus & AI_STATUS_RUNNING) || (this.aistatus & AI_STATUS_ROAMING) || PHYS_INPUT_BUTTON_JUMP(this))
1116                         {
1117                                 // Look downwards
1118                                 traceline(dst_ahead , dst_down, true, NULL);
1119                                 //te_lightning2(NULL, this.origin + this.view_ofs, dst_ahead); // Draw "ahead" look
1120                                 //te_lightning2(NULL, dst_ahead, trace_endpos); // Draw "downwards" look
1121                                 if(trace_endpos.z < this.origin.z + this.mins.z)
1122                                 {
1123                                         s = pointcontents(trace_endpos + '0 0 1');
1124                                         if (s != CONTENT_SOLID)
1125                                         if (s == CONTENT_LAVA || s == CONTENT_SLIME)
1126                                                 evadelava = normalize(this.velocity) * -1;
1127                                         else if (s == CONTENT_SKY)
1128                                                 evadeobstacle = normalize(this.velocity) * -1;
1129                                         else if (tracebox_hits_trigger_hurt(dst_ahead, this.mins, this.maxs, trace_endpos))
1130                                         {
1131                                                 // the traceline check isn't enough but is good as optimization,
1132                                                 // when not true (most of the time) this tracebox call is avoided
1133                                                 tracebox(dst_ahead, this.mins, this.maxs, dst_down, true, this);
1134                                                 if (tracebox_hits_trigger_hurt(dst_ahead, this.mins, this.maxs, trace_endpos))
1135                                                 {
1136                                                         if (destorg.z > this.origin.z + jumpstepheightvec.z)
1137                                                         {
1138                                                                 // the goal is probably on an upper platform, assume bot can't get there
1139                                                                 unreachable = true;
1140                                                         }
1141                                                         else
1142                                                                 evadelava = normalize(this.velocity) * -1;
1143                                                 }
1144                                         }
1145                                 }
1146                         }
1147
1148                         dir = flatdir;
1149                         evadeobstacle.z = 0;
1150                         evadelava.z = 0;
1151                         makevectors(this.v_angle.y * '0 1 0');
1152
1153                         if(evadeobstacle || evadelava || (s == CONTENT_WATER))
1154                         {
1155                                 this.aistatus |= AI_STATUS_DANGER_AHEAD;
1156                                 if(IS_PLAYER(this.goalcurrent))
1157                                         unreachable = true;
1158                         }
1159
1160                         // slow down if bot is in the air and goal is under it
1161                         if (!waypoint_is_hardwiredlink(this.goalcurrent_prev, this.goalcurrent)
1162                                 && vdist(flat_diff, <, 250) && this.origin.z - destorg.z > 120
1163                                 && (!IS_ONGROUND(this) || vdist(vec2(this.velocity), >, maxspeed * 0.3)))
1164                         {
1165                                 // tracebox wouldn't work when bot is still on the ledge
1166                                 traceline(this.origin, this.origin - '0 0 200', true, this);
1167                                 if (this.origin.z - trace_endpos.z > 120)
1168                                         evadeobstacle = normalize(this.velocity) * -1;
1169                         }
1170
1171                         if(unreachable)
1172                         {
1173                                 navigation_clearroute(this);
1174                                 navigation_goalrating_timeout_force(this);
1175                                 this.ignoregoal = this.goalcurrent;
1176                                 this.ignoregoaltime = time + autocvar_bot_ai_ignoregoal_timeout;
1177                         }
1178                 }
1179
1180                 dodge = havocbot_dodge(this);
1181                 if (dodge)
1182                         dodge *= bound(0, 0.5 + (skill + this.bot_dodgeskill) * 0.1, 1);
1183                 dodge += evadeobstacle + evadelava;
1184                 evadelava = evadelava * bound(1,3-(skill+this.bot_dodgeskill),3); //Noobs fear lava a lot and take more distance from it
1185                 if (this.enemy)
1186                 {
1187                         traceline(this.origin, (this.enemy.absmin + this.enemy.absmax) * 0.5, true, NULL);
1188                         if (IS_PLAYER(trace_ent))
1189                                 dodge_enemy_factor = bound(0, (skill + this.bot_dodgeskill) / 7, 1);
1190                 }
1191         //      this.bot_dodgevector = dir;
1192         //      this.bot_dodgevector_jumpbutton = PHYS_INPUT_BUTTON_JUMP(this);
1193         }
1194
1195         float ladder_zdir = 0;
1196         if(time < this.ladder_time)
1197         {
1198                 if(this.goalcurrent.origin.z + this.goalcurrent.mins.z > this.origin.z + this.mins.z)
1199                 {
1200                         if(this.origin.z + this.mins.z  < this.ladder_entity.origin.z + this.ladder_entity.maxs.z)
1201                                 ladder_zdir = 1;
1202                 }
1203                 else
1204                 {
1205                         if(this.origin.z + this.mins.z  > this.ladder_entity.origin.z + this.ladder_entity.mins.z)
1206                                 ladder_zdir = -1;
1207                 }
1208                 if (ladder_zdir)
1209                 {
1210                         if (vdist(vec2(diff), <, 40))
1211                                 dir.z = ladder_zdir * 4;
1212                         else
1213                                 dir.z = ladder_zdir * 2;
1214                         dir = normalize(dir);
1215                 }
1216         }
1217
1218         if (this.goalcurrent.wpisbox
1219                 && boxesoverlap(this.goalcurrent.absmin, this.goalcurrent.absmax, this.origin, this.origin))
1220         {
1221                 // bot is inside teleport waypoint but hasn't touched the real teleport yet
1222                 // head to teleport origin
1223                 dir = (this.goalcurrent.origin - this.origin);
1224                 dir.z = 0;
1225                 dir = normalize(dir);
1226         }
1227
1228         // already executed when bot targets an enemy
1229         if (!this.bot_aimdir_executed)
1230         {
1231                 if (time < this.bot_stop_moving_timeout)
1232                         bot_aimdir(this, normalize(this.goalcurrent.origin - this.origin), 0);
1233                 else
1234                         bot_aimdir(this, dir, 0);
1235         }
1236
1237         if (!ladder_zdir)
1238         {
1239                 dir *= dodge_enemy_factor;
1240                 dir = normalize(dir + dodge);
1241         }
1242
1243         makevectors(this.v_angle);
1244         //dir = this.bot_dodgevector;
1245         //if (this.bot_dodgevector_jumpbutton)
1246         //      PHYS_INPUT_BUTTON_JUMP(this) = true;
1247         CS(this).movement_x = dir * v_forward * maxspeed;
1248         CS(this).movement_y = dir * v_right * maxspeed;
1249         CS(this).movement_z = dir * v_up * maxspeed;
1250
1251         // Emulate keyboard interface
1252         if (skill < 10)
1253                 havocbot_keyboard_movement(this, destorg);
1254
1255         // Bunnyhop!
1256         //if(this.aistatus & AI_STATUS_ROAMING)
1257         if(!bunnyhop_forbidden && this.goalcurrent)
1258         if(skill+this.bot_moveskill >= autocvar_bot_ai_bunnyhop_skilloffset)
1259                 havocbot_bunnyhop(this, dir);
1260
1261         if (dir * v_up >= autocvar_sv_jumpvelocity * 0.5 && IS_ONGROUND(this))
1262                 PHYS_INPUT_BUTTON_JUMP(this) = true;
1263         if (dodge)
1264         {
1265                 if (dodge * v_up > 0 && random() * frametime >= 0.2 * bound(0, (10 - skill - this.bot_dodgeskill) * 0.1, 1))
1266                         PHYS_INPUT_BUTTON_JUMP(this) = true;
1267                 if (dodge * v_up < 0 && random() * frametime >= 0.5 * bound(0, (10 - skill - this.bot_dodgeskill) * 0.1, 1))
1268                         this.havocbot_ducktime = time + 0.3 / bound(0.1, skill + this.bot_dodgeskill, 10);
1269         }
1270 }
1271
1272 entity havocbot_gettarget(entity this, bool secondary)
1273 {
1274         entity best = NULL;
1275         vector eye = CENTER_OR_VIEWOFS(this);
1276         IL_EACH(g_bot_targets, boolean((secondary) ? it.classname == "misc_breakablemodel" : it.classname != "misc_breakablemodel"),
1277         {
1278                 vector v = CENTER_OR_VIEWOFS(it);
1279                 if(vdist(v - eye, <, autocvar_bot_ai_enemydetectionradius))
1280                 if(!best || vlen2(CENTER_OR_VIEWOFS(best) - eye) > vlen2(v - eye))
1281                 if(bot_shouldattack(this, it))
1282                 {
1283                         traceline(eye, v, true, this);
1284                         if (trace_ent == it || trace_fraction >= 1)
1285                                 best = it;
1286                 }
1287         });
1288
1289         return best;
1290 }
1291
1292 void havocbot_chooseenemy(entity this)
1293 {
1294         if (autocvar_bot_nofire || IS_INDEPENDENT_PLAYER(this))
1295         {
1296                 this.enemy = NULL;
1297                 return;
1298         }
1299         if (this.enemy)
1300         {
1301                 if (!bot_shouldattack(this, this.enemy))
1302                 {
1303                         // enemy died or something, find a new target
1304                         this.enemy = NULL;
1305                         this.havocbot_chooseenemy_finished = time;
1306                 }
1307                 else if (this.havocbot_stickenemy)
1308                 {
1309                         // tracking last chosen enemy
1310                         // if enemy is visible
1311                         // and not really really far away
1312                         // and we're not severely injured
1313                         // then keep tracking for a half second into the future
1314                         traceline(this.origin+this.view_ofs, ( this.enemy.absmin + this.enemy.absmax ) * 0.5,false,NULL);
1315                         if (trace_ent == this.enemy || trace_fraction == 1)
1316                         if (vdist(((this.enemy.absmin + this.enemy.absmax) * 0.5) - this.origin, <, 1000))
1317                         if (GetResource(this, RES_HEALTH) > 30)
1318                         {
1319                                 // remain tracking him for a shot while (case he went after a small corner or pilar
1320                                 this.havocbot_chooseenemy_finished = time + 0.5;
1321                                 return;
1322                         }
1323                         // enemy isn't visible, or is far away, or we're injured severely
1324                         // so stop preferring this enemy
1325                         // (it will still take a half second until a new one is chosen)
1326                         this.havocbot_stickenemy = 0;
1327                 }
1328         }
1329         if (time < this.havocbot_chooseenemy_finished)
1330                 return;
1331         this.havocbot_chooseenemy_finished = time + autocvar_bot_ai_enemydetectioninterval;
1332         vector eye = this.origin + this.view_ofs;
1333         entity best = NULL;
1334         float bestrating = 100000000;
1335
1336         // Backup hit flags
1337         int hf = this.dphitcontentsmask;
1338
1339         // Search for enemies, if no enemy can be seen directly try to look through transparent objects
1340
1341         this.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_CORPSE;
1342
1343         bool scan_transparent = false;
1344         bool scan_secondary_targets = false;
1345         bool have_secondary_targets = false;
1346         while(true)
1347         {
1348                 scan_secondary_targets = false;
1349 LABEL(scan_targets)
1350                 IL_EACH(g_bot_targets, it.bot_attack,
1351                 {
1352                         if(!scan_secondary_targets)
1353                         {
1354                                 if(it.classname == "misc_breakablemodel")
1355                                 {
1356                                         have_secondary_targets = true;
1357                                         continue;
1358                                 }
1359                         }
1360                         else if(it.classname != "misc_breakablemodel")
1361                                 continue;
1362
1363                         vector v = (it.absmin + it.absmax) * 0.5;
1364                         float rating = vlen2(v - eye);
1365                         if (vdist(v - eye, <, autocvar_bot_ai_enemydetectionradius))
1366                         if (bestrating > rating)
1367                         if (bot_shouldattack(this, it))
1368                         {
1369                                 traceline(eye, v, true, this);
1370                                 if (trace_ent == it || trace_fraction >= 1)
1371                                 {
1372                                         best = it;
1373                                         bestrating = rating;
1374                                 }
1375                         }
1376                 });
1377
1378                 if(!best && have_secondary_targets && !scan_secondary_targets)
1379                 {
1380                         scan_secondary_targets = true;
1381                         // restart the loop
1382                         bestrating = 100000000;
1383                         goto scan_targets;
1384                 }
1385
1386                 // I want to do a second scan if no enemy was found or I don't have weapons
1387                 // TODO: Perform the scan when using the rifle (requires changes on the rifle code)
1388                 if(best || STAT(WEAPONS, this)) // || this.weapon == WEP_RIFLE.m_id
1389                         break;
1390                 if(scan_transparent)
1391                         break;
1392
1393                 // Set flags to see through transparent objects
1394                 this.dphitcontentsmask |= DPCONTENTS_OPAQUE;
1395
1396                 scan_transparent = true;
1397         }
1398
1399         // Restore hit flags
1400         this.dphitcontentsmask = hf;
1401
1402         this.enemy = best;
1403         this.havocbot_stickenemy = true;
1404         if(best && best.classname == "misc_breakablemodel")
1405                 this.havocbot_stickenemy = false;
1406 }
1407
1408 float havocbot_chooseweapon_checkreload(entity this, .entity weaponentity, int new_weapon)
1409 {
1410         // bots under this skill cannot find unloaded weapons to reload idly when not in combat,
1411         // so skip this for them, or they'll never get to reload their weapons at all.
1412         // this also allows bots under this skill to be more stupid, and reload more often during combat :)
1413         if(skill < 5)
1414                 return false;
1415
1416         // if this weapon is scheduled for reloading, don't switch to it during combat
1417         if (this.(weaponentity).weapon_load[new_weapon] < 0)
1418         {
1419                 FOREACH(Weapons, it != WEP_Null, {
1420                         if(it.wr_checkammo1(it, this, weaponentity) + it.wr_checkammo2(it, this, weaponentity))
1421                                 return true; // other weapon available
1422                 });
1423         }
1424
1425         return false;
1426 }
1427
1428 void havocbot_chooseweapon(entity this, .entity weaponentity)
1429 {
1430         int i;
1431
1432         // ;)
1433         if(g_weaponarena_weapons == WEPSET(TUBA))
1434         {
1435                 this.(weaponentity).m_switchweapon = WEP_TUBA;
1436                 return;
1437         }
1438
1439         // TODO: clean this up by moving it to weapon code
1440         if(this.enemy==NULL)
1441         {
1442                 // If no weapon was chosen get the first available weapon
1443                 if(this.(weaponentity).m_weapon==WEP_Null)
1444                 FOREACH(Weapons, it != WEP_Null, {
1445                         if(client_hasweapon(this, it, weaponentity, true, false))
1446                         {
1447                                 this.(weaponentity).m_switchweapon = it;
1448                                 return;
1449                         }
1450                 });
1451                 return;
1452         }
1453
1454         // Do not change weapon during the next second after a combo
1455         float f = time - this.lastcombotime;
1456         if(f < 1)
1457                 return;
1458
1459         float w;
1460         float distance; distance=bound(10,vlen(this.origin-this.enemy.origin)-200,10000);
1461
1462         // Should it do a weapon combo?
1463         float af, ct, combo_time, combo;
1464
1465         af = ATTACK_FINISHED(this, weaponentity);
1466         ct = autocvar_bot_ai_weapon_combo_threshold;
1467
1468         // Bots with no skill will be 4 times more slower than "godlike" bots when doing weapon combos
1469         // Ideally this 4 should be calculated as longest_weapon_refire / bot_ai_weapon_combo_threshold
1470         combo_time = time + ct + (ct * ((-0.3*(skill+this.bot_weaponskill))+3));
1471
1472         combo = false;
1473
1474         if(autocvar_bot_ai_weapon_combo)
1475         if(this.(weaponentity).m_weapon.m_id == this.(weaponentity).lastfiredweapon)
1476         if(af > combo_time)
1477         {
1478                 combo = true;
1479                 this.lastcombotime = time;
1480         }
1481
1482         distance *= (2 ** this.bot_rangepreference);
1483
1484         // Custom weapon list based on distance to the enemy
1485         if(bot_custom_weapon){
1486
1487                 // Choose weapons for far distance
1488                 if ( distance > bot_distance_far ) {
1489                         for(i=0; i < Weapons_COUNT && bot_weapons_far[i] != -1 ; ++i){
1490                                 w = bot_weapons_far[i];
1491                                 if ( client_hasweapon(this, Weapons_from(w), weaponentity, true, false) )
1492                                 {
1493                                         if ((this.(weaponentity).m_weapon.m_id == w && combo) || havocbot_chooseweapon_checkreload(this, weaponentity, w))
1494                                                 continue;
1495                                         this.(weaponentity).m_switchweapon = Weapons_from(w);
1496                                         return;
1497                                 }
1498                         }
1499                 }
1500
1501                 // Choose weapons for mid distance
1502                 if ( distance > bot_distance_close) {
1503                         for(i=0; i < Weapons_COUNT && bot_weapons_mid[i] != -1 ; ++i){
1504                                 w = bot_weapons_mid[i];
1505                                 if ( client_hasweapon(this, Weapons_from(w), weaponentity, true, false) )
1506                                 {
1507                                         if ((this.(weaponentity).m_weapon.m_id == w && combo) || havocbot_chooseweapon_checkreload(this, weaponentity, w))
1508                                                 continue;
1509                                         this.(weaponentity).m_switchweapon = Weapons_from(w);
1510                                         return;
1511                                 }
1512                         }
1513                 }
1514
1515                 // Choose weapons for close distance
1516                 for(i=0; i < Weapons_COUNT && bot_weapons_close[i] != -1 ; ++i){
1517                         w = bot_weapons_close[i];
1518                         if ( client_hasweapon(this, Weapons_from(w), weaponentity, true, false) )
1519                         {
1520                                 if ((this.(weaponentity).m_weapon.m_id == w && combo) || havocbot_chooseweapon_checkreload(this, weaponentity, w))
1521                                         continue;
1522                                 this.(weaponentity).m_switchweapon = Weapons_from(w);
1523                                 return;
1524                         }
1525                 }
1526         }
1527 }
1528
1529 void havocbot_aim(entity this)
1530 {
1531         if (time < this.nextaim)
1532                 return;
1533         this.nextaim = time + 0.1;
1534         vector myvel = this.velocity;
1535         if (!this.waterlevel)
1536                 myvel.z = 0;
1537         if(MUTATOR_CALLHOOK(HavocBot_Aim, this)) { /* do nothing */ }
1538         else if (this.enemy)
1539         {
1540                 vector enemyvel = this.enemy.velocity;
1541                 if (!this.enemy.waterlevel)
1542                         enemyvel.z = 0;
1543                 lag_additem(this, time + CS(this).ping, 0, 0, this.enemy, this.origin, myvel, (this.enemy.absmin + this.enemy.absmax) * 0.5, enemyvel);
1544         }
1545         else
1546                 lag_additem(this, time + CS(this).ping, 0, 0, NULL, this.origin, myvel, ( this.goalcurrent.absmin + this.goalcurrent.absmax ) * 0.5, '0 0 0');
1547 }
1548
1549 bool havocbot_moveto_refresh_route(entity this)
1550 {
1551         // Refresh path to goal if necessary
1552         entity wp;
1553         wp = this.havocbot_personal_waypoint;
1554         navigation_goalrating_start(this);
1555         navigation_routerating(this, wp, 10000, 10000);
1556         navigation_goalrating_end(this);
1557         return (this.goalentity != NULL);
1558 }
1559
1560 float havocbot_moveto(entity this, vector pos)
1561 {
1562         entity wp;
1563
1564         if(this.aistatus & AI_STATUS_WAYPOINT_PERSONAL_GOING)
1565         {
1566                 // Step 4: Move to waypoint
1567                 if(this.havocbot_personal_waypoint==NULL)
1568                 {
1569                         LOG_TRACE("Error: ", this.netname, " trying to walk to a non existent personal waypoint");
1570                         this.aistatus &= ~AI_STATUS_WAYPOINT_PERSONAL_GOING;
1571                         return CMD_STATUS_ERROR;
1572                 }
1573
1574                 if (!bot_strategytoken_taken)
1575                 if(this.havocbot_personal_waypoint_searchtime<time)
1576                 {
1577                         bot_strategytoken_taken = true;
1578                         if(havocbot_moveto_refresh_route(this))
1579                         {
1580                                 LOG_TRACE(this.netname, " walking to its personal waypoint (after ", ftos(this.havocbot_personal_waypoint_failcounter), " failed attempts)");
1581                                 this.havocbot_personal_waypoint_searchtime = time + 10;
1582                                 this.havocbot_personal_waypoint_failcounter = 0;
1583                         }
1584                         else
1585                         {
1586                                 this.havocbot_personal_waypoint_failcounter += 1;
1587                                 this.havocbot_personal_waypoint_searchtime = time + 2;
1588                                 if(this.havocbot_personal_waypoint_failcounter >= 30)
1589                                 {
1590                                         LOG_TRACE("Warning: can't walk to the personal waypoint located at ", vtos(this.havocbot_personal_waypoint.origin));
1591                                         this.aistatus &= ~AI_STATUS_WAYPOINT_PERSONAL_LINKING;
1592                                         delete(this.havocbot_personal_waypoint);
1593                                         return CMD_STATUS_ERROR;
1594                                 }
1595                                 else
1596                                         LOG_TRACE(this.netname, " can't walk to its personal waypoint (after ", ftos(this.havocbot_personal_waypoint_failcounter), " failed attempts), trying later");
1597                         }
1598                 }
1599
1600                 if(autocvar_bot_debug_goalstack)
1601                         debuggoalstack(this);
1602
1603
1604                 // Go!
1605                 havocbot_movetogoal(this);
1606
1607                 if (!this.bot_aimdir_executed && this.goalcurrent)
1608                 {
1609                         // Heading
1610                         vector dir = get_closer_dest(this.goalcurrent, this.origin);
1611                         dir -= this.origin + this.view_ofs;
1612                         dir.z = 0;
1613                         bot_aimdir(this, dir, 0);
1614                 }
1615
1616                 if(this.aistatus & AI_STATUS_WAYPOINT_PERSONAL_REACHED)
1617                 {
1618                         // Step 5: Waypoint reached
1619                         LOG_TRACE(this.netname, "'s personal waypoint reached");
1620                         waypoint_remove(this.havocbot_personal_waypoint);
1621                         this.aistatus &= ~AI_STATUS_WAYPOINT_PERSONAL_REACHED;
1622                         return CMD_STATUS_FINISHED;
1623                 }
1624
1625                 return CMD_STATUS_EXECUTING;
1626         }
1627
1628         // Step 2: Linking waypoint
1629         if(this.aistatus & AI_STATUS_WAYPOINT_PERSONAL_LINKING)
1630         {
1631                 // Wait until it is linked
1632                 if(!this.havocbot_personal_waypoint.wplinked)
1633                 {
1634                         LOG_TRACE(this.netname, " waiting for personal waypoint to be linked");
1635                         return CMD_STATUS_EXECUTING;
1636                 }
1637
1638                 this.havocbot_personal_waypoint_searchtime = time; // so we set the route next frame
1639                 this.aistatus &= ~AI_STATUS_WAYPOINT_PERSONAL_LINKING;
1640                 this.aistatus |= AI_STATUS_WAYPOINT_PERSONAL_GOING;
1641
1642                 // Step 3: Route to waypoint
1643                 LOG_TRACE(this.netname, " walking to its personal waypoint");
1644
1645                 return CMD_STATUS_EXECUTING;
1646         }
1647
1648         // Step 1: Spawning waypoint
1649         wp = waypoint_spawnpersonal(this, pos);
1650         if(wp==NULL)
1651         {
1652                 LOG_TRACE("Error: Can't spawn personal waypoint at ",vtos(pos));
1653                 return CMD_STATUS_ERROR;
1654         }
1655
1656         this.havocbot_personal_waypoint = wp;
1657         this.havocbot_personal_waypoint_failcounter = 0;
1658         this.aistatus |= AI_STATUS_WAYPOINT_PERSONAL_LINKING;
1659
1660         // if pos is inside a teleport, then let's mark it as teleport waypoint
1661         IL_EACH(g_teleporters, WarpZoneLib_BoxTouchesBrush(pos, pos, it, NULL),
1662         {
1663                 wp.wpflags |= WAYPOINTFLAG_TELEPORT;
1664                 this.lastteleporttime = 0;
1665         });
1666
1667 /*
1668         if(wp.wpflags & WAYPOINTFLAG_TELEPORT)
1669                 print("routing to a teleporter\n");
1670         else
1671                 print("routing to a non-teleporter\n");
1672 */
1673
1674         return CMD_STATUS_EXECUTING;
1675 }
1676
1677 float havocbot_resetgoal(entity this)
1678 {
1679         navigation_clearroute(this);
1680         return CMD_STATUS_FINISHED;
1681 }
1682
1683 void havocbot_setupbot(entity this)
1684 {
1685         this.bot_ai = havocbot_ai;
1686         this.cmd_moveto = havocbot_moveto;
1687         this.cmd_resetgoal = havocbot_resetgoal;
1688
1689         // NOTE: bot is not player yet
1690         havocbot_chooserole(this);
1691 }
1692
1693 vector havocbot_dodge(entity this)
1694 {
1695         // LordHavoc: disabled because this is too expensive
1696         return '0 0 0';
1697 #if 0
1698         entity head;
1699         vector dodge, v, n;
1700         float danger, bestdanger, vl, d;
1701         dodge = '0 0 0';
1702         bestdanger = -20;
1703         // check for dangerous objects near bot or approaching bot
1704         head = findchainfloat(bot_dodge, true);
1705         while(head)
1706         {
1707                 if (head.owner != this)
1708                 {
1709                         vl = vlen(head.velocity);
1710                         if (vl > autocvar_sv_maxspeed * 0.3)
1711                         {
1712                                 n = normalize(head.velocity);
1713                                 v = this.origin - head.origin;
1714                                 d = v * n;
1715                                 if (d > (0 - head.bot_dodgerating))
1716                                 if (d < (vl * 0.2 + head.bot_dodgerating))
1717                                 {
1718                                         // calculate direction and distance from the flight path, by removing the forward axis
1719                                         v = v - (n * (v * n));
1720                                         danger = head.bot_dodgerating - vlen(v);
1721                                         if (bestdanger < danger)
1722                                         {
1723                                                 bestdanger = danger;
1724                                                 // dodge to the side of the object
1725                                                 dodge = normalize(v);
1726                                         }
1727                                 }
1728                         }
1729                         else
1730                         {
1731                                 danger = head.bot_dodgerating - vlen(head.origin - this.origin);
1732                                 if (bestdanger < danger)
1733                                 {
1734                                         bestdanger = danger;
1735                                         dodge = normalize(this.origin - head.origin);
1736                                 }
1737                         }
1738                 }
1739                 head = head.chain;
1740         }
1741         return dodge;
1742 #endif
1743 }