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