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