Increase the maximum number of mutators
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / bot / default / bot.qc
1 #include "bot.qh"
2
3 #include "aim.qh"
4 #include "navigation.qh"
5 #include "scripting.qh"
6 #include "waypoints.qh"
7
8 #include "havocbot/havocbot.qh"
9
10 #include "../../weapons/accuracy.qh"
11
12 entity bot_spawn()
13 {SELFPARAM();
14         entity bot = spawnclient();
15         if (bot)
16         {
17                 currentbots = currentbots + 1;
18                 setself(bot);
19                 bot_setnameandstuff();
20                 ClientConnect();
21                 PutClientInServer();
22                 setself(this);
23         }
24         return bot;
25 }
26
27 void bot_think()
28 {SELFPARAM();
29         if (self.bot_nextthink > time)
30                 return;
31
32         self.flags &= ~FL_GODMODE;
33         if(autocvar_bot_god)
34                 self.flags |= FL_GODMODE;
35
36         self.bot_nextthink = self.bot_nextthink + autocvar_bot_ai_thinkinterval * pow(0.5, self.bot_aiskill);
37         //if (self.bot_painintensity > 0)
38         //      self.bot_painintensity = self.bot_painintensity - (skill + 1) * 40 * frametime;
39
40         //self.bot_painintensity = self.bot_painintensity + self.bot_oldhealth - self.health;
41         //self.bot_painintensity = bound(0, self.bot_painintensity, 100);
42
43         if (!IS_PLAYER(self) || (autocvar_g_campaign && !campaign_bots_may_start))
44         {
45                 self.bot_nextthink = time + 0.5;
46                 return;
47         }
48
49         if (self.fixangle)
50         {
51                 self.v_angle = self.angles;
52                 self.v_angle_z = 0;
53                 self.fixangle = false;
54         }
55
56         self.dmg_take = 0;
57         self.dmg_save = 0;
58         self.dmg_inflictor = world;
59
60         // calculate an aiming latency based on the skill setting
61         // (simulated network latency + naturally delayed reflexes)
62         //self.ping = 0.7 - bound(0, 0.05 * skill, 0.5); // moved the reflexes to bot_aimdir (under the name 'think')
63         // minimum ping 20+10 random
64         self.ping = bound(0,0.07 - bound(0, (skill + self.bot_pingskill) * 0.005,0.05)+random()*0.01,0.65); // Now holds real lag to server, and higer skill players take a less laggy server
65         // skill 10 = ping 0.2 (adrenaline)
66         // skill 0 = ping 0.7 (slightly drunk)
67
68         // clear buttons
69         self.BUTTON_ATCK = 0;
70         self.button1 = 0;
71         self.BUTTON_JUMP = 0;
72         self.BUTTON_ATCK2 = 0;
73         self.BUTTON_ZOOM = 0;
74         self.BUTTON_CROUCH = 0;
75         self.BUTTON_HOOK = 0;
76         self.BUTTON_INFO = 0;
77         self.button8 = 0;
78         self.BUTTON_CHAT = 0;
79         self.BUTTON_USE = 0;
80
81         if (time < game_starttime)
82         {
83                 // block the bot during the countdown to game start
84                 self.movement = '0 0 0';
85                 self.bot_nextthink = game_starttime;
86                 return;
87         }
88
89         // if dead, just wait until we can respawn
90         if (self.deadflag)
91         {
92                 if (self.deadflag == DEAD_DEAD)
93                 {
94                         self.BUTTON_JUMP = 1; // press jump to respawn
95                         self.bot_strategytime = 0;
96                 }
97         }
98         else if(self.aistatus & AI_STATUS_STUCK)
99                 navigation_unstuck();
100
101         // now call the current bot AI (havocbot for example)
102         self.bot_ai();
103 }
104
105 void bot_setnameandstuff()
106 {SELFPARAM();
107         string readfile, s;
108         float file, tokens, prio;
109         entity p;
110
111         string bot_name, bot_model, bot_skin, bot_shirt, bot_pants;
112         string name, prefix, suffix;
113
114         if(autocvar_g_campaign)
115         {
116                 prefix = "";
117                 suffix = "";
118         }
119         else
120         {
121                 prefix = autocvar_bot_prefix;
122                 suffix = autocvar_bot_suffix;
123         }
124
125         file = fopen(autocvar_bot_config_file, FILE_READ);
126
127         if(file < 0)
128         {
129                 LOG_INFO(strcat("Error: Can not open the bot configuration file '",autocvar_bot_config_file,"'\n"));
130                 readfile = "";
131         }
132         else
133         {
134                 RandomSelection_Init();
135                 while((readfile = fgets(file)))
136                 {
137                         if(substring(readfile, 0, 2) == "//")
138                                 continue;
139                         if(substring(readfile, 0, 1) == "#")
140                                 continue;
141                         tokens = tokenizebyseparator(readfile, "\t");
142                         if(tokens == 0)
143                                 continue;
144                         s = argv(0);
145                         prio = 1;
146                         FOR_EACH_CLIENT(p)
147                         {
148                                 if(IS_BOT_CLIENT(p))
149                                 if(s == p.cleanname)
150                                 {
151                                         prio = 0;
152                                         break;
153                                 }
154                         }
155                         RandomSelection_Add(world, 0, readfile, 1, prio);
156                 }
157                 readfile = RandomSelection_chosen_string;
158                 fclose(file);
159         }
160
161         tokens = tokenizebyseparator(readfile, "\t");
162         if(argv(0) != "") bot_name = argv(0);
163         else bot_name = "Bot";
164
165         if(argv(1) != "") bot_model = argv(1);
166         else bot_model = "";
167
168         if(argv(2) != "") bot_skin = argv(2);
169         else bot_skin = "0";
170
171         if(argv(3) != "" && stof(argv(3)) >= 0) bot_shirt = argv(3);
172         else bot_shirt = ftos(floor(random() * 15));
173
174         if(argv(4) != "" && stof(argv(4)) >= 0) bot_pants = argv(4);
175         else bot_pants = ftos(floor(random() * 15));
176
177         self.bot_forced_team = stof(argv(5));
178
179         prio = 6;
180
181         #define READSKILL(f,w,r) if(argv(prio) != "") self.f = stof(argv(prio)) * (w); else self.f = (!autocvar_g_campaign) * (2 * random() - 1) * (r) * (w); ++prio
182         //print(bot_name, ": ping=", argv(9), "\n");
183
184         READSKILL(havocbot_keyboardskill, 0.5, 0.5); // keyboard skill
185         READSKILL(bot_moveskill, 2, 0); // move skill
186         READSKILL(bot_dodgeskill, 2, 0); // dodge skill
187
188         READSKILL(bot_pingskill, 0.5, 0); // ping skill
189
190         READSKILL(bot_weaponskill, 2, 0); // weapon skill
191         READSKILL(bot_aggresskill, 1, 0); // aggre skill
192         READSKILL(bot_rangepreference, 1, 0); // read skill
193
194         READSKILL(bot_aimskill, 2, 0); // aim skill
195         READSKILL(bot_offsetskill, 2, 0.5); // offset skill
196         READSKILL(bot_mouseskill, 1, 0.5); // mouse skill
197
198         READSKILL(bot_thinkskill, 1, 0.5); // think skill
199         READSKILL(bot_aiskill, 2, 0); // "ai" skill
200
201         self.bot_config_loaded = true;
202
203         // this is really only a default, JoinBestTeam is called later
204         setcolor(self, stof(bot_shirt) * 16 + stof(bot_pants));
205         self.bot_preferredcolors = self.clientcolors;
206
207         // pick the name
208         if (autocvar_bot_usemodelnames)
209                 name = bot_model;
210         else
211                 name = bot_name;
212
213         // number bots with identical names
214         float i;
215         i = 0;
216         FOR_EACH_CLIENT(p)
217         {
218                 if(IS_BOT_CLIENT(p))
219                         if(p.cleanname == name)
220                                 ++i;
221         }
222         if (i)
223                 self.netname = self.netname_freeme = strzone(strcat(prefix, name, "(", ftos(i), ")", suffix));
224         else
225                 self.netname = self.netname_freeme = strzone(strcat(prefix, name, suffix));
226
227         self.cleanname = strzone(name);
228
229         // pick the model and skin
230         if(substring(bot_model, -4, 1) != ".")
231                 bot_model = strcat(bot_model, ".iqm");
232         self.playermodel = self.playermodel_freeme = strzone(strcat("models/player/", bot_model));
233         self.playerskin = self.playerskin_freeme = strzone(bot_skin);
234
235         self.cvar_cl_accuracy_data_share = 1;  // share the bots weapon accuracy data with the world
236         self.cvar_cl_accuracy_data_receive = 0;  // don't receive any weapon accuracy data
237 }
238
239 void bot_custom_weapon_priority_setup()
240 {
241         float tokens, i, w;
242
243         bot_custom_weapon = false;
244
245         if(     autocvar_bot_ai_custom_weapon_priority_far == "" ||
246                 autocvar_bot_ai_custom_weapon_priority_mid == "" ||
247                 autocvar_bot_ai_custom_weapon_priority_close == "" ||
248                 autocvar_bot_ai_custom_weapon_priority_distances == ""
249         )
250                 return;
251
252         // Parse distances
253         tokens = tokenizebyseparator(autocvar_bot_ai_custom_weapon_priority_distances," ");
254
255         if (tokens!=2)
256                 return;
257
258         bot_distance_far = stof(argv(0));
259         bot_distance_close = stof(argv(1));
260
261         if(bot_distance_far < bot_distance_close){
262                 bot_distance_far = stof(argv(1));
263                 bot_distance_close = stof(argv(0));
264         }
265
266         // Initialize list of weapons
267         bot_weapons_far[0] = -1;
268         bot_weapons_mid[0] = -1;
269         bot_weapons_close[0] = -1;
270
271         // Parse far distance weapon priorities
272         tokens = tokenizebyseparator(W_NumberWeaponOrder(autocvar_bot_ai_custom_weapon_priority_far)," ");
273
274         int c = 0;
275         for(i=0; i < tokens && c < Weapons_COUNT; ++i){
276                 w = stof(argv(i));
277                 if ( w >= WEP_FIRST && w <= WEP_LAST) {
278                         bot_weapons_far[c] = w;
279                         ++c;
280                 }
281         }
282         if(c < Weapons_COUNT)
283                 bot_weapons_far[c] = -1;
284
285         // Parse mid distance weapon priorities
286         tokens = tokenizebyseparator(W_NumberWeaponOrder(autocvar_bot_ai_custom_weapon_priority_mid)," ");
287
288         c = 0;
289         for(i=0; i < tokens && c < Weapons_COUNT; ++i){
290                 w = stof(argv(i));
291                 if ( w >= WEP_FIRST && w <= WEP_LAST) {
292                         bot_weapons_mid[c] = w;
293                         ++c;
294                 }
295         }
296         if(c < Weapons_COUNT)
297                 bot_weapons_mid[c] = -1;
298
299         // Parse close distance weapon priorities
300         tokens = tokenizebyseparator(W_NumberWeaponOrder(autocvar_bot_ai_custom_weapon_priority_close)," ");
301
302         c = 0;
303         for(i=0; i < tokens && i < Weapons_COUNT; ++i){
304                 w = stof(argv(i));
305                 if ( w >= WEP_FIRST && w <= WEP_LAST) {
306                         bot_weapons_close[c] = w;
307                         ++c;
308                 }
309         }
310         if(c < Weapons_COUNT)
311                 bot_weapons_close[c] = -1;
312
313         bot_custom_weapon = true;
314 }
315
316 void bot_endgame()
317 {
318         entity e;
319         //dprint("bot_endgame\n");
320         e = bot_list;
321         while (e)
322         {
323                 setcolor(e, e.bot_preferredcolors);
324                 e = e.nextbot;
325         }
326         // if dynamic waypoints are ever implemented, save them here
327 }
328
329 void bot_relinkplayerlist()
330 {
331         entity e;
332         entity prevbot;
333         player_count = 0;
334         currentbots = 0;
335         player_list = e = findchainflags(flags, FL_CLIENT);
336         bot_list = world;
337         prevbot = world;
338         while (e)
339         {
340                 player_count = player_count + 1;
341                 e.nextplayer = e.chain;
342                 if (IS_BOT_CLIENT(e))
343                 {
344                         if (prevbot)
345                                 prevbot.nextbot = e;
346                         else
347                         {
348                                 bot_list = e;
349                                 bot_list.nextbot = world;
350                         }
351                         prevbot = e;
352                         currentbots = currentbots + 1;
353                 }
354                 e = e.chain;
355         }
356         LOG_TRACE(strcat("relink: ", ftos(currentbots), " bots seen.\n"));
357         bot_strategytoken = bot_list;
358         bot_strategytoken_taken = true;
359 }
360
361 void bot_clientdisconnect()
362 {SELFPARAM();
363         if (!IS_BOT_CLIENT(self))
364                 return;
365         bot_clearqueue(self);
366         if(self.cleanname)
367                 strunzone(self.cleanname);
368         if(self.netname_freeme)
369                 strunzone(self.netname_freeme);
370         if(self.playermodel_freeme)
371                 strunzone(self.playermodel_freeme);
372         if(self.playerskin_freeme)
373                 strunzone(self.playerskin_freeme);
374         self.cleanname = string_null;
375         self.netname_freeme = string_null;
376         self.playermodel_freeme = string_null;
377         self.playerskin_freeme = string_null;
378         if(self.bot_cmd_current)
379                 remove(self.bot_cmd_current);
380         if(bot_waypoint_queue_owner==self)
381                 bot_waypoint_queue_owner = world;
382 }
383
384 void bot_clientconnect()
385 {SELFPARAM();
386         if (!IS_BOT_CLIENT(self))
387                 return;
388         self.bot_preferredcolors = self.clientcolors;
389         self.bot_nextthink = time - random();
390         self.lag_func = bot_lagfunc;
391         self.isbot = true;
392         self.createdtime = self.bot_nextthink;
393
394         if(!self.bot_config_loaded) // This is needed so team overrider doesn't break between matches
395                 bot_setnameandstuff();
396
397         if(self.bot_forced_team==1)
398                 self.team = NUM_TEAM_1;
399         else if(self.bot_forced_team==2)
400                 self.team = NUM_TEAM_2;
401         else if(self.bot_forced_team==3)
402                 self.team = NUM_TEAM_3;
403         else if(self.bot_forced_team==4)
404                 self.team = NUM_TEAM_4;
405         else
406                 JoinBestTeam(self, false, true);
407
408         havocbot_setupbot();
409 }
410
411 void bot_removefromlargestteam()
412 {
413         float besttime, bestcount, thiscount;
414         entity best, head;
415         CheckAllowedTeams(world);
416         GetTeamCounts(world);
417         head = findchainfloat(isbot, true);
418         if (!head)
419                 return;
420         best = head;
421         besttime = head.createdtime;
422         bestcount = 0;
423         while (head)
424         {
425                 if(head.team == NUM_TEAM_1)
426                         thiscount = c1;
427                 else if(head.team == NUM_TEAM_2)
428                         thiscount = c2;
429                 else if(head.team == NUM_TEAM_3)
430                         thiscount = c3;
431                 else if(head.team == NUM_TEAM_4)
432                         thiscount = c4;
433                 else
434                         thiscount = 0;
435                 if (thiscount > bestcount)
436                 {
437                         bestcount = thiscount;
438                         besttime = head.createdtime;
439                         best = head;
440                 }
441                 else if (thiscount == bestcount && besttime < head.createdtime)
442                 {
443                         besttime = head.createdtime;
444                         best = head;
445                 }
446                 head = head.chain;
447         }
448         currentbots = currentbots - 1;
449         dropclient(best);
450 }
451
452 void bot_removenewest()
453 {
454         float besttime;
455         entity best, head;
456
457         if(teamplay)
458         {
459                 bot_removefromlargestteam();
460                 return;
461         }
462
463         head = findchainfloat(isbot, true);
464         if (!head)
465                 return;
466         best = head;
467         besttime = head.createdtime;
468         while (head)
469         {
470                 if (besttime < head.createdtime)
471                 {
472                         besttime = head.createdtime;
473                         best = head;
474                 }
475                 head = head.chain;
476         }
477         currentbots = currentbots - 1;
478         dropclient(best);
479 }
480
481 void autoskill(float factor)
482 {
483         float bestbot;
484         float bestplayer;
485         entity head;
486
487         bestbot = -1;
488         bestplayer = -1;
489         FOR_EACH_PLAYER(head)
490         {
491                 if(IS_REAL_CLIENT(head))
492                         bestplayer = max(bestplayer, head.totalfrags - head.totalfrags_lastcheck);
493                 else
494                         bestbot = max(bestbot, head.totalfrags - head.totalfrags_lastcheck);
495         }
496
497         LOG_TRACE("autoskill: best player got ", ftos(bestplayer), ", ");
498         LOG_TRACE("best bot got ", ftos(bestbot), "; ");
499         if(bestbot < 0 || bestplayer < 0)
500         {
501                 LOG_TRACE("not doing anything\n");
502                 // don't return, let it reset all counters below
503         }
504         else if(bestbot <= bestplayer * factor - 2)
505         {
506                 if(autocvar_skill < 17)
507                 {
508                         LOG_TRACE("2 frags difference, increasing skill\n");
509                         cvar_set("skill", ftos(autocvar_skill + 1));
510                         bprint("^2SKILL UP!^7 Now at level ", ftos(autocvar_skill), "\n");
511                 }
512         }
513         else if(bestbot >= bestplayer * factor + 2)
514         {
515                 if(autocvar_skill > 0)
516                 {
517                         LOG_TRACE("2 frags difference, decreasing skill\n");
518                         cvar_set("skill", ftos(autocvar_skill - 1));
519                         bprint("^1SKILL DOWN!^7 Now at level ", ftos(autocvar_skill), "\n");
520                 }
521         }
522         else
523         {
524                 LOG_TRACE("not doing anything\n");
525                 return;
526                 // don't reset counters, wait for them to accumulate
527         }
528
529         FOR_EACH_PLAYER(head)
530                 head.totalfrags_lastcheck = head.totalfrags;
531 }
532
533 void bot_calculate_stepheightvec(void)
534 {
535         stepheightvec = autocvar_sv_stepheight * '0 0 1';
536         jumpstepheightvec = stepheightvec +
537                 ((autocvar_sv_jumpvelocity * autocvar_sv_jumpvelocity) / (2 * autocvar_sv_gravity)) * '0 0 0.85';
538                 // 0.75 factor is for safety to make the jumps easy
539 }
540
541 float bot_fixcount()
542 {
543         entity head;
544         float realplayers, bots, activerealplayers;
545
546         activerealplayers = 0;
547         realplayers = 0;
548
549         FOR_EACH_REALCLIENT(head)
550         {
551                 if(IS_PLAYER(head) || g_lms || head.caplayer == 1)
552                         ++activerealplayers;
553                 ++realplayers;
554         }
555
556         // add/remove bots if needed to make sure there are at least
557         // minplayers+bot_number, or remove all bots if no one is playing
558         // But don't remove bots immediately on level change, as the real players
559         // usually haven't rejoined yet
560         bots_would_leave = false;
561         if (teamplay && autocvar_bot_vs_human && (c3==-1 && c4==-1))
562                 bots = min(ceil(fabs(autocvar_bot_vs_human) * activerealplayers), maxclients - realplayers);
563         else if ((realplayers || autocvar_bot_join_empty || (currentbots > 0 && time < 5)))
564         {
565                 float realminplayers, minplayers;
566                 realminplayers = autocvar_minplayers;
567                 minplayers = max(0, floor(realminplayers));
568
569                 float realminbots, minbots;
570                 realminbots = autocvar_bot_number;
571                 minbots = max(0, floor(realminbots));
572
573                 bots = min(max(minbots, minplayers - activerealplayers), maxclients - realplayers);
574                 if(bots > minbots)
575                         bots_would_leave = true;
576         }
577         else
578         {
579                 // if there are no players, remove bots
580                 bots = 0;
581         }
582
583         // only add one bot per frame to avoid utter chaos
584         if(time > botframe_nextthink)
585         {
586                 //dprint(ftos(bots), " ? ", ftos(currentbots), "\n");
587                 while (currentbots < bots)
588                 {
589                         if (bot_spawn() == world)
590                         {
591                                 bprint("Can not add bot, server full.\n");
592                                 return false;
593                         }
594                 }
595                 while (currentbots > bots)
596                         bot_removenewest();
597         }
598
599         return true;
600 }
601
602 void bot_serverframe()
603 {
604         if (intermission_running)
605                 return;
606
607         if (time < 2)
608                 return;
609
610         bot_calculate_stepheightvec();
611         bot_navigation_movemode = ((autocvar_bot_navigation_ignoreplayers) ? MOVE_NOMONSTERS : MOVE_NORMAL);
612
613         if(time > autoskill_nextthink)
614         {
615                 float a;
616                 a = autocvar_skill_auto;
617                 if(a)
618                         autoskill(a);
619                 autoskill_nextthink = time + 5;
620         }
621
622         if(time > botframe_nextthink)
623         {
624                 if(!bot_fixcount())
625                         botframe_nextthink = time + 10;
626         }
627
628         bot_ignore_bots = autocvar_bot_ignore_bots;
629
630         if(botframe_spawnedwaypoints)
631         {
632                 if(autocvar_waypoint_benchmark)
633                         localcmd("quit\n");
634         }
635
636         if (currentbots > 0 || autocvar_g_waypointeditor || autocvar_g_waypointeditor_auto)
637         if (botframe_spawnedwaypoints)
638         {
639                 if(botframe_cachedwaypointlinks)
640                 {
641                         if(!botframe_loadedforcedlinks)
642                                 waypoint_load_links_hardwired();
643                 }
644                 else
645                 {
646                         // TODO: Make this check cleaner
647                         entity wp = findchain(classname, "waypoint");
648                         if(time - wp.nextthink > 10)
649                                 waypoint_save_links();
650                 }
651         }
652         else
653         {
654                 botframe_spawnedwaypoints = true;
655                 waypoint_loadall();
656                 if(!waypoint_load_links())
657                         waypoint_schedulerelinkall();
658         }
659
660         if (bot_list)
661         {
662                 // cycle the goal token from one bot to the next each frame
663                 // (this prevents them from all doing spawnfunc_waypoint searches on the same
664                 //  frame, which causes choppy framerates)
665                 if (bot_strategytoken_taken)
666                 {
667                         bot_strategytoken_taken = false;
668                         if (bot_strategytoken)
669                                 bot_strategytoken = bot_strategytoken.nextbot;
670                         if (!bot_strategytoken)
671                                 bot_strategytoken = bot_list;
672                 }
673
674                 if (botframe_nextdangertime < time)
675                 {
676                         float interval;
677                         interval = autocvar_bot_ai_dangerdetectioninterval;
678                         if (botframe_nextdangertime < time - interval * 1.5)
679                                 botframe_nextdangertime = time;
680                         botframe_nextdangertime = botframe_nextdangertime + interval;
681                         botframe_updatedangerousobjects(autocvar_bot_ai_dangerdetectionupdates);
682                 }
683         }
684
685         if (autocvar_g_waypointeditor)
686                 botframe_showwaypointlinks();
687
688         if (autocvar_g_waypointeditor_auto)
689                 botframe_autowaypoints();
690
691         if(time > bot_cvar_nextthink)
692         {
693                 if(currentbots>0)
694                         bot_custom_weapon_priority_setup();
695                 bot_cvar_nextthink = time + 5;
696         }
697 }