]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/bot/default/bot.qc
Add a new bot skill level for extremely tough bots
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / bot / default / bot.qc
1 #include "bot.qh"
2
3 #include <common/constants.qh>
4 #include <common/mapinfo.qh>
5 #include <common/net_linked.qh>
6 #include <common/physics/player.qh>
7 #include <common/stats.qh>
8 #include <common/teams.qh>
9 #include <common/util.qh>
10 #include <common/weapons/_all.qh>
11 #include <lib/csqcmodel/sv_model.qh>
12 #include <lib/warpzone/common.qh>
13 #include <lib/warpzone/util_server.qh>
14 #include <server/antilag.qh>
15 #include <server/bot/default/aim.qh>
16 #include <server/bot/default/cvars.qh>
17 #include <server/bot/default/havocbot/havocbot.qh>
18 #include <server/bot/default/havocbot/scripting.qh>
19 #include <server/bot/default/navigation.qh>
20 #include <server/bot/default/scripting.qh>
21 #include <server/bot/default/waypoints.qh>
22 #include <server/campaign.qh>
23 #include <server/client.qh>
24 #include <server/damage.qh>
25 #include <server/items/items.qh>
26 #include <server/mutators/_mod.qh>
27 #include <server/race.qh>
28 #include <server/scores_rules.qh>
29 #include <server/teamplay.qh>
30 #include <server/weapons/accuracy.qh>
31 #include <server/weapons/selection.qh>
32 #include <server/world.qh>
33 #include <server/command/vote.qh>
34
35 STATIC_INIT(bot) { bot_calculate_stepheightvec(); }
36
37 // TODO: remove this function! its only purpose is to update these fields since bot_setnameandstuff is called before ClientState
38 void bot_setclientfields(entity this)
39 {
40         CS_CVAR(this).cvar_cl_accuracy_data_share = 1;  // share the bots weapon accuracy data with the world
41         CS_CVAR(this).cvar_cl_accuracy_data_receive = 0;  // don't receive any weapon accuracy data
42 }
43
44 entity bot_spawn()
45 {
46         entity bot = spawnclient();
47         if (bot)
48         {
49                 setItemGroupCount();
50                 currentbots = currentbots + 1;
51                 bot_setnameandstuff(bot);
52                 ClientConnect(bot);
53                 bot_setclientfields(bot);
54                 PutClientInServer(bot);
55         }
56         return bot;
57 }
58
59 void bot_think(entity this)
60 {
61         if (this.bot_nextthink > time)
62                 return;
63
64         this.flags &= ~FL_GODMODE;
65         if(autocvar_bot_god)
66                 this.flags |= FL_GODMODE;
67
68         // if bot skill is high enough don't limit their think frequency
69         if (SUPERBOT)
70                 this.bot_nextthink = max(time, this.bot_nextthink) + 0.005;
71         else
72                 this.bot_nextthink = max(time, this.bot_nextthink) + max(0.01, autocvar_bot_ai_thinkinterval * min(14 / (skill + this.bot_aiskill + 14), 1));
73
74         if (!IS_PLAYER(this) || (autocvar_g_campaign && !campaign_bots_may_start))
75         {
76                 if (IS_PLAYER(this))
77                 {
78                         .entity weaponentity = weaponentities[0];
79                         if(this.(weaponentity).m_weapon == WEP_Null)
80                                 W_NextWeapon(this, 0, weaponentity);
81                 }
82                 CS(this).movement = '0 0 0';
83                 this.bot_nextthink = time + 0.5;
84                 return;
85         }
86
87         if (this.fixangle)
88         {
89                 this.v_angle = this.angles;
90                 this.v_angle_z = 0;
91                 this.fixangle = false;
92         }
93
94         this.dmg_take = 0;
95         this.dmg_save = 0;
96         this.dmg_inflictor = NULL;
97
98         // if bot skill is high enough don't assign latency to them
99         if (SUPERBOT)
100                 CS(this).ping = 0;
101         else
102         {
103                 // calculate an aiming latency based on the skill setting
104                 // (simulated network latency + naturally delayed reflexes)
105                 //this.ping = 0.7 - bound(0, 0.05 * skill, 0.5); // moved the reflexes to bot_aimdir (under the name 'think')
106                 // minimum ping 20+10 random
107                 CS(this).ping = bound(0,0.07 - bound(0, (skill + this.bot_pingskill) * 0.005,0.05)+random()*0.01,0.65); // Now holds real lag to server, and higher skill players take a less laggy server
108                 // skill 10 = ping 0.2 (adrenaline)
109                 // skill 0 = ping 0.7 (slightly drunk)
110         }
111
112         // clear buttons
113         PHYS_INPUT_BUTTON_ATCK(this) = false;
114         // keep jump button pressed for a short while, useful with ramp jumps
115         PHYS_INPUT_BUTTON_JUMP(this) = (!IS_DEAD(this) && time < this.bot_jump_time + 0.2);
116         PHYS_INPUT_BUTTON_ATCK2(this) = false;
117         PHYS_INPUT_BUTTON_ZOOM(this) = false;
118         PHYS_INPUT_BUTTON_CROUCH(this) = false;
119         PHYS_INPUT_BUTTON_HOOK(this) = false;
120         PHYS_INPUT_BUTTON_INFO(this) = false;
121         PHYS_INPUT_BUTTON_DRAG(this) = false;
122         PHYS_INPUT_BUTTON_CHAT(this) = false;
123         PHYS_INPUT_BUTTON_USE(this) = false;
124
125         if (time < game_starttime)
126         {
127                 .entity weaponentity = weaponentities[0];
128                 if(this.(weaponentity).m_weapon == WEP_Null)
129                         W_NextWeapon(this, 0, weaponentity);
130                 // block the bot during the countdown to game start
131                 CS(this).movement = '0 0 0';
132                 return;
133         }
134
135         // if dead, just wait until we can respawn
136         if (IS_DEAD(this) || IS_OBSERVER(this))
137         {
138                 if (bot_waypoint_queue_owner == this)
139                         bot_waypoint_queue_owner = NULL;
140                 this.aistatus = 0;
141                 CS(this).movement = '0 0 0';
142                 if (IS_OBSERVER(this))
143                         return;
144                 if (IS_DEAD(this))
145                 {
146                         if (!navigation_goalrating_timeout(this))
147                                 navigation_goalrating_timeout_force(this);
148                         // jump must not be pressed for at least one frame in order for
149                         // PlayerThink to detect the key down event
150                         if (this.deadflag == DEAD_DYING)
151                                 PHYS_INPUT_BUTTON_JUMP(this) = false;
152                         else if (this.deadflag == DEAD_DEAD)
153                                 PHYS_INPUT_BUTTON_JUMP(this) = true; // press jump to respawn
154                 }
155         }
156         else if(this.aistatus & AI_STATUS_STUCK)
157                 navigation_unstuck(this);
158
159         if (warmup_stage && !this.ready)
160         {
161                 this.ready = true;
162                 ReadyCount(); // this must be delayed until the bot has spawned
163         }
164
165         // now call the current bot AI (havocbot for example)
166         this.bot_ai(this);
167 }
168
169 void bot_setnameandstuff(entity this)
170 {
171         string readfile, s;
172         int file, tokens, prio;
173
174         file = fopen(autocvar_bot_config_file, FILE_READ);
175
176         if(file < 0)
177         {
178                 LOG_INFOF("Error: Can not open the bot configuration file '%s'", autocvar_bot_config_file);
179                 readfile = "";
180         }
181         else
182         {
183                 entity balance = TeamBalance_CheckAllowedTeams(NULL);
184                 TeamBalance_GetTeamCounts(balance, NULL);
185                 int smallest_team = -1;
186                 int smallest_count = -1;
187                 if (teamplay)
188                 {
189                         for (int i = 1; i <= AVAILABLE_TEAMS; ++i)
190                         {
191                                 // NOTE if (autocvar_g_campaign && autocvar_g_campaign_forceteam == i)
192                                 // TeamBalance_GetNumberOfPlayers(balance, i); returns the number of players + 1
193                                 // since it keeps a spot for the real player in the desired team
194                                 int count = TeamBalance_GetNumberOfPlayers(balance, i);
195                                 if (smallest_count < 0 || count < smallest_count)
196                                 {
197                                         smallest_team = i;
198                                         smallest_count = count;
199                                 }
200                         }
201                 }
202                 TeamBalance_Destroy(balance);
203                 RandomSelection_Init();
204                 while((readfile = fgets(file)))
205                 {
206                         if(substring(readfile, 0, 2) == "//")
207                                 continue;
208                         if(substring(readfile, 0, 1) == "#")
209                                 continue;
210                         // NOTE if the line is empty tokenizebyseparator(readfile, "\t")
211                         // will create 1 empty token because there's no separator (bug?)
212                         if (readfile == "")
213                                 continue;
214                         tokens = tokenizebyseparator(readfile, "\t");
215                         if(tokens == 0)
216                                 continue;
217                         s = argv(0);
218                         prio = 0;
219                         bool conflict = false;
220                         FOREACH_CLIENT(IS_BOT_CLIENT(it), {
221                                 if (s == it.cleanname)
222                                 {
223                                         conflict = true;
224                                         break;
225                                 }
226                         });
227                         if (!conflict)
228                                 prio += 1;
229                         if (teamplay && !(autocvar_bot_vs_human && AVAILABLE_TEAMS == 2))
230                         {
231                                 int forced_team = stof(argv(5));
232                                 if (!Team_IsValidIndex(forced_team))
233                                         forced_team = 0;
234                                 if (!forced_team || forced_team == smallest_team)
235                                         prio += 2;
236                         }
237                         RandomSelection_AddString(readfile, 1, prio);
238                 }
239                 readfile = RandomSelection_chosen_string;
240                 fclose(file);
241         }
242
243         string bot_name, bot_model, bot_skin, bot_shirt, bot_pants;
244
245         tokens = tokenizebyseparator(readfile, "\t");
246         if(argv(0) != "") bot_name = argv(0);
247         else bot_name = "Bot";
248
249         if(argv(1) != "") bot_model = argv(1);
250         else bot_model = "";
251
252         if(argv(2) != "") bot_skin = argv(2);
253         else bot_skin = "0";
254
255         if(argv(3) != "" && stof(argv(3)) >= 0) bot_shirt = argv(3);
256         else bot_shirt = ftos(floor(random() * 15));
257
258         if(argv(4) != "" && stof(argv(4)) >= 0) bot_pants = argv(4);
259         else bot_pants = ftos(floor(random() * 15));
260
261         if (teamplay && !(autocvar_bot_vs_human && AVAILABLE_TEAMS == 2))
262         {
263                 this.bot_forced_team = stof(argv(5));
264                 if (!Team_IsValidIndex(this.bot_forced_team))
265                         this.bot_forced_team = 0;
266         }
267         else
268                 this.bot_forced_team = 0;
269
270         prio = 6;
271
272         #define READSKILL(f, w, r) MACRO_BEGIN \
273                 if(argv(prio) != "") \
274                         this.f = stof(argv(prio)) * w; \
275                 else \
276                         this.f = (!autocvar_g_campaign) * (2 * random() - 1) * r * w; \
277                 prio++; \
278         MACRO_END
279         //print(bot_name, ": ping=", argv(9), "\n");
280
281         READSKILL(havocbot_keyboardskill, 0.5, 0.5); // keyboard skill
282         READSKILL(bot_moveskill, 2, 0); // move skill
283         READSKILL(bot_dodgeskill, 2, 0); // dodge skill
284
285         READSKILL(bot_pingskill, 0.5, 0); // ping skill
286
287         READSKILL(bot_weaponskill, 2, 0); // weapon skill
288         READSKILL(bot_aggresskill, 1, 0); // aggre skill
289         READSKILL(bot_rangepreference, 1, 0); // read skill
290
291         READSKILL(bot_aimskill, 2, 0); // aim skill
292         READSKILL(bot_offsetskill, 2, 0.5); // offset skill
293         READSKILL(bot_mouseskill, 1, 0.5); // mouse skill
294
295         READSKILL(bot_thinkskill, 1, 0.5); // think skill
296         READSKILL(bot_aiskill, 2, 0); // "ai" skill
297
298         // if bot skill is high enough don't limit their skill
299         if (SUPERBOT)
300         {
301                 // commented out means they're meaningless with this high skill
302                 // no reason to set them, uncomment if this changes
303                 //this.havocbot_keyboardskill = 10;
304                 //this.bot_moveskill = 10; //midair modifier sets this to 0 to disable bhop
305                 //this.bot_dodgeskill = 10;
306                 //this.bot_pingskill = 10;
307                 //this.bot_weaponskill = 10;
308                 //this.bot_aggresskill = 10;
309                 this.bot_rangepreference = 1; // no range preference modification
310                 //this.bot_aimskill = 10;
311                 //this.bot_offsetskill = 10;
312                 //this.bot_mouseskill = 10;
313                 //this.bot_thinkskill = 10;
314                 //this.bot_aiskill = 10;
315         }
316         if (file >= 0 && argv(prio) != "")
317                 LOG_INFOF("^1Warning^7: too many parameters for bot %s, please check format of %s", bot_name, autocvar_bot_config_file);
318
319         this.bot_config_loaded = true;
320
321         // this is really only a default, TeamBalance_JoinBestTeam is called later
322         setcolor(this, stof(bot_shirt) * 16 + stof(bot_pants));
323         this.bot_preferredcolors = this.clientcolors;
324
325         string prefix = (autocvar_g_campaign ? "" : autocvar_bot_prefix);
326         string suffix = (autocvar_g_campaign ? "" : autocvar_bot_suffix);
327         string name = (autocvar_bot_usemodelnames ? bot_model : bot_name);
328
329         if (name == "")
330         {
331                 name = ftos(etof(this));
332                 this.netname = this.netname_freeme = strzone(strcat(prefix, name, suffix));
333         }
334         else
335         {
336                 // number bots with identical names
337                 int j = 0;
338                 FOREACH_CLIENT(IS_BOT_CLIENT(it), {
339                         if(it.cleanname == name)
340                                 ++j;
341                 });
342                 if (j)
343                         this.netname = this.netname_freeme = strzone(strcat(prefix, name, "(", ftos(j), ")", suffix));
344                 else
345                         this.netname = this.netname_freeme = strzone(strcat(prefix, name, suffix));
346         }
347         this.cleanname = strzone(name);
348
349         // pick the model and skin
350         if(substring(bot_model, -4, 1) != ".")
351                 bot_model = strcat(bot_model, ".iqm");
352         this.playermodel = this.playermodel_freeme = strzone(strcat("models/player/", bot_model));
353         this.playerskin = this.playerskin_freeme = strzone(bot_skin);
354 }
355
356 void bot_custom_weapon_priority_setup()
357 {
358         static string bot_priority_far_prev;
359         static string bot_priority_mid_prev;
360         static string bot_priority_close_prev;
361         static string bot_priority_distances_prev;
362         float tokens, i, w;
363
364         bot_custom_weapon = false;
365
366         if(     autocvar_bot_ai_custom_weapon_priority_far == "" ||
367                 autocvar_bot_ai_custom_weapon_priority_mid == "" ||
368                 autocvar_bot_ai_custom_weapon_priority_close == "" ||
369                 autocvar_bot_ai_custom_weapon_priority_distances == ""
370         )
371                 return;
372
373         if (bot_priority_distances_prev != autocvar_bot_ai_custom_weapon_priority_distances)
374         {
375                 strcpy(bot_priority_distances_prev, autocvar_bot_ai_custom_weapon_priority_distances);
376                 tokens = tokenizebyseparator(autocvar_bot_ai_custom_weapon_priority_distances," ");
377
378                 if (tokens!=2)
379                         return;
380
381                 bot_distance_far = stof(argv(0));
382                 bot_distance_close = stof(argv(1));
383
384                 if(bot_distance_far < bot_distance_close){
385                         bot_distance_far = stof(argv(1));
386                         bot_distance_close = stof(argv(0));
387                 }
388         }
389
390         int c;
391
392         #define PARSE_WEAPON_PRIORITIES(dist) MACRO_BEGIN \
393                 if (bot_priority_##dist##_prev != autocvar_bot_ai_custom_weapon_priority_##dist) { \
394                         strcpy(bot_priority_##dist##_prev, autocvar_bot_ai_custom_weapon_priority_##dist); \
395                         tokens = tokenizebyseparator(W_NumberWeaponOrder(autocvar_bot_ai_custom_weapon_priority_##dist)," "); \
396                         bot_weapons_##dist[0] = -1; \
397                         c = 0; \
398                         for(i = 0; i < tokens && c < REGISTRY_COUNT(Weapons); ++i) { \
399                                 w = stof(argv(i)); \
400                                 if (w >= WEP_FIRST && w <= WEP_LAST) { \
401                                         bot_weapons_##dist[c] = w; \
402                                         ++c; \
403                                 } \
404                         } \
405                         if (c < REGISTRY_COUNT(Weapons)) \
406                                 bot_weapons_##dist[c] = -1; \
407                 } \
408         MACRO_END
409
410         PARSE_WEAPON_PRIORITIES(far);
411         PARSE_WEAPON_PRIORITIES(mid);
412         PARSE_WEAPON_PRIORITIES(close);
413
414         bot_custom_weapon = true;
415 }
416
417 void bot_endgame()
418 {
419         bot_relinkplayerlist();
420         entity e = bot_list;
421         while (e)
422         {
423                 setcolor(e, e.bot_preferredcolors);
424                 e = e.nextbot;
425         }
426         // if dynamic waypoints are ever implemented, save them here
427 }
428
429 void bot_relinkplayerlist()
430 {
431         player_count = 0;
432         currentbots = 0;
433         bot_list = NULL;
434
435         entity prevbot = NULL;
436         FOREACH_CLIENT(true,
437         {
438                 ++player_count;
439
440                 if(IS_BOT_CLIENT(it))
441                 {
442                         if (!IS_OBSERVER(it) && !bot_ispaused(it))
443                         {
444                                 if(prevbot)
445                                         prevbot.nextbot = it;
446                                 else
447                                         bot_list = it;
448                                 prevbot = it;
449                         }
450                         ++currentbots;
451                 }
452         });
453         if(prevbot)
454                 prevbot.nextbot = NULL;
455         bot_strategytoken = bot_list;
456         bot_strategytoken_taken = true;
457 }
458
459 void bot_clientdisconnect(entity this)
460 {
461         if (!IS_BOT_CLIENT(this))
462                 return;
463         bot_clearqueue(this);
464         strfree(this.cleanname);
465         strfree(this.netname_freeme);
466         strfree(this.playermodel_freeme);
467         strfree(this.playerskin_freeme);
468         if(this.bot_cmd_current)
469                 delete(this.bot_cmd_current);
470         if(bot_waypoint_queue_owner == this)
471                 bot_waypoint_queue_owner = NULL;
472 }
473
474 void bot_clientconnect(entity this)
475 {
476         if (!IS_BOT_CLIENT(this)) return;
477         this.bot_preferredcolors = this.clientcolors;
478         this.bot_nextthink = time - random();
479         this.isbot = true;
480         this.createdtime = this.bot_nextthink;
481
482         if(!this.bot_config_loaded) // This is needed so team overrider doesn't break between matches
483         {
484                 bot_setnameandstuff(this);
485                 bot_setclientfields(this);
486         }
487
488         havocbot_setupbot(this);
489 }
490
491 void bot_removefromlargestteam()
492 {
493         entity balance = TeamBalance_CheckAllowedTeams(NULL);
494         TeamBalance_GetTeamCounts(balance, NULL);
495
496         entity best = NULL;
497         float besttime = 0;
498         int bestcount = 0;
499
500         int bcount = 0;
501         FOREACH_CLIENT(it.isbot,
502         {
503                 ++bcount;
504
505                 if(!best)
506                 {
507                         best = it;
508                         besttime = it.createdtime;
509                 }
510
511                 int thiscount = 0;
512
513                 if (Team_IsValidTeam(it.team))
514                 {
515                         thiscount = TeamBalance_GetNumberOfPlayers(balance,
516                                 Team_TeamToIndex(it.team));
517                 }
518
519                 if(thiscount > bestcount)
520                 {
521                         bestcount = thiscount;
522                         besttime = it.createdtime;
523                         best = it;
524                 }
525                 else if(thiscount == bestcount && besttime < it.createdtime)
526                 {
527                         besttime = it.createdtime;
528                         best = it;
529                 }
530         });
531         TeamBalance_Destroy(balance);
532         if(!bcount)
533                 return; // no bots to remove
534         currentbots = currentbots - 1;
535         dropclient(best);
536 }
537
538 void bot_removenewest()
539 {
540         if(teamplay)
541         {
542                 bot_removefromlargestteam();
543                 return;
544         }
545
546         float besttime = 0;
547         entity best = NULL;
548         int bcount = 0;
549
550         FOREACH_CLIENT(it.isbot,
551         {
552                 ++bcount;
553
554                 if(!best)
555                 {
556                         best = it;
557                         besttime = it.createdtime;
558                 }
559
560                 if(besttime < it.createdtime)
561                 {
562                         besttime = it.createdtime;
563                         best = it;
564                 }
565         });
566
567         if(!bcount)
568                 return; // no bots to remove
569
570         currentbots = currentbots - 1;
571         dropclient(best);
572 }
573
574 void autoskill(float factor)
575 {
576         int bestbot = -1;
577         int bestplayer = -1;
578         FOREACH_CLIENT(IS_PLAYER(it), {
579                 if(IS_REAL_CLIENT(it))
580                         bestplayer = max(bestplayer, it.totalfrags - it.totalfrags_lastcheck);
581                 else
582                         bestbot = max(bestbot, it.totalfrags - it.totalfrags_lastcheck);
583         });
584
585         string msg = strcat("autoskill: best player got ", ftos(bestplayer), ", ""best bot got ", ftos(bestbot), "; ");
586         if(bestbot < 0 || bestplayer < 0)
587         {
588                 msg = strcat(msg, "not doing anything");
589                 // don't return, let it reset all counters below
590         }
591         else if(bestbot <= bestplayer * factor - 2)
592         {
593                 if(autocvar_skill < 17)
594                 {
595                         msg = strcat(msg, "2 frags difference, increasing skill");
596                         cvar_set("skill", ftos(autocvar_skill + 1));
597                         bprint("^2BOT SKILL UP!^7 Now at level ", ftos(autocvar_skill), "\n");
598                 }
599         }
600         else if(bestbot >= bestplayer * factor + 2)
601         {
602                 if(autocvar_skill > 0)
603                 {
604                         msg = strcat(msg, "2 frags difference, decreasing skill");
605                         cvar_set("skill", ftos(autocvar_skill - 1));
606                         bprint("^1BOT SKILL DOWN!^7 Now at level ", ftos(autocvar_skill), "\n");
607                 }
608         }
609         else
610         {
611                 msg = strcat(msg, "not doing anything");
612                 return;
613                 // don't reset counters, wait for them to accumulate
614         }
615         LOG_DEBUG(msg);
616
617         FOREACH_CLIENT(IS_PLAYER(it), { it.totalfrags_lastcheck = it.totalfrags; });
618 }
619
620 void bot_calculate_stepheightvec()
621 {
622         stepheightvec = autocvar_sv_stepheight * '0 0 1';
623         jumpheight_vec = (autocvar_sv_jumpvelocity ** 2) / (2 * autocvar_sv_gravity) * '0 0 1';
624         jumpstepheightvec = stepheightvec + jumpheight_vec * 0.85; // reduce it a bit to make the jumps easy
625         jumpheight_time = autocvar_sv_jumpvelocity / autocvar_sv_gravity;
626 }
627
628 bool bot_fixcount(bool multiple_per_frame)
629 {
630         int activerealplayers = 0;
631         int realplayers = 0;
632         if (MUTATOR_CALLHOOK(Bot_FixCount, activerealplayers, realplayers)) {
633                 activerealplayers = M_ARGV(0, int);
634                 realplayers = M_ARGV(1, int);
635         } else {
636                 FOREACH_CLIENT(IS_REAL_CLIENT(it), {
637                         if(IS_PLAYER(it))
638                                 ++activerealplayers;
639                         ++realplayers;
640                 });
641         }
642
643         int bots;
644         // But don't remove bots immediately on level change, as the real players
645         // usually haven't rejoined yet
646         bots_would_leave = false;
647         if (autocvar_bot_vs_human && AVAILABLE_TEAMS == 2)
648                 bots = min(ceil(fabs(autocvar_bot_vs_human) * activerealplayers), maxclients - realplayers);
649         else if ((realplayers || autocvar_bot_join_empty || (currentbots > 0 && time < 5)))
650         {
651                 int minplayers = max(0, floor(autocvar_minplayers));
652                 if (teamplay)
653                         minplayers = max(0, floor(autocvar_minplayers_per_team) * AVAILABLE_TEAMS);
654                 int minbots = max(0, floor(autocvar_bot_number));
655
656                 // add bots to reach minplayers if needed
657                 bots = max(minbots, minplayers - activerealplayers);
658                 // cap bots to the max players allowed by the server
659                 int player_limit = GetPlayerLimit();
660                 if(player_limit)
661                         bots = min(bots, max(player_limit - activerealplayers, 0));
662                 bots = min(bots, maxclients - realplayers);
663
664                 if(bots > minbots)
665                         bots_would_leave = true;
666         }
667         else
668         {
669                 // if there are no players, remove bots
670                 bots = 0;
671         }
672
673         // only add one bot per frame to avoid utter chaos
674         if(time > botframe_nextthink)
675         {
676                 while (currentbots < bots)
677                 {
678                         if (bot_spawn() == NULL)
679                         {
680                                 bprint("Can not add bot, server full.\n");
681                                 return false;
682                         }
683                         if (!multiple_per_frame)
684                         {
685                                 break;
686                         }
687                 }
688                 while (currentbots > bots && bots >= 0)
689                         bot_removenewest();
690         }
691
692         return true;
693 }
694
695 void bot_serverframe()
696 {
697         if (intermission_running && currentbots > 0)
698         {
699                 // after the end of the match all bots stay unless all human players disconnect
700                 int realplayers = 0;
701                 FOREACH_CLIENT(IS_REAL_CLIENT(it), { ++realplayers; });
702                 if (!realplayers)
703                 {
704                         FOREACH_CLIENT(IS_BOT_CLIENT(it), { dropclient(it); });
705                         currentbots = 0;
706                 }
707                 return;
708         }
709
710         if (game_stopped)
711                 return;
712
713         // Added 0.5 to avoid possible addition + immediate removal of bots that would make them appear as
714         // spectators in the scoreboard and never go away. This issue happens at time 2 if map is changed
715         // with the gotomap command, minplayers is > 1 and human clients join as players very soon
716         // either intentionally or automatically (sv_spectate 0)
717         // A working workaround for this bug was implemented in commit fbd145044, see entcs_attach
718         if (time < 2.5)
719         {
720                 currentbots = -1;
721                 return;
722         }
723
724         if (currentbots == -1)
725         {
726                 // count bots already in the server from the previous match
727                 currentbots = 0;
728                 FOREACH_CLIENT(IS_BOT_CLIENT(it), { ++currentbots; });
729         }
730
731         if(autocvar_skill != skill)
732         {
733                 float wpcost_update = false;
734                 if(skill >= autocvar_bot_ai_bunnyhop_skilloffset && autocvar_skill < autocvar_bot_ai_bunnyhop_skilloffset)
735                         wpcost_update = true;
736                 if(skill < autocvar_bot_ai_bunnyhop_skilloffset && autocvar_skill >= autocvar_bot_ai_bunnyhop_skilloffset)
737                         wpcost_update = true;
738
739                 skill = autocvar_skill;
740                 if (wpcost_update)
741                         waypoint_updatecost_foralllinks();
742         }
743
744         bot_calculate_stepheightvec();
745         bot_navigation_movemode = ((autocvar_bot_navigation_ignoreplayers) ? MOVE_NOMONSTERS : MOVE_NORMAL);
746
747         if(time > autoskill_nextthink)
748         {
749                 float a;
750                 a = autocvar_skill_auto;
751                 if(a)
752                         autoskill(a);
753                 autoskill_nextthink = time + 5;
754         }
755
756         if(time > botframe_nextthink)
757         {
758                 if(!bot_fixcount(false))
759                         botframe_nextthink = time + 10;
760         }
761
762         if(botframe_spawnedwaypoints)
763         {
764                 if(autocvar_waypoint_benchmark)
765                         localcmd("quit\n");
766         }
767
768         if (currentbots > 0 || waypointeditor_enabled || autocvar_g_waypointeditor_auto)
769         if (botframe_spawnedwaypoints)
770         {
771                 if(botframe_cachedwaypointlinks)
772                 {
773                         if(!botframe_loadedforcedlinks)
774                                 waypoint_load_hardwiredlinks();
775                 }
776                 else
777                 {
778                         // TODO: Make this check cleaner
779                         IL_EACH(g_waypoints, time - it.nextthink > 10,
780                         {
781                                 waypoint_save_links();
782                                 break;
783                         });
784                 }
785         }
786         else
787         {
788                 botframe_spawnedwaypoints = true;
789                 waypoint_loadall();
790                 waypoint_load_links();
791         }
792
793         if (bot_list)
794         {
795                 // cycle the goal token from one bot to the next each frame
796                 // (this prevents them from all doing spawnfunc_waypoint searches on the same
797                 //  frame, which causes choppy framerates)
798                 if (bot_strategytoken_taken)
799                 {
800                         // give goal token to the first bot without goals; if all bots don't have
801                         // any goal (or are dead/frozen) simply give it to the next one
802                         bot_strategytoken_taken = false;
803                         entity bot_strategytoken_save = bot_strategytoken;
804                         while (true)
805                         {
806                                 if (bot_strategytoken)
807                                         bot_strategytoken = bot_strategytoken.nextbot;
808                                 if (!bot_strategytoken)
809                                         bot_strategytoken = bot_list;
810
811                                 if (!(IS_DEAD(bot_strategytoken) || STAT(FROZEN, bot_strategytoken))
812                                         && !bot_strategytoken.goalcurrent)
813                                         break;
814
815                                 if (!bot_strategytoken_save) // break loop if all the bots are dead or frozen
816                                         break;
817                                 if (bot_strategytoken == bot_strategytoken_save)
818                                         bot_strategytoken_save = NULL; // looped through all the bots
819                         }
820                 }
821
822                 if (botframe_nextdangertime < time)
823                 {
824                         float interval;
825                         interval = autocvar_bot_ai_dangerdetectioninterval;
826                         if (botframe_nextdangertime < time - interval * 1.5)
827                                 botframe_nextdangertime = time;
828                         botframe_nextdangertime = botframe_nextdangertime + interval;
829                         botframe_updatedangerousobjects(autocvar_bot_ai_dangerdetectionupdates);
830                 }
831         }
832
833         if (waypointeditor_enabled)
834                 botframe_showwaypointlinks();
835
836         if (autocvar_g_waypointeditor_auto)
837                 botframe_autowaypoints();
838
839         if (currentbots > 0)
840                 bot_custom_weapon_priority_setup();
841 }