]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/main.qc
Remove redundant g_players intrusive list
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / main.qc
1 #include "main.qh"
2
3 #include <common/command/generic.qh>
4 #include <common/constants.qh>
5 #include <common/deathtypes/all.qh>
6 #include <common/debug.qh>
7 #include <common/mapinfo.qh>
8 #include <common/monsters/sv_monsters.qh>
9 #include <common/util.qh>
10 #include <common/vehicles/all.qh>
11 #include <common/weapons/_all.qh>
12 #include <lib/csqcmodel/sv_model.qh>
13 #include <lib/warpzone/common.qh>
14 #include <lib/warpzone/server.qh>
15 #include <server/anticheat.qh>
16 #include <server/bot/api.qh>
17 #include <server/command/common.qh>
18 #include <server/compat/quake3.qh>
19 #include <server/damage.qh>
20 #include <server/gamelog.qh>
21 #include <server/hook.qh>
22 #include <server/ipban.qh>
23 #include <server/mutators/_mod.qh>
24 #include <server/spawnpoints.qh>
25 #include <server/weapons/common.qh>
26 #include <server/weapons/csqcprojectile.qh>
27 #include <server/world.qh>
28
29 void dropclient_do(entity this)
30 {
31         if (this.owner)
32                 dropclient(this.owner);
33         delete(this);
34 }
35
36 /**
37  * Schedules dropclient for a player and returns true;
38  * if dropclient is already scheduled (for that player) it does nothing and returns false.
39  *
40  * NOTE: this function exists only to allow sending a message to the kicked player with
41  * Send_Notification, which doesn't work if called together with dropclient
42  */
43 bool dropclient_schedule(entity this)
44 {
45         bool scheduled = false;
46         FOREACH_ENTITY_CLASS("dropclient_handler", true,
47         {
48                 if(it.owner == this)
49                 {
50                         scheduled = true;
51                         break; // can't use return here, compiler shows a warning
52                 }
53         });
54         if (scheduled)
55                 return false;
56
57         entity e = new_pure(dropclient_handler);
58         setthink(e, dropclient_do);
59         e.owner = this;
60         e.nextthink = time + 0.1;
61         return true;
62 }
63
64 void CreatureFrame_hotliquids(entity this)
65 {
66         if (this.contents_damagetime >= time)
67         {
68                 return;
69         }
70
71         this.contents_damagetime = time + autocvar_g_balance_contents_damagerate;
72
73         if (this.flags & FL_PROJECTILE)
74         {
75                 if (this.watertype == CONTENT_LAVA)
76                         Damage (this, NULL, NULL, autocvar_g_balance_contents_projectiledamage * autocvar_g_balance_contents_damagerate * this.waterlevel, DEATH_LAVA.m_id, DMG_NOWEP, this.origin, '0 0 0');
77                 else if (this.watertype == CONTENT_SLIME)
78                         Damage (this, NULL, NULL, autocvar_g_balance_contents_projectiledamage * autocvar_g_balance_contents_damagerate * this.waterlevel, DEATH_SLIME.m_id, DMG_NOWEP, this.origin, '0 0 0');
79         }
80         else
81         {
82                 if (STAT(FROZEN, this))
83                 {
84                         if (this.watertype == CONTENT_LAVA)
85                                 Damage(this, NULL, NULL, 10000, DEATH_LAVA.m_id, DMG_NOWEP, this.origin, '0 0 0');
86                         else if (this.watertype == CONTENT_SLIME)
87                                 Damage(this, NULL, NULL, 10000, DEATH_SLIME.m_id, DMG_NOWEP, this.origin, '0 0 0');
88                 }
89                 else if (this.watertype == CONTENT_LAVA)
90                 {
91                         if (this.watersound_finished < time)
92                         {
93                                 this.watersound_finished = time + 0.5;
94                                 sound (this, CH_PLAYER_SINGLE, SND_LAVA, VOL_BASE, ATTEN_NORM);
95                         }
96                         Damage (this, NULL, NULL, autocvar_g_balance_contents_playerdamage_lava * autocvar_g_balance_contents_damagerate * this.waterlevel, DEATH_LAVA.m_id, DMG_NOWEP, this.origin, '0 0 0');
97                         if(autocvar_g_balance_contents_playerdamage_lava_burn)
98                                 Fire_AddDamage(this, NULL, autocvar_g_balance_contents_playerdamage_lava_burn * this.waterlevel, autocvar_g_balance_contents_playerdamage_lava_burn_time * this.waterlevel, DEATH_LAVA.m_id);
99                 }
100                 else if (this.watertype == CONTENT_SLIME)
101                 {
102                         if (this.watersound_finished < time)
103                         {
104                                 this.watersound_finished = time + 0.5;
105                                 sound (this, CH_PLAYER_SINGLE, SND_SLIME, VOL_BASE, ATTEN_NORM);
106                         }
107                         Damage (this, NULL, NULL, autocvar_g_balance_contents_playerdamage_slime * autocvar_g_balance_contents_damagerate * this.waterlevel, DEATH_SLIME.m_id, DMG_NOWEP, this.origin, '0 0 0');
108                 }
109         }
110 }
111
112 void CreatureFrame_Liquids(entity this)
113 {
114         if (this.watertype <= CONTENT_WATER && this.waterlevel > 0) // workaround a retarded bug made by id software :P (yes, it's that old of a bug)
115         {
116                 if (!(this.flags & FL_INWATER))
117                 {
118                         this.flags |= FL_INWATER;
119                         this.contents_damagetime = 0;
120                 }
121
122                 CreatureFrame_hotliquids(this);
123         }
124         else
125         {
126                 if (this.flags & FL_INWATER)
127                 {
128                         // play leave water sound
129                         this.flags &= ~FL_INWATER;
130                         this.contents_damagetime = 0;
131                 }
132         }
133 }
134
135 void CreatureFrame_FallDamage(entity this)
136 {
137         if(IS_VEHICLE(this) || (this.flags & FL_PROJECTILE))
138                 return; // vehicles and projectiles don't receive fall damage
139         if(!(this.velocity || this.oldvelocity))
140                 return; // if the entity hasn't moved and isn't moving, then don't do anything
141
142         // check for falling damage
143         bool have_hook = false;
144         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
145         {
146                 .entity weaponentity = weaponentities[slot];
147                 if(this.(weaponentity).hook && this.(weaponentity).hook.state)
148                 {
149                         have_hook = true;
150                         break;
151                 }
152         }
153         if(!have_hook)
154         {
155                 float dm; // dm is the velocity DECREASE. Velocity INCREASE should never cause a sound or any damage.
156                 if(autocvar_g_balance_falldamage_onlyvertical)
157                         dm = fabs(this.oldvelocity.z) - vlen(this.velocity);
158                 else
159                         dm = vlen(this.oldvelocity) - vlen(this.velocity);
160                 if (IS_DEAD(this))
161                         dm = (dm - autocvar_g_balance_falldamage_deadminspeed) * autocvar_g_balance_falldamage_factor;
162                 else
163                         dm = min((dm - autocvar_g_balance_falldamage_minspeed) * autocvar_g_balance_falldamage_factor, autocvar_g_balance_falldamage_maxdamage);
164                 if (dm > 0)
165                 {
166                         tracebox(this.origin, this.mins, this.maxs, this.origin - '0 0 1', MOVE_NOMONSTERS, this);
167                         if (!(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NODAMAGE))
168                                 Damage (this, NULL, NULL, dm, DEATH_FALL.m_id, DMG_NOWEP, this.origin, '0 0 0');
169                 }
170         }
171
172         if(autocvar_g_maxspeed > 0 && vdist(this.velocity, >, autocvar_g_maxspeed))
173                 Damage (this, NULL, NULL, 100000, DEATH_SHOOTING_STAR.m_id, DMG_NOWEP, this.origin, '0 0 0');
174 }
175
176 void CreatureFrame_All()
177 {
178         if(game_stopped || time < game_starttime)
179                 return;
180
181         IL_EACH(g_damagedbycontents, it.damagedbycontents,
182         {
183                 if (it.move_movetype == MOVETYPE_NOCLIP) continue;
184                 CreatureFrame_Liquids(it);
185                 CreatureFrame_FallDamage(it);
186                 it.oldvelocity = it.velocity;
187         });
188 }
189
190 void Pause_TryPause_Dedicated(entity this)
191 {
192         if (player_count == 0)
193                 setpause(1);
194 }
195
196 void Pause_TryPause()
197 {
198         int n = 0, p = 0;
199         FOREACH_CLIENT(IS_REAL_CLIENT(it), {
200                 if (PHYS_INPUT_BUTTON_CHAT(it)) ++p;
201                 ++n;
202         });
203         if (!n) return;
204         if (n == p)
205                 setpause(1);
206         else
207                 setpause(0);
208 }
209
210 void SV_PausedTic(float elapsedtime)
211 {
212         if (!server_is_dedicated)
213         {
214                 if (autocvar_sv_autopause)
215                         Pause_TryPause();
216                 else
217                         setpause(0);
218         }
219 }
220
221 void dedicated_print(string input)
222 {
223         if (server_is_dedicated) print(input);
224 }
225
226 void make_safe_for_remove(entity e)
227 {
228         if (e.initialize_entity)
229         {
230                 entity ent, prev = NULL;
231                 for (ent = initialize_entity_first; ent; )
232                 {
233                         if ((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
234                         {
235                                 //print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
236                                 // skip it in linked list
237                                 if (prev)
238                                 {
239                                         prev.initialize_entity_next = ent.initialize_entity_next;
240                                         ent = prev.initialize_entity_next;
241                                 }
242                                 else
243                                 {
244                                         initialize_entity_first = ent.initialize_entity_next;
245                                         ent = initialize_entity_first;
246                                 }
247                         }
248                         else
249                         {
250                                 prev = ent;
251                                 ent = ent.initialize_entity_next;
252                         }
253                 }
254         }
255 }
256
257 void remove_except_protected(entity e)
258 {
259         if(e.remove_except_protected_forbidden)
260                 error("not allowed to remove this at this point");
261         builtin_remove(e);
262 }
263
264 void remove_unsafely(entity e)
265 {
266         if(e.classname == "spike")
267                 error("Removing spikes is forbidden (crylink bug), please report");
268         builtin_remove(e);
269 }
270
271 void remove_safely(entity e)
272 {
273         make_safe_for_remove(e);
274         builtin_remove(e);
275 }
276
277 /*
278 =============
279 StartFrame
280
281 Called before each frame by the server
282 =============
283 */
284
285 bool game_delay_last;
286
287 void systems_update();
288 void sys_phys_update(entity this, float dt);
289 void StartFrame()
290 {
291         FOREACH_CLIENT(IS_FAKE_CLIENT(it),
292         {
293                 // DP calls these for real clients only
294                 sys_phys_update(it, frametime); // called by SV_PlayerPhysics for players
295                 PlayerPreThink(it);
296         });
297
298         execute_next_frame();
299         if (autocvar_sv_autopause && !server_is_dedicated) Pause_TryPause();
300
301         delete_fn = remove_unsafely; // not during spawning!
302         serverprevtime = servertime;
303         servertime = time;
304         serverframetime = frametime;
305
306 #ifdef PROFILING
307         if(time > client_cefc_accumulatortime + 1)
308         {
309                 float t = client_cefc_accumulator / (time - client_cefc_accumulatortime);
310                 int c_seeing = 0;
311                 int c_seen = 0;
312                 FOREACH_CLIENT(true, {
313                         if(IS_REAL_CLIENT(it))
314                                 ++c_seeing;
315                         if(IS_PLAYER(it))
316                                 ++c_seen;
317                 });
318                 LOG_INFO(
319                         "CEFC time: ", ftos(t * 1000), "ms; ",
320                         "CEFC calls per second: ", ftos(c_seeing * (c_seen - 1) / t), "; ",
321                         "CEFC 100% load at: ", ftos(solve_quadratic(t, -t, -1) * '0 1 0')
322                 );
323                 client_cefc_accumulatortime = time;
324                 client_cefc_accumulator = 0;
325         }
326 #endif
327
328         IL_EACH(g_projectiles, it.csqcprojectile_clientanimate, CSQCProjectile_Check(it));
329
330         if (RedirectionThink()) return;
331
332         UncustomizeEntitiesRun();
333         InitializeEntitiesRun();
334
335         WarpZone_StartFrame();
336
337         sys_frametime = autocvar_sys_ticrate * autocvar_slowmo;
338         if (sys_frametime <= 0) sys_frametime = 1.0 / 60.0; // somewhat safe fallback
339
340         if (timeout_status == TIMEOUT_LEADTIME) // just before the timeout (when timeout_status will be TIMEOUT_ACTIVE)
341                 orig_slowmo = autocvar_slowmo; // slowmo will be restored after the timeout
342
343         // detect when the pre-game countdown (if any) has ended and the game has started
344         bool game_delay = (time < game_starttime);
345         if (autocvar_sv_eventlog && game_delay_last && !game_delay)
346                 GameLogEcho(":startdelay_ended");
347         game_delay_last = game_delay;
348
349         CreatureFrame_All();
350         CheckRules_World();
351
352         if (warmup_stage && !game_stopped && warmup_limit > 0 && time - game_starttime >= warmup_limit) {
353                 ReadyRestart(true);
354                 return;
355         }
356
357         bot_serverframe();
358         anticheat_startframe();
359         MUTATOR_CALLHOOK(SV_StartFrame);
360
361         GlobalStats_updateglobal();
362         FOREACH_CLIENT(true,
363         {
364                 GlobalStats_update(it);
365                 if (IS_FAKE_CLIENT(it))
366                         PlayerPostThink(it); // DP calls this for real clients only
367         });
368 }
369
370 .vector originjitter;
371 .vector anglesjitter;
372 .float anglejitter;
373 .string gametypefilter;
374 .string cvarfilter;
375
376 void SV_OnEntityPreSpawnFunction(entity this)
377 {
378         if (this)
379         if (this.gametypefilter != "")
380         if (!isGametypeInFilter(MapInfo_LoadedGametype, teamplay, have_team_spawns, this.gametypefilter))
381         {
382                 delete(this);
383                 return;
384         }
385         if (this.cvarfilter != "" && !expr_evaluate(this.cvarfilter)) {
386                 delete(this);
387                 return;
388         }
389
390         if (q3compat && DoesQ3ARemoveThisEntity(this)) {
391                 delete(this);
392                 return;
393         }
394
395         set_movetype(this, this.movetype);
396
397         if (this.monster_attack) {
398                 IL_PUSH(g_monster_targets, this);
399         }
400
401         // support special -1 and -2 angle from radiant
402         if (this.angles == '0 -1 0') {
403                 this.angles = '-90 0 0';
404         } else if (this.angles == '0 -2 0') {
405                 this.angles = '+90 0 0';
406         }
407
408         #define X(out, in) MACRO_BEGIN \
409                 if (in != 0) { out = out + (random() * 2 - 1) * in; } \
410         MACRO_END
411         X(this.origin.x, this.originjitter.x); X(this.origin.y, this.originjitter.y); X(this.origin.z, this.originjitter.z);
412         X(this.angles.x, this.anglesjitter.x); X(this.angles.y, this.anglesjitter.y); X(this.angles.z, this.anglesjitter.z);
413         X(this.angles.y, this.anglejitter);
414         #undef X
415
416         if (MUTATOR_CALLHOOK(OnEntityPreSpawn, this)) {
417                 delete(this);
418                 return;
419         }
420 }
421
422 string GetField_fullspawndata(entity e, string f, ...)
423 /* Retrieves the value of a map entity field from fullspawndata
424  * This bypasses field value changes made by the engine,
425  * eg string-to-float and escape sequence substitution.
426  *
427  * Avoids the need to declare fields just to read them once :)
428  *
429  * Returns the last instance of the field to match DarkPlaces behaviour.
430  * Path support: converts \ to / and tests the file if a third (bool, true) arg is passed.
431  * Returns string_null if the entity does not have the field, or the file is not in the VFS.
432  *
433  * FIXME: entities with //comments are not supported.
434  */
435 {
436         string v = string_null;
437
438         if (!e.fullspawndata)
439         {
440                 //LOG_WARNF("^1EDICT %s (classname %s) has no fullspawndata, engine lacks support?", ftos(num_for_edict(e)), e.classname);
441                 return v;
442         }
443
444         if (strstrofs(e.fullspawndata, "//", 0) >= 0)
445         {
446                 // tokenize and tokenize_console return early if "//" is reached,
447                 // which can leave an odd number of tokens and break key:value pairing.
448                 LOG_WARNF("^1EDICT %s fullspawndata contains unsupported //comment^7%s", ftos(num_for_edict(e)), e.fullspawndata);
449                 return v;
450         }
451
452         //print(sprintf("%s(EDICT %s, FIELD %s)\n", __FUNC__, ftos(num_for_edict(e)), f));
453         //print(strcat("FULLSPAWNDATA:", e.fullspawndata, "\n"));
454
455         // tokenize treats \ as an escape, but tokenize_console returns the required literal
456         for (int t = tokenize_console(e.fullspawndata) - 3; t > 0; t -= 2)
457         {
458                 //print(sprintf("\tTOKEN %s:%s\t%s:%s\n", ftos(t), ftos(t + 1), argv(t), argv(t + 1)));
459                 if (argv(t) == f)
460                 {
461                         v = argv(t + 1);
462                         break;
463                 }
464         }
465
466         //print(strcat("RESULT: ", v, "\n\n"));
467
468         if (v && ...(0, bool) == true)
469         {
470                 v = strreplace("\\", "/", v);
471                 if (whichpack(v) == "")
472                         return string_null;
473         }
474
475         return v;
476 }
477
478 /*
479 =============
480 FindFileInMapPack
481
482 Returns the first matching VFS file path that exists in the current map's pack.
483 Returns string_null if no files match or the map isn't packaged.
484 =============
485 */
486 string FindFileInMapPack(string pattern)
487 {
488         if(!checkextension("DP_QC_FS_SEARCH_PACKFILE"))
489                 return string_null;
490
491         string base_pack = whichpack(strcat("maps/", mapname, ".bsp"));
492         if(base_pack == "" || !base_pack) // this map isn't packaged or there was an error
493                 return string_null;
494
495         int glob = search_packfile_begin(pattern, true, true, base_pack);
496         if(glob < 0)
497                 return string_null;
498
499         string file = search_getfilename(glob, 0);
500         search_end(glob);
501         return file;
502 }
503
504 void WarpZone_PostInitialize_Callback()
505 {
506         // create waypoint links for warpzones
507         entity tracetest_ent = spawn();
508         setsize(tracetest_ent, PL_MIN_CONST, PL_MAX_CONST);
509         tracetest_ent.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_PLAYERCLIP | DPCONTENTS_BOTCLIP;
510         //for(entity e = warpzone_first; e; e = e.warpzone_next)
511         for(entity e = NULL; (e = find(e, classname, "trigger_warpzone")); )
512                 waypoint_spawnforteleporter_wz(e, tracetest_ent);
513         delete(tracetest_ent);
514 }
515
516 /** engine callback */
517 void URI_Get_Callback(float id, float status, string data)
518 {
519         if(url_URI_Get_Callback(id, status, data))
520         {
521                 // handled
522         }
523         else if (id == URI_GET_DISCARD)
524         {
525                 // discard
526         }
527         else if (id >= URI_GET_CURL && id <= URI_GET_CURL_END)
528         {
529                 // sv_cmd curl
530                 Curl_URI_Get_Callback(id, status, data);
531         }
532         else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
533         {
534                 // online ban list
535                 OnlineBanList_URI_Get_Callback(id, status, data);
536         }
537         else if (MUTATOR_CALLHOOK(URI_GetCallback, id, status, data))
538         {
539                 // handled by a mutator
540         }
541         else
542         {
543                 LOG_INFO("Received HTTP request data for an invalid id ", ftos(id), ".");
544         }
545 }
546
547 /*
548 ==================
549 main
550
551 unused but required by the engine
552 ==================
553 */
554 void main ()
555 {
556
557 }