]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/items/items.qc
Merge branch 'master' into bones_was_here/q3compat
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / items / items.qc
1 #include "items.qh"
2
3 #include <common/constants.qh>
4 #include <common/deathtypes/all.qh>
5 #include <common/gamemodes/gamemode/cts/cts.qh>
6 #include <common/items/_mod.qh>
7 #include <common/mapobjects/subs.qh>
8 #include <common/mapobjects/triggers.qh>
9 #include <common/monsters/_mod.qh>
10 #include <common/mutators/mutator/buffs/buffs.qh>
11 #include <common/mutators/mutator/buffs/sv_buffs.qh>
12 #include <common/notifications/all.qh>
13 #include <common/util.qh>
14 #include <common/weapons/_all.qh>
15 #include <common/wepent.qh>
16 #include <lib/warpzone/common.qh>
17 #include <lib/warpzone/util_server.qh>
18 #include <server/bot/api.qh>
19 #include <server/command/vote.qh>
20 #include <server/damage.qh>
21 #include <server/mutators/_mod.qh>
22 #include <server/teamplay.qh>
23 #include <server/weapons/common.qh>
24 #include <server/weapons/selection.qh>
25 #include <server/weapons/weaponsystem.qh>
26 #include <server/world.qh>
27
28 bool ItemSend(entity this, entity to, int sf)
29 {
30         if(this.gravity)
31                 sf |= ISF_DROP;
32         else
33                 sf &= ~ISF_DROP;
34
35         WriteHeader(MSG_ENTITY, ENT_CLIENT_ITEM);
36         WriteByte(MSG_ENTITY, sf);
37
38         //WriteByte(MSG_ENTITY, this.cnt);
39         if(sf & ISF_LOCATION)
40         {
41                 WriteVector(MSG_ENTITY, this.origin);
42         }
43
44         if(sf & ISF_ANGLES)
45         {
46                 WriteAngleVector(MSG_ENTITY, this.angles);
47         }
48
49         // sets size on the client, unused on server
50         //if(sf & ISF_SIZE)
51
52         if(sf & ISF_STATUS)
53                 WriteByte(MSG_ENTITY, this.ItemStatus);
54
55         if(sf & ISF_MODEL)
56         {
57                 WriteShort(MSG_ENTITY, this.fade_end);
58                 WriteShort(MSG_ENTITY, this.fade_start);
59
60                 if(this.mdl == "")
61                         LOG_TRACE("^1WARNING!^7 this.mdl is unset for item ", this.classname, "expect a crash just about now");
62
63                 WriteString(MSG_ENTITY, this.mdl);
64         }
65
66
67         if(sf & ISF_COLORMAP)
68         {
69                 WriteShort(MSG_ENTITY, this.colormap);
70                 WriteByte(MSG_ENTITY, this.glowmod.x * 255.0);
71                 WriteByte(MSG_ENTITY, this.glowmod.y * 255.0);
72                 WriteByte(MSG_ENTITY, this.glowmod.z * 255.0);
73         }
74
75         if(sf & ISF_DROP)
76         {
77                 WriteVector(MSG_ENTITY, this.velocity);
78         }
79
80         return true;
81 }
82
83 void ItemUpdate(entity this)
84 {
85         this.oldorigin = this.origin;
86         this.SendFlags |= ISF_LOCATION;
87 }
88
89 void UpdateItemAfterTeleport(entity this)
90 {
91         if(getSendEntity(this) == ItemSend)
92                 ItemUpdate(this);
93 }
94
95 bool have_pickup_item(entity this)
96 {
97         if(this.itemdef.instanceOfPowerup)
98         {
99                 if(autocvar_g_powerups > 0)
100                         return true;
101                 if(autocvar_g_powerups == 0)
102                         return false;
103         }
104         else
105         {
106                 if(autocvar_g_pickup_items > 0)
107                         return true;
108                 if(autocvar_g_pickup_items == 0)
109                         return false;
110                 if(g_weaponarena)
111                         if(STAT(WEAPONS, this) || this.itemdef.instanceOfAmmo) // no item or ammo pickups in weaponarena
112                                 return false;
113         }
114         return true;
115 }
116
117 void Item_Show(entity e, int mode)
118 {
119         e.effects &= ~(EF_ADDITIVE | EF_STARDUST | EF_FULLBRIGHT | EF_NODEPTHTEST);
120         e.ItemStatus &= ~ITS_STAYWEP;
121         entity def = e.itemdef;
122         if (mode > 0)
123         {
124                 // make the item look normal, and be touchable
125                 e.model = e.mdl;
126                 e.solid = SOLID_TRIGGER;
127                 e.spawnshieldtime = 1;
128                 e.ItemStatus |= ITS_AVAILABLE;
129         }
130         else if (mode < 0)
131         {
132                 // hide the item completely
133                 e.model = string_null;
134                 e.solid = SOLID_NOT;
135                 e.spawnshieldtime = 1;
136                 e.ItemStatus &= ~ITS_AVAILABLE;
137         }
138         else
139         {
140                 bool nostay = def.instanceOfWeaponPickup ? !!(def.m_weapon.m_wepset & WEPSET_SUPERWEAPONS) : false // no weapon-stay on superweapons
141                         || e.team // weapon stay isn't supported for teamed weapons
142                         ;
143                 if(def.instanceOfWeaponPickup && !nostay && g_weapon_stay)
144                 {
145                         // make the item translucent and not touchable
146                         e.model = e.mdl;
147                         e.solid = SOLID_TRIGGER; // can STILL be picked up!
148                         e.effects |= EF_STARDUST;
149                         e.spawnshieldtime = 0; // field indicates whether picking it up may give you anything other than the weapon
150                         e.ItemStatus |= (ITS_AVAILABLE | ITS_STAYWEP);
151                 }
152                 else
153                 {
154                         //setmodel(e, "null");
155                         e.solid = SOLID_NOT;
156                         e.colormod = '0 0 0';
157                         //e.glowmod = e.colormod;
158                         e.spawnshieldtime = 1;
159                         e.ItemStatus &= ~ITS_AVAILABLE;
160                 }
161         }
162
163         if (def.m_glow)
164                 e.ItemStatus |= ITS_GLOW;
165
166         if (autocvar_g_nodepthtestitems)
167                 e.effects |= EF_NODEPTHTEST;
168
169         if (autocvar_g_fullbrightitems)
170                 e.ItemStatus |= ITS_ALLOWFB;
171         else
172                 e.ItemStatus &= ~ITS_ALLOWFB;
173
174         if (autocvar_sv_simple_items)
175                 e.ItemStatus |= ITS_ALLOWSI;
176
177         // relink entity (because solid may have changed)
178         setorigin(e, e.origin);
179         e.SendFlags |= ISF_STATUS;
180 }
181
182 void Item_Think(entity this)
183 {
184         this.nextthink = time;
185         if(this.origin != this.oldorigin)
186                 ItemUpdate(this);
187 }
188
189 bool Item_ItemsTime_SpectatorOnly(GameItem it);
190 bool Item_ItemsTime_Allow(GameItem it);
191 float Item_ItemsTime_UpdateTime(entity e, float t);
192 void Item_ItemsTime_SetTime(entity e, float t);
193 void Item_ItemsTime_SetTimesForAllPlayers();
194
195 void Item_Respawn(entity this)
196 {
197         Item_Show(this, 1);
198         sound(this, CH_TRIGGER, this.itemdef.m_respawnsound, VOL_BASE, ATTEN_NORM);     // play respawn sound
199         setorigin(this, this.origin);
200
201         if (Item_ItemsTime_Allow(this.itemdef) || (STAT(WEAPONS, this) & WEPSET_SUPERWEAPONS))
202         {
203                 float t = Item_ItemsTime_UpdateTime(this, 0);
204                 Item_ItemsTime_SetTime(this, t);
205                 Item_ItemsTime_SetTimesForAllPlayers();
206         }
207
208         setthink(this, Item_Think);
209         this.nextthink = time;
210
211         //Send_Effect(EFFECT_ITEM_RESPAWN, this.origin + this.mins_z * '0 0 1' + '0 0 48', '0 0 0', 1);
212         Send_Effect(EFFECT_ITEM_RESPAWN, CENTER_OR_VIEWOFS(this), '0 0 0', 1);
213 }
214
215 void Item_RespawnCountdown(entity this)
216 {
217         if(this.item_respawncounter >= ITEM_RESPAWN_TICKS)
218         {
219                 if(this.waypointsprite_attached)
220                         WaypointSprite_Kill(this.waypointsprite_attached);
221                 Item_Respawn(this);
222         }
223         else
224         {
225                 this.nextthink = time + 1;
226                 this.item_respawncounter += 1;
227                 if(this.item_respawncounter == 1)
228                 {
229                         do {
230                                 {
231                                         entity wi = REGISTRY_GET(Weapons, this.weapon);
232                                         if (wi != WEP_Null) {
233                                                 entity wp = WaypointSprite_Spawn(WP_Weapon, 0, 0, this, '0 0 64', NULL, 0, this, waypointsprite_attached, true, RADARICON_Weapon);
234                                                 wp.wp_extra = wi.m_id;
235                                                 break;
236                                         }
237                                 }
238                                 {
239                                         entity ii = this.itemdef;
240                                         if (ii != NULL) {
241                                                 entity wp = WaypointSprite_Spawn(WP_Item, 0, 0, this, '0 0 64', NULL, 0, this, waypointsprite_attached, true, RADARICON_Item);
242                                                 wp.wp_extra = ii.m_id;
243                                                 break;
244                                         }
245                                 }
246                         } while (0);
247                         bool mutator_returnvalue = MUTATOR_CALLHOOK(Item_RespawnCountdown, this);
248             if(this.waypointsprite_attached)
249             {
250                 GameItem def = this.itemdef;
251                 if (Item_ItemsTime_SpectatorOnly(def) && !mutator_returnvalue)
252                     WaypointSprite_UpdateRule(this.waypointsprite_attached, 0, SPRITERULE_SPECTATOR);
253                 WaypointSprite_UpdateBuildFinished(this.waypointsprite_attached, time + ITEM_RESPAWN_TICKS);
254             }
255                 }
256
257                 if(this.waypointsprite_attached)
258                 {
259                         FOREACH_CLIENT(IS_REAL_CLIENT(it), {
260                                 if(this.waypointsprite_attached.waypointsprite_visible_for_player(this.waypointsprite_attached, it, it))
261                                 {
262                                         msg_entity = it;
263                                         soundto(MSG_ONE, this, CH_TRIGGER, SND(ITEMRESPAWNCOUNTDOWN), VOL_BASE, ATTEN_NORM, 0); // play respawn sound
264                                 }
265                         });
266
267                         WaypointSprite_Ping(this.waypointsprite_attached);
268                         //WaypointSprite_UpdateHealth(this.waypointsprite_attached, this.item_respawncounter);
269                 }
270         }
271 }
272
273 void Item_RespawnThink(entity this)
274 {
275         this.nextthink = time;
276         if(this.origin != this.oldorigin)
277                 ItemUpdate(this);
278
279         if(time >= this.wait)
280                 Item_Respawn(this);
281 }
282
283 void Item_ScheduleRespawnIn(entity e, float t)
284 {
285         // if the respawn time is longer than 10 seconds, show a waypoint, otherwise, just respawn normally
286         if ((Item_ItemsTime_Allow(e.itemdef) || (STAT(WEAPONS, e) & WEPSET_SUPERWEAPONS) || MUTATOR_CALLHOOK(Item_ScheduleRespawn, e, t)) && (t - ITEM_RESPAWN_TICKS) > 0)
287         {
288                 setthink(e, Item_RespawnCountdown);
289                 e.nextthink = time + max(0, t - ITEM_RESPAWN_TICKS);
290                 e.scheduledrespawntime = e.nextthink + ITEM_RESPAWN_TICKS;
291                 e.item_respawncounter = 0;
292                 if(Item_ItemsTime_Allow(e.itemdef) || (STAT(WEAPONS, e) & WEPSET_SUPERWEAPONS))
293                 {
294                         t = Item_ItemsTime_UpdateTime(e, e.scheduledrespawntime);
295                         Item_ItemsTime_SetTime(e, t);
296                         Item_ItemsTime_SetTimesForAllPlayers();
297                 }
298         }
299         else
300         {
301                 setthink(e, Item_RespawnThink);
302                 e.nextthink = time;
303                 e.scheduledrespawntime = time + t;
304                 e.wait = time + t;
305
306                 if(Item_ItemsTime_Allow(e.itemdef) || (STAT(WEAPONS, e) & WEPSET_SUPERWEAPONS))
307                 {
308                         t = Item_ItemsTime_UpdateTime(e, e.scheduledrespawntime);
309                         Item_ItemsTime_SetTime(e, t);
310                         Item_ItemsTime_SetTimesForAllPlayers();
311                 }
312         }
313 }
314
315 AUTOCVAR(g_pickup_respawntime_scaling_reciprocal, float, 0.0, "Multiply respawn time by `reciprocal / (p + offset) + linear` where `p` is the current number of players, takes effect with 2 or more players present, `reciprocal` (with `offset` and `linear` set to 0) can be used to achieve a constant number of items spawned *per player*");
316 AUTOCVAR(g_pickup_respawntime_scaling_offset, float, 0.0, "Multiply respawn time by `reciprocal / (p + offset) + linear` where `p` is the current number of players, takes effect with 2 or more players present, `offset` offsets the curve left or right - the results are not intuitive and I recommend plotting the respawn time and the number of items per player to see what's happening");
317 AUTOCVAR(g_pickup_respawntime_scaling_linear, float, 1.0, "Multiply respawn time by `reciprocal / (p + offset) + linear` where `p` is the current number of players, takes effect with 2 or more players present, `linear` can be used to simply scale the respawn time linearly");
318
319 /// Adjust respawn time according to the number of players.
320 float adjust_respawntime(float normal_respawntime) {
321         float r = autocvar_g_pickup_respawntime_scaling_reciprocal;
322         float o = autocvar_g_pickup_respawntime_scaling_offset;
323         float l = autocvar_g_pickup_respawntime_scaling_linear;
324
325         if (r == 0 && l == 1) {
326                 return normal_respawntime;
327         }
328
329         entity balance = TeamBalance_CheckAllowedTeams(NULL);
330         TeamBalance_GetTeamCounts(balance, NULL);
331         int players = 0;
332         for (int i = 1; i <= NUM_TEAMS; ++i)
333         {
334                 if (TeamBalance_IsTeamAllowed(balance, i))
335                 {
336                         players += TeamBalance_GetNumberOfPlayers(balance, i);
337                 }
338         }
339         TeamBalance_Destroy(balance);
340
341         if (players >= 2) {
342                 return normal_respawntime * (r / (players + o) + l);
343         } else {
344                 return normal_respawntime;
345         }
346 }
347
348 void Item_ScheduleRespawn(entity e)
349 {
350         if(e.respawntime > 0)
351         {
352                 Item_Show(e, 0);
353
354                 float adjusted_respawntime = adjust_respawntime(e.respawntime);
355                 //LOG_INFOF("item %s will respawn in %f", e.classname, adjusted_respawntime);
356
357                 // range: adjusted_respawntime - respawntimejitter .. adjusted_respawntime + respawntimejitter
358                 float respawn_in = adjusted_respawntime + crandom() * e.respawntimejitter;
359                 Item_ScheduleRespawnIn(e, respawn_in);
360         }
361         else // if respawntime is -1, this item does not respawn
362                 Item_Show(e, -1);
363 }
364
365 AUTOCVAR(g_pickup_respawntime_initial_random, int, 1,
366         "For items that don't start spawned: 0: spawn after their normal respawntime; 1: spawn after `random * respawntime` with the *same* random; 2: same as 1 but each item has separate random");
367
368 void Item_ScheduleInitialRespawn(entity e)
369 {
370         Item_Show(e, 0);
371
372         float spawn_in;
373         if (autocvar_g_pickup_respawntime_initial_random == 0)
374         {
375                 // range: respawntime .. respawntime + respawntimejitter
376                 spawn_in = e.respawntime + random() * e.respawntimejitter;
377         }
378         else
379         {
380                 float rnd;
381                 if (autocvar_g_pickup_respawntime_initial_random == 1)
382                 {
383                         static float shared_random = 0;
384                         // NOTE this code works only if items are scheduled at the same time (normal case)
385                         // NOTE2 random() can't return exactly 1 so this check always work as intended
386                         if (!shared_random || floor(time) > shared_random)
387                                 shared_random = floor(time) + random();
388                         rnd = shared_random - floor(time);
389                 }
390                 else
391                         rnd = random();
392
393                 // range:
394                 // if respawntime >= ITEM_RESPAWN_TICKS: ITEM_RESPAWN_TICKS .. respawntime + respawntimejitter
395                 // else: 0 .. ITEM_RESPAWN_TICKS
396                 // this is to prevent powerups spawning unexpectedly without waypoints
397                 spawn_in = ITEM_RESPAWN_TICKS + rnd * (e.respawntime + e.respawntimejitter - ITEM_RESPAWN_TICKS);
398         }
399
400         Item_ScheduleRespawnIn(e, max(0, game_starttime - time) + ((e.respawntimestart) ? e.respawntimestart : spawn_in));
401 }
402
403 void GiveRandomWeapons(entity receiver, int num_weapons, string weapon_names,
404         entity ammo_entity)
405 {
406         if (num_weapons == 0)
407         {
408                 return;
409         }
410         int num_potential_weapons = tokenize_console(weapon_names);
411         for (int give_attempt = 0; give_attempt < num_weapons; ++give_attempt)
412         {
413                 RandomSelection_Init();
414                 for (int weapon_index = 0; weapon_index < num_potential_weapons;
415                         ++weapon_index)
416                 {
417                         string weapon = argv(weapon_index);
418                         FOREACH(Weapons, it != WEP_Null,
419                         {
420                                 // Finding a weapon which player doesn't have.
421                                 if (!(STAT(WEAPONS, receiver) & it.m_wepset) && (it.netname == weapon))
422                                 {
423                                         RandomSelection_AddEnt(it, 1, 1);
424                                         break;
425                                 }
426                         });
427                 }
428                 if (RandomSelection_chosen_ent == NULL)
429                 {
430                         return;
431                 }
432                 STAT(WEAPONS, receiver) |= RandomSelection_chosen_ent.m_wepset;
433                 if (RandomSelection_chosen_ent.ammo_type == RES_NONE)
434                 {
435                         continue;
436                 }
437                 if (GetResource(receiver,
438                         RandomSelection_chosen_ent.ammo_type) != 0)
439                 {
440                         continue;
441                 }
442                 GiveResource(receiver, RandomSelection_chosen_ent.ammo_type,
443                         GetResource(ammo_entity,
444                         RandomSelection_chosen_ent.ammo_type));
445         }
446 }
447
448 bool Item_GiveAmmoTo(entity item, entity player, int res_type, float ammomax)
449 {
450         float amount = GetResource(item, res_type);
451         if (amount == 0)
452         {
453                 return false;
454         }
455         float player_amount = GetResource(player, res_type);
456         if (item.spawnshieldtime)
457         {
458                 if ((player_amount >= ammomax) && (item.pickup_anyway <= 0))
459                         return false;
460         }
461         else if (g_weapon_stay == 2)
462         {
463                 ammomax = min(amount, ammomax);
464                 if(player_amount >= ammomax)
465                         return false;
466         }
467         else
468                 return false;
469         if (amount < 0)
470                 TakeResourceWithLimit(player, res_type, -amount, ammomax);
471         else
472                 GiveResourceWithLimit(player, res_type, amount, ammomax);
473         return true;
474 }
475
476 bool Item_GiveTo(entity item, entity player)
477 {
478         // if nothing happens to player, just return without taking the item
479         int _switchweapon = 0;
480         // in case the player has autoswitch enabled do the following:
481         // if the player is using their best weapon before items are given, they
482         // probably want to switch to an even better weapon after items are given
483
484         if(CS_CVAR(player).autoswitch)
485         {
486                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
487                 {
488                         .entity weaponentity = weaponentities[slot];
489                         if(player.(weaponentity).m_weapon != WEP_Null || slot == 0)
490                         {
491                                 if(player.(weaponentity).m_switchweapon == w_getbestweapon(player, weaponentity))
492                                         _switchweapon |= BIT(slot);
493
494                                 if(!(STAT(WEAPONS, player) & WepSet_FromWeapon(player.(weaponentity).m_switchweapon)))
495                                         _switchweapon |= BIT(slot);
496                         }
497                 }
498         }
499         bool pickedup = false;
500         pickedup |= Item_GiveAmmoTo(item, player, RES_HEALTH, item.max_health);
501         pickedup |= Item_GiveAmmoTo(item, player, RES_ARMOR, item.max_armorvalue);
502         pickedup |= Item_GiveAmmoTo(item, player, RES_SHELLS, g_pickup_shells_max);
503         pickedup |= Item_GiveAmmoTo(item, player, RES_BULLETS, g_pickup_nails_max);
504         pickedup |= Item_GiveAmmoTo(item, player, RES_ROCKETS, g_pickup_rockets_max);
505         pickedup |= Item_GiveAmmoTo(item, player, RES_CELLS, g_pickup_cells_max);
506         pickedup |= Item_GiveAmmoTo(item, player, RES_PLASMA, g_pickup_plasma_max);
507         pickedup |= Item_GiveAmmoTo(item, player, RES_FUEL, g_pickup_fuel_max);
508         if (item.itemdef.instanceOfWeaponPickup)
509         {
510                 WepSet w;
511                 w = STAT(WEAPONS, item);
512                 w &= ~STAT(WEAPONS, player);
513
514                 if (w || (item.spawnshieldtime && item.pickup_anyway > 0))
515                 {
516                         pickedup = true;
517                         FOREACH(Weapons, it != WEP_Null, {
518                                 if(w & (it.m_wepset))
519                                 {
520                                         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
521                                         {
522                                                 .entity weaponentity = weaponentities[slot];
523                                                 if(player.(weaponentity).m_weapon != WEP_Null || slot == 0)
524                                                         W_DropEvent(wr_pickup, player, it.m_id, item, weaponentity);
525                                         }
526                                         W_GiveWeapon(player, it.m_id);
527                                 }
528                         });
529                 }
530         }
531
532         if (item.itemdef.instanceOfPowerup)
533         {
534                 if ((item.itemdef == ITEM_JetpackRegen) && !(player.items & IT_FUEL_REGEN))
535                         Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_ITEM_FUELREGEN_GOT);
536                 else if ((item.itemdef == ITEM_Jetpack) && !(player.items & IT_JETPACK))
537                         Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_ITEM_JETPACK_GOT);
538         }
539
540         int its;
541         if((its = (item.items - (item.items & player.items)) & IT_PICKUPMASK))
542         {
543                 pickedup = true;
544                 player.items |= its;
545                 // TODO: we probably want to show a message in the console, but not this one!
546                 //Send_Notification(NOTIF_ONE, player, MSG_INFO, INFO_ITEM_WEAPON_GOT, item.netname);
547         }
548
549         if (item.strength_finished)
550         {
551                 pickedup = true;
552                 STAT(STRENGTH_FINISHED, player) = max(STAT(STRENGTH_FINISHED, player), time) + item.strength_finished;
553         }
554         if (item.invincible_finished)
555         {
556                 pickedup = true;
557                 STAT(INVINCIBLE_FINISHED, player) = max(STAT(INVINCIBLE_FINISHED, player), time) + item.invincible_finished;
558         }
559         if (item.superweapons_finished)
560         {
561                 pickedup = true;
562                 STAT(SUPERWEAPONS_FINISHED, player) = max(STAT(SUPERWEAPONS_FINISHED, player), time) + item.superweapons_finished;
563         }
564
565         // always eat teamed entities
566         if(item.team)
567                 pickedup = true;
568
569         if (!pickedup)
570                 return false;
571
572         // crude hack to enforce switching weapons
573         if(g_cts && item.itemdef.instanceOfWeaponPickup && !CS_CVAR(player).cvar_cl_cts_noautoswitch)
574         {
575                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
576                 {
577                         .entity weaponentity = weaponentities[slot];
578                         if(player.(weaponentity).m_weapon != WEP_Null || slot == 0)
579                                 W_SwitchWeapon_Force(player, REGISTRY_GET(Weapons, item.weapon), weaponentity);
580                 }
581                 return true;
582         }
583
584         if(_switchweapon)
585         {
586                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
587                 {
588                         .entity weaponentity = weaponentities[slot];
589                         if(_switchweapon & BIT(slot))
590                         if(player.(weaponentity).m_switchweapon != w_getbestweapon(player, weaponentity))
591                                 W_SwitchWeapon_Force(player, w_getbestweapon(player, weaponentity), weaponentity);
592                 }
593         }
594
595         return true;
596 }
597
598 void Item_Touch(entity this, entity toucher)
599 {
600         // remove the item if it's currnetly in a NODROP brush or hits a NOIMPACT surface (such as sky)
601         if (Item_IsLoot(this))
602         {
603                 if (ITEM_TOUCH_NEEDKILL())
604                 {
605                         delete(this);
606                         return;
607                 }
608         }
609
610         if(!(toucher.flags & FL_PICKUPITEMS)
611         || STAT(FROZEN, toucher)
612         || IS_DEAD(toucher)
613         || (this.solid != SOLID_TRIGGER)
614         || (this.owner == toucher)
615         || (time < this.item_spawnshieldtime)
616         ) { return; }
617
618         switch (MUTATOR_CALLHOOK(ItemTouch, this, toucher))
619         {
620                 case MUT_ITEMTOUCH_RETURN: { return; }
621                 case MUT_ITEMTOUCH_PICKUP: { toucher = M_ARGV(1, entity); goto pickup; }
622         }
623
624         toucher = M_ARGV(1, entity);
625
626         if (Item_IsExpiring(this))
627         {
628                 this.strength_finished = max(0, this.strength_finished - time);
629                 this.invincible_finished = max(0, this.invincible_finished - time);
630                 this.superweapons_finished = max(0, this.superweapons_finished - time);
631         }
632         bool gave = ITEM_HANDLE(Pickup, this.itemdef, this, toucher);
633         if (!gave)
634         {
635                 if (Item_IsExpiring(this))
636                 {
637                         // undo what we did above
638                         this.strength_finished += time;
639                         this.invincible_finished += time;
640                         this.superweapons_finished += time;
641                 }
642                 return;
643         }
644
645 LABEL(pickup)
646
647         if(this.target && this.target != "" && this.target != "###item###") // defrag support
648                 SUB_UseTargets(this, toucher, NULL);
649
650         STAT(LAST_PICKUP, toucher) = time;
651
652         Send_Effect(EFFECT_ITEM_PICKUP, CENTER_OR_VIEWOFS(this), '0 0 0', 1);
653         _sound (toucher, (this.itemdef.instanceOfPowerup ? CH_TRIGGER_SINGLE : CH_TRIGGER), (this.item_pickupsound ? this.item_pickupsound : Sound_fixpath(this.item_pickupsound_ent)), VOL_BASE, ATTEN_NORM);
654
655         MUTATOR_CALLHOOK(ItemTouched, this, toucher);
656         if (wasfreed(this))
657         {
658                 return;
659         }
660
661         if (Item_IsLoot(this))
662         {
663                 delete(this);
664                 return;
665         }
666         if (!this.spawnshieldtime)
667         {
668                 return;
669         }
670         entity e;
671         if (this.team)
672         {
673                 RandomSelection_Init();
674                 IL_EACH(g_items, it.team == this.team,
675                 {
676                         if (it.itemdef) // is a registered item
677                         {
678                                 Item_Show(it, -1);
679                                 it.scheduledrespawntime = 0;
680                                 RandomSelection_AddEnt(it, it.cnt, 0);
681                         }
682                 });
683                 e = RandomSelection_chosen_ent;
684                 Item_Show(e, 1); // reset its state so it is visible (extra sendflags doesn't matter, this happens anyway)
685         }
686         else
687                 e = this;
688         Item_ScheduleRespawn(e);
689 }
690
691 void Item_Reset(entity this)
692 {
693         Item_Show(this, !this.state);
694         setorigin(this, this.origin);
695
696         if (Item_IsLoot(this))
697         {
698                 return;
699         }
700         setthink(this, Item_Think);
701         this.nextthink = time;
702         if (this.waypointsprite_attached)
703         {
704                 WaypointSprite_Kill(this.waypointsprite_attached);
705         }
706         if (this.itemdef.instanceOfPowerup || (STAT(WEAPONS, this) & WEPSET_SUPERWEAPONS)) // do not spawn powerups initially!
707         {
708                 Item_ScheduleInitialRespawn(this);
709         }
710 }
711
712 void Item_FindTeam(entity this)
713 {
714         entity e;
715
716         if(this.effects & EF_NODRAW)
717         {
718                 // marker for item team search
719                 LOG_TRACE("Initializing item team ", ftos(this.team));
720                 RandomSelection_Init();
721                 IL_EACH(g_items, it.team == this.team,
722                 {
723                         if(it.itemdef) // is a registered item
724                                 RandomSelection_AddEnt(it, it.cnt, 0);
725                 });
726
727                 e = RandomSelection_chosen_ent;
728                 if (!e)
729                         return;
730
731                 IL_EACH(g_items, it.team == this.team,
732                 {
733                         if(it.itemdef) // is a registered item
734                         {
735                                 if(it != e)
736                                 {
737                                         // make it non-spawned
738                                         Item_Show(it, -1);
739                                         it.state = 1; // state 1 = initially hidden item, apparently
740                                 }
741                                 else
742                                         Item_Reset(it);
743                                 it.effects &= ~EF_NODRAW;
744                         }
745                 });
746         }
747 }
748
749 // Savage: used for item garbage-collection
750 void RemoveItem(entity this)
751 {
752         if(wasfreed(this) || !this) { return; }
753         Send_Effect(EFFECT_ITEM_PICKUP, CENTER_OR_VIEWOFS(this), '0 0 0', 1);
754         delete(this);
755 }
756
757 // pickup evaluation functions
758 // these functions decide how desirable an item is to the bots
759
760 float generic_pickupevalfunc(entity player, entity item) {return item.bot_pickupbasevalue;}
761
762 float weapon_pickupevalfunc(entity player, entity item)
763 {
764         // See if I have it already
765         if(STAT(WEAPONS, player) & STAT(WEAPONS, item))
766         {
767                 // If I can pick it up
768                 if(!item.spawnshieldtime)
769                         return 0;
770                 return ammo_pickupevalfunc(player, item);
771         }
772
773         // reduce weapon value if bot already got a good arsenal
774         float c = 1;
775         int weapons_value = 0;
776         FOREACH(Weapons, it != WEP_Null && (STAT(WEAPONS, player) & it.m_wepset), {
777                 weapons_value += it.bot_pickupbasevalue;
778         });
779         c -= bound(0, weapons_value / 20000, 1) * 0.5;
780
781         return item.bot_pickupbasevalue * c;
782 }
783
784 float ammo_pickupevalfunc(entity player, entity item)
785 {
786         bool need_shells = false, need_nails = false, need_rockets = false, need_cells = false, need_plasma = false, need_fuel = false;
787         entity wpn = NULL;
788         float c = 0;
789         float rating = 0;
790
791         // Detect needed ammo
792         if(item.itemdef.instanceOfWeaponPickup)
793         {
794                 entity ammo = NULL;
795                 if(GetResource(item, RES_SHELLS))       { need_shells  = true; ammo = ITEM_Shells;      }
796                 else if(GetResource(item, RES_BULLETS))   { need_nails   = true; ammo = ITEM_Bullets;     }
797                 else if(GetResource(item, RES_ROCKETS)) { need_rockets = true; ammo = ITEM_Rockets;     }
798                 else if(GetResource(item, RES_CELLS))   { need_cells   = true; ammo = ITEM_Cells;       }
799                 else if(GetResource(item, RES_PLASMA))  { need_plasma  = true; ammo = ITEM_Plasma;      }
800                 else if(GetResource(item, RES_FUEL))    { need_fuel    = true; ammo = ITEM_JetpackFuel; }
801
802                 if(!ammo)
803                         return 0;
804                 wpn = item;
805                 rating = ammo.m_botvalue;
806         }
807         else
808         {
809                 FOREACH(Weapons, it != WEP_Null, {
810                         if(!(STAT(WEAPONS, player) & (it.m_wepset)))
811                                 continue;
812
813                         switch(it.ammo_type)
814                         {
815                                 case RES_SHELLS:  need_shells  = true; break;
816                                 case RES_BULLETS: need_nails   = true; break;
817                                 case RES_ROCKETS: need_rockets = true; break;
818                                 case RES_CELLS:   need_cells   = true; break;
819                                 case RES_PLASMA:  need_plasma  = true; break;
820                                 case RES_FUEL:    need_fuel    = true; break;
821                         }
822                 });
823                 rating = item.bot_pickupbasevalue;
824         }
825
826         float noammorating = 0.5;
827
828         if ((need_shells) && GetResource(item, RES_SHELLS) && (GetResource(player, RES_SHELLS) < g_pickup_shells_max))
829                 c = GetResource(item, RES_SHELLS) / max(noammorating, GetResource(player, RES_SHELLS));
830
831         if ((need_nails) && GetResource(item, RES_BULLETS) && (GetResource(player, RES_BULLETS) < g_pickup_nails_max))
832                 c = GetResource(item, RES_BULLETS) / max(noammorating, GetResource(player, RES_BULLETS));
833
834         if ((need_rockets) && GetResource(item, RES_ROCKETS) && (GetResource(player, RES_ROCKETS) < g_pickup_rockets_max))
835                 c = GetResource(item, RES_ROCKETS) / max(noammorating, GetResource(player, RES_ROCKETS));
836
837         if ((need_cells) && GetResource(item, RES_CELLS) && (GetResource(player, RES_CELLS) < g_pickup_cells_max))
838                 c = GetResource(item, RES_CELLS) / max(noammorating, GetResource(player, RES_CELLS));
839
840         if ((need_plasma) && GetResource(item, RES_PLASMA) && (GetResource(player, RES_PLASMA) < g_pickup_plasma_max))
841                 c = GetResource(item, RES_PLASMA) / max(noammorating, GetResource(player, RES_PLASMA));
842
843         if ((need_fuel) && GetResource(item, RES_FUEL) && (GetResource(player, RES_FUEL) < g_pickup_fuel_max))
844                 c = GetResource(item, RES_FUEL) / max(noammorating, GetResource(player, RES_FUEL));
845
846         rating *= min(c, 2);
847         if(wpn)
848                 rating += wpn.bot_pickupbasevalue * 0.1;
849         return rating;
850 }
851
852 float healtharmor_pickupevalfunc(entity player, entity item)
853 {
854         float c = 0;
855         float rating = item.bot_pickupbasevalue;
856
857         float itemarmor = GetResource(item, RES_ARMOR);
858         float itemhealth = GetResource(item, RES_HEALTH);
859
860         if(item.item_group)
861         {
862                 itemarmor *= min(4, item.item_group_count);
863                 itemhealth *= min(4, item.item_group_count);
864         }
865
866         if (itemarmor && (GetResource(player, RES_ARMOR) < item.max_armorvalue))
867                 c = itemarmor / max(1, GetResource(player, RES_ARMOR) * 2/3 + GetResource(player, RES_HEALTH) * 1/3);
868
869         if (itemhealth && (GetResource(player, RES_HEALTH) < item.max_health))
870                 c = itemhealth / max(1, GetResource(player, RES_HEALTH));
871
872         rating *= min(2, c);
873         return rating;
874 }
875
876 void Item_Damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, .entity weaponentity, vector hitloc, vector force)
877 {
878         if(ITEM_DAMAGE_NEEDKILL(deathtype))
879                 RemoveItem(this);
880 }
881
882 void item_use(entity this, entity actor, entity trigger)
883 {
884         // use the touch function to handle collection
885         gettouch(this)(this, actor);
886 }
887
888 void _StartItem(entity this, entity def, float defaultrespawntime, float defaultrespawntimejitter)
889 {
890         string itemname = def.m_name;
891         Model itemmodel = def.m_model;
892         Sound pickupsound = def.m_sound;
893         float(entity player, entity item) pickupevalfunc = def.m_pickupevalfunc;
894         float pickupbasevalue = def.m_botvalue;
895         int itemflags = def.m_itemflags;
896
897         startitem_failed = false;
898
899         this.item_model_ent = itemmodel;
900         this.item_pickupsound_ent = pickupsound;
901
902         if(def.m_iteminit)
903                 def.m_iteminit(def, this);
904
905         if(!this.respawntime) // both need to be set
906         {
907                 this.respawntime = defaultrespawntime;
908                 this.respawntimejitter = defaultrespawntimejitter;
909         }
910
911         if(!this.pickup_anyway && def.m_pickupanyway)
912                 this.pickup_anyway = def.m_pickupanyway();
913
914         int itemid = def.m_itemid;
915         this.items = itemid;
916         int weaponid = def.instanceOfWeaponPickup ? def.m_weapon.m_id : 0;
917         this.weapon = weaponid;
918
919         if(!this.fade_end)
920         {
921                 this.fade_start = autocvar_g_items_mindist;
922                 this.fade_end = autocvar_g_items_maxdist;
923         }
924
925         if(weaponid)
926                 STAT(WEAPONS, this) = WepSet_FromWeapon(REGISTRY_GET(Weapons, weaponid));
927
928         this.flags = FL_ITEM | itemflags;
929         IL_PUSH(g_items, this);
930
931         if(MUTATOR_CALLHOOK(FilterItem, this)) // error means we do not want the item
932         {
933                 startitem_failed = true;
934                 delete(this);
935                 return;
936         }
937
938         precache_model(this.model);
939         precache_sound(this.item_pickupsound);
940
941         if (Item_IsLoot(this))
942         {
943                 this.reset = SUB_Remove;
944                 set_movetype(this, MOVETYPE_TOSS);
945
946                 // Savage: remove thrown items after a certain period of time ("garbage collection")
947                 setthink(this, RemoveItem);
948                 this.nextthink = time + 20;
949
950                 this.takedamage = DAMAGE_YES;
951                 this.event_damage = Item_Damage;
952
953                 if (Item_IsExpiring(this))
954                 {
955                         // if item is worthless after a timer, have it expire then
956                         this.nextthink = max(this.strength_finished, this.invincible_finished, this.superweapons_finished);
957                 }
958
959                 // don't drop if in a NODROP zone (such as lava)
960                 traceline(this.origin, this.origin, MOVE_NORMAL, this);
961                 if (trace_dpstartcontents & DPCONTENTS_NODROP)
962                 {
963                         startitem_failed = true;
964                         delete(this);
965                         return;
966                 }
967         }
968         else
969         {
970                 if(!have_pickup_item(this))
971                 {
972                         startitem_failed = true;
973                         delete(this);
974                         return;
975                 }
976
977                 if(this.angles != '0 0 0')
978                         this.SendFlags |= ISF_ANGLES;
979
980                 this.reset = Item_Reset;
981                 // it's a level item
982                 if(this.spawnflags & 1)
983                         this.noalign = 1;
984                 if (this.noalign > 0)
985                         set_movetype(this, MOVETYPE_NONE);
986                 else
987                         set_movetype(this, MOVETYPE_TOSS);
988                 // do item filtering according to game mode and other things
989                 if (this.noalign <= 0)
990                 {
991                         // first nudge it off the floor a little bit to avoid math errors
992                         setorigin(this, this.origin + '0 0 1');
993                         // set item size before we spawn a spawnfunc_waypoint
994                         setsize(this, def.m_mins, def.m_maxs);
995                         this.SendFlags |= ISF_SIZE;
996                         // note droptofloor returns false if stuck/or would fall too far
997                         if (!this.noalign)
998                                 droptofloor(this);
999                         waypoint_spawnforitem(this);
1000                 }
1001
1002                 /*
1003                  * can't do it that way, as it would break maps
1004                  * TODO make a target_give like entity another way, that perhaps has
1005                  * the weapon name in a key
1006                 if(this.targetname)
1007                 {
1008                         // target_give not yet supported; maybe later
1009                         print("removed targeted ", this.classname, "\n");
1010                         startitem_failed = true;
1011                         delete(this);
1012                         return;
1013                 }
1014                 */
1015
1016                 if(this.targetname != "" && (this.spawnflags & 16))
1017                         this.use = item_use;
1018
1019                 if(autocvar_spawn_debug >= 2)
1020                 {
1021                         // why not flags & fl_item?
1022                         FOREACH_ENTITY_RADIUS(this.origin, 3, it.is_item, {
1023                                 LOG_TRACE("XXX Found duplicated item: ", itemname, vtos(this.origin));
1024                                 LOG_TRACE(" vs ", it.netname, vtos(it.origin));
1025                                 error("Mapper sucks.");
1026                         });
1027                         this.is_item = true;
1028                 }
1029
1030                 weaponsInMap |= WepSet_FromWeapon(REGISTRY_GET(Weapons, weaponid));
1031
1032                 if (        def.instanceOfPowerup
1033                         ||  def.instanceOfWeaponPickup
1034                         || (def.instanceOfHealth && def != ITEM_HealthSmall)
1035                         || (def.instanceOfArmor && def != ITEM_ArmorSmall)
1036                         || (itemid & (IT_KEY1 | IT_KEY2))
1037                 )
1038                 {
1039                         if(!this.target || this.target == "")
1040                                 this.target = "###item###"; // for finding the nearest item using findnearest
1041                 }
1042
1043                 Item_ItemsTime_SetTime(this, 0);
1044         }
1045
1046         this.bot_pickup = true;
1047         this.bot_pickupevalfunc = pickupevalfunc;
1048         this.bot_pickupbasevalue = pickupbasevalue;
1049         this.mdl = this.model ? this.model : strzone(this.item_model_ent.model_str());
1050         this.netname = (def.m_weapon) ? def.m_weapon.netname : def.netname;
1051         settouch(this, Item_Touch);
1052         setmodel(this, MDL_Null); // precision set below
1053         //this.effects |= EF_LOWPRECISION;
1054
1055         setsize (this, this.pos1 =  def.m_mins, this.pos2 = def.m_maxs);
1056
1057         this.SendFlags |= ISF_SIZE;
1058
1059         if (!(this.spawnflags & 1024)) {
1060                 if(def.instanceOfPowerup)
1061                         this.ItemStatus |= ITS_ANIMATE1;
1062
1063                 if(GetResource(this, RES_ARMOR) || GetResource(this, RES_HEALTH))
1064                         this.ItemStatus |= ITS_ANIMATE2;
1065         }
1066
1067         if(Item_IsLoot(this))
1068                 this.gravity = 1;
1069
1070         if(def.instanceOfWeaponPickup)
1071         {
1072                 if (!Item_IsLoot(this)) // if dropped, colormap is already set up nicely
1073                         this.colormap = 1024; // color shirt=0 pants=0 grey
1074                 if (!(this.spawnflags & 1024))
1075                         this.ItemStatus |= ITS_ANIMATE1;
1076                 this.SendFlags |= ISF_COLORMAP;
1077         }
1078
1079         this.state = 0;
1080         if(this.team)
1081         {
1082                 if(!this.cnt)
1083                         this.cnt = 1; // item probability weight
1084
1085                 this.effects |= EF_NODRAW; // marker for item team search
1086                 InitializeEntity(this, Item_FindTeam, INITPRIO_FINDTARGET);
1087         }
1088         else
1089                 Item_Reset(this);
1090
1091         Net_LinkEntity(this, !(def.instanceOfPowerup || def.instanceOfHealth || def.instanceOfArmor), 0, ItemSend);
1092
1093         // call this hook after everything else has been done
1094         if (MUTATOR_CALLHOOK(Item_Spawn, this))
1095         {
1096                 startitem_failed = true;
1097                 delete(this);
1098                 return;
1099         }
1100
1101         setItemGroup(this);
1102 }
1103
1104 void StartItem(entity this, GameItem def)
1105 {
1106         def = def.m_spawnfunc_hookreplace(def, this);
1107
1108         if (def.spawnflags & ITEM_FLAG_MUTATORBLOCKED)
1109         {
1110                 delete(this);
1111                 return;
1112         }
1113
1114         this.classname = def.m_canonical_spawnfunc;
1115
1116         _StartItem(
1117                 this,
1118                 this.itemdef = def,
1119                 def.m_respawntime(), // defaultrespawntime
1120                 def.m_respawntimejitter() // defaultrespawntimejitter
1121         );
1122 }
1123
1124 #define IS_SMALL(def) ((def.instanceOfHealth && def == ITEM_HealthSmall) || (def.instanceOfArmor && def == ITEM_ArmorSmall))
1125 int group_count = 1;
1126
1127 void setItemGroup(entity this)
1128 {
1129         if(!IS_SMALL(this.itemdef) || Item_IsLoot(this))
1130                 return;
1131
1132         FOREACH_ENTITY_RADIUS(this.origin, 120, (it != this) && IS_SMALL(it.itemdef),
1133         {
1134                 if(!this.item_group)
1135                 {
1136                         if(!it.item_group)
1137                         {
1138                                 it.item_group = group_count;
1139                                 group_count++;
1140                         }
1141                         this.item_group = it.item_group;
1142                 }
1143                 else // spawning item is already part of a item_group X
1144                 {
1145                         if(!it.item_group)
1146                                 it.item_group = this.item_group;
1147                         else if(it.item_group != this.item_group) // found an item near the spawning item that is part of a different item_group Y
1148                         {
1149                                 int grY = it.item_group;
1150                                 // move all items of item_group Y to item_group X
1151                                 IL_EACH(g_items, IS_SMALL(it.itemdef),
1152                                 {
1153                                         if(it.item_group == grY)
1154                                                 it.item_group = this.item_group;
1155                                 });
1156                         }
1157                 }
1158         });
1159 }
1160
1161 void setItemGroupCount()
1162 {
1163         for (int k = 1; k <= group_count; k++)
1164         {
1165                 int count = 0;
1166                 IL_EACH(g_items, IS_SMALL(it.itemdef) && it.item_group == k, { count++; });
1167                 if (count)
1168                         IL_EACH(g_items, IS_SMALL(it.itemdef) && it.item_group == k, { it.item_group_count = count; });
1169         }
1170 }
1171
1172 void target_items_use(entity this, entity actor, entity trigger)
1173 {
1174         if(Item_IsLoot(actor))
1175         {
1176                 EXACTTRIGGER_TOUCH(this, trigger);
1177                 delete(actor);
1178                 return;
1179         }
1180
1181         if (!IS_PLAYER(actor) || IS_DEAD(actor))
1182                 return;
1183
1184         if(trigger.solid == SOLID_TRIGGER)
1185         {
1186                 EXACTTRIGGER_TOUCH(this, trigger);
1187         }
1188
1189         IL_EACH(g_items, it.enemy == actor && Item_IsLoot(it),
1190         {
1191                 delete(it);
1192         });
1193
1194         if(GiveItems(actor, 0, tokenize_console(this.netname)))
1195                 centerprint(actor, this.message);
1196 }
1197
1198 spawnfunc(target_items)
1199 {
1200         this.use = target_items_use;
1201         if(!this.strength_finished)
1202                 this.strength_finished = autocvar_g_balance_powerup_strength_time;
1203         if(!this.invincible_finished)
1204                 this.invincible_finished = autocvar_g_balance_powerup_invincible_time;
1205         if(!this.superweapons_finished)
1206                 this.superweapons_finished = autocvar_g_balance_superweapons_time;
1207
1208         string str;
1209         int n = tokenize_console(this.netname);
1210         if(argv(0) == "give")
1211         {
1212                 str = substring(this.netname, argv_start_index(1), argv_end_index(-1) - argv_start_index(1));
1213         }
1214         else
1215         {
1216                 for(int j = 0; j < n; ++j)
1217                 {
1218                         // this is from a time when unlimited superweapons were handled together with ammo in some parts of the code
1219                         if     (argv(j) == "unlimited_ammo")         this.items |= IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS;
1220                         else if(argv(j) == "unlimited_weapon_ammo")  this.items |= IT_UNLIMITED_AMMO;
1221                         else if(argv(j) == "unlimited_superweapons") this.items |= IT_UNLIMITED_SUPERWEAPONS;
1222                         else if(argv(j) == "strength")               this.items |= ITEM_Strength.m_itemid;
1223                         else if(argv(j) == "invincible")             this.items |= ITEM_Shield.m_itemid;
1224                         else if(argv(j) == "superweapons")           this.items |= IT_SUPERWEAPON;
1225                         else if(argv(j) == "jetpack")                this.items |= ITEM_Jetpack.m_itemid;
1226                         else if(argv(j) == "fuel_regen")             this.items |= ITEM_JetpackRegen.m_itemid;
1227                         else
1228                         {
1229                                 FOREACH(Buffs, it != BUFF_Null,
1230                                 {
1231                                         string s = Buff_UndeprecateName(argv(j));
1232                                         if(s == it.netname)
1233                                         {
1234                                                 STAT(BUFFS, this) |= (it.m_itemid);
1235                                                 if(!STAT(BUFF_TIME, this))
1236                                                         STAT(BUFF_TIME, this) = it.m_time(it);
1237                                                 break;
1238                                         }
1239                                 });
1240                                 FOREACH(Weapons, it != WEP_Null, {
1241                                         string s = W_UndeprecateName(argv(j));
1242                                         if(s == it.netname)
1243                                         {
1244                                                 STAT(WEAPONS, this) |= (it.m_wepset);
1245                                                 if(this.spawnflags == 0 || this.spawnflags == 2)
1246                                                         it.wr_init(it);
1247                                                 break;
1248                                         }
1249                                 });
1250                         }
1251                 }
1252
1253                 string itemprefix, valueprefix;
1254                 if(this.spawnflags == 0)
1255                 {
1256                         itemprefix = "";
1257                         valueprefix = "";
1258                 }
1259                 else if(this.spawnflags == 1)
1260                 {
1261                         itemprefix = "max ";
1262                         valueprefix = "max ";
1263                 }
1264                 else if(this.spawnflags == 2)
1265                 {
1266                         itemprefix = "min ";
1267                         valueprefix = "min ";
1268                 }
1269                 else if(this.spawnflags == 4)
1270                 {
1271                         itemprefix = "minus ";
1272                         valueprefix = "max ";
1273                 }
1274                 else
1275                 {
1276                         error("invalid spawnflags");
1277                         itemprefix = valueprefix = string_null;
1278                 }
1279
1280                 str = "";
1281                 str = sprintf("%s %s%d %s", str, itemprefix, boolean(this.items & IT_UNLIMITED_AMMO), "unlimited_weapon_ammo");
1282                 str = sprintf("%s %s%d %s", str, itemprefix, boolean(this.items & IT_UNLIMITED_SUPERWEAPONS), "unlimited_superweapons");
1283                 str = sprintf("%s %s%d %s", str, valueprefix, this.strength_finished * boolean(this.items & ITEM_Strength.m_itemid), "strength");
1284                 str = sprintf("%s %s%d %s", str, valueprefix, this.invincible_finished * boolean(this.items & ITEM_Shield.m_itemid), "invincible");
1285                 str = sprintf("%s %s%d %s", str, valueprefix, this.superweapons_finished * boolean(this.items & IT_SUPERWEAPON), "superweapons");
1286                 str = sprintf("%s %s%d %s", str, itemprefix, boolean(this.items & ITEM_Jetpack.m_itemid), "jetpack");
1287                 str = sprintf("%s %s%d %s", str, itemprefix, boolean(this.items & ITEM_JetpackRegen.m_itemid), "fuel_regen");
1288                 float res;
1289                 res = GetResource(this, RES_SHELLS);  if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "shells");
1290                 res = GetResource(this, RES_BULLETS); if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "nails");
1291                 res = GetResource(this, RES_ROCKETS); if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "rockets");
1292                 res = GetResource(this, RES_CELLS);   if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "cells");
1293                 res = GetResource(this, RES_PLASMA);  if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "plasma");
1294                 res = GetResource(this, RES_FUEL);    if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "fuel");
1295                 res = GetResource(this, RES_HEALTH);  if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "health");
1296                 res = GetResource(this, RES_ARMOR);   if(res != 0) str = sprintf("%s %s%d %s", str, valueprefix, max(0, res), "armor");
1297                 // HACK: buffs share a single timer, so we need to include enabled buffs AFTER disabled ones to avoid loss
1298                 FOREACH(Buffs, it != BUFF_Null && !(STAT(BUFFS, this) & it.m_itemid), str = sprintf("%s %s%d %s", str, valueprefix, max(0, STAT(BUFF_TIME, this)), it.netname));
1299                 FOREACH(Buffs, it != BUFF_Null && (STAT(BUFFS, this) & it.m_itemid), str = sprintf("%s %s%d %s", str, valueprefix, max(0, STAT(BUFF_TIME, this)), it.netname));
1300                 FOREACH(Weapons, it != WEP_Null, str = sprintf("%s %s%d %s", str, itemprefix, !!(STAT(WEAPONS, this) & (it.m_wepset)), it.netname));
1301         }
1302         this.netname = strzone(str);
1303
1304         n = tokenize_console(this.netname);
1305         for(int j = 0; j < n; ++j)
1306         {
1307                 FOREACH(Weapons, it != WEP_Null && W_UndeprecateName(argv(j)) == it.netname, {
1308                         it.wr_init(it);
1309                         break;
1310                 });
1311         }
1312 }
1313
1314 float GiveWeapon(entity e, float wpn, float op, float val)
1315 {
1316         WepSet v0, v1;
1317         WepSet s = WepSet_FromWeapon(REGISTRY_GET(Weapons, wpn));
1318         v0 = (STAT(WEAPONS, e) & s);
1319         switch(op)
1320         {
1321                 case OP_SET:
1322                         if(val > 0)
1323                                 STAT(WEAPONS, e) |= s;
1324                         else
1325                                 STAT(WEAPONS, e) &= ~s;
1326                         break;
1327                 case OP_MIN:
1328                 case OP_PLUS:
1329                         if(val > 0)
1330                                 STAT(WEAPONS, e) |= s;
1331                         break;
1332                 case OP_MAX:
1333                         if(val <= 0)
1334                                 STAT(WEAPONS, e) &= ~s;
1335                         break;
1336                 case OP_MINUS:
1337                         if(val > 0)
1338                                 STAT(WEAPONS, e) &= ~s;
1339                         break;
1340         }
1341         v1 = (STAT(WEAPONS, e) & s);
1342         return (v0 != v1);
1343 }
1344
1345 bool GiveBuff(entity e, Buff thebuff, int op, int val)
1346 {
1347         bool had_buff = (STAT(BUFFS, e) & thebuff.m_itemid);
1348         float new_buff_time = ((had_buff) ? STAT(BUFF_TIME, e) : 0);
1349         switch (op)
1350         {
1351                 case OP_SET:
1352                         new_buff_time = val;
1353                         break;
1354                 case OP_MIN:
1355                         new_buff_time = max(new_buff_time, val);
1356                         break;
1357                 case OP_MAX:
1358                         new_buff_time = min(new_buff_time, val);
1359                         break;
1360                 case OP_PLUS:
1361                         new_buff_time += val;
1362                         break;
1363                 case OP_MINUS:
1364                         new_buff_time -= val;
1365                         break;
1366         }
1367         if(new_buff_time <= 0)
1368         {
1369                 if(had_buff)
1370                         STAT(BUFF_TIME, e) = new_buff_time;
1371                 STAT(BUFFS, e) &= ~thebuff.m_itemid;
1372         }
1373         else
1374         {
1375                 STAT(BUFF_TIME, e) = new_buff_time;
1376                 STAT(BUFFS, e) = thebuff.m_itemid; // NOTE: replaces any existing buffs on the player!
1377         }
1378         bool have_buff = (STAT(BUFFS, e) & thebuff.m_itemid);
1379         return (had_buff != have_buff);
1380 }
1381
1382 void GiveSound(entity e, float v0, float v1, float t, Sound snd_incr, Sound snd_decr)
1383 {
1384         if(v1 == v0)
1385                 return;
1386         if(v1 <= v0 - t)
1387         {
1388                 if(snd_decr != NULL)
1389                         sound (e, CH_TRIGGER, snd_decr, VOL_BASE, ATTEN_NORM);
1390         }
1391         else if(v0 >= v0 + t)
1392         {
1393                 if(snd_incr != NULL)
1394                         sound (e, CH_TRIGGER, snd_incr, VOL_BASE, ATTEN_NORM);
1395         }
1396 }
1397
1398 void GiveRot(entity e, float v0, float v1, .float rotfield, float rottime, .float regenfield, float regentime)
1399 {
1400         if(v0 < v1)
1401                 e.(rotfield) = max(e.(rotfield), time + rottime);
1402         else if(v0 > v1)
1403                 e.(regenfield) = max(e.(regenfield), time + regentime);
1404 }
1405 bool GiveResourceValue(entity e, int res_type, int op, int val)
1406 {
1407         int v0 = GetResource(e, res_type);
1408         float new_val = 0;
1409         switch (op)
1410         {
1411                 // min 100 cells = at least 100 cells
1412                 case OP_SET: new_val = val; break;
1413                 case OP_MIN: new_val = max(v0, val); break;
1414                 case OP_MAX: new_val = min(v0, val); break;
1415                 case OP_PLUS: new_val = v0 + val; break;
1416                 case OP_MINUS: new_val = v0 - val; break;
1417                 default: return false;
1418         }
1419
1420         return SetResourceExplicit(e, res_type, new_val);
1421 }
1422
1423 float GiveItems(entity e, float beginarg, float endarg)
1424 {
1425         float got, i, val, op;
1426         string cmd;
1427
1428         val = 999;
1429         op = OP_SET;
1430
1431         got = 0;
1432
1433         int _switchweapon = 0;
1434
1435         if(CS_CVAR(e).autoswitch)
1436         {
1437                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1438                 {
1439                         .entity weaponentity = weaponentities[slot];
1440                         if(e.(weaponentity).m_weapon != WEP_Null || slot == 0)
1441                         if(e.(weaponentity).m_switchweapon == w_getbestweapon(e, weaponentity))
1442                                 _switchweapon |= BIT(slot);
1443                 }
1444         }
1445
1446         STAT(STRENGTH_FINISHED, e) = max(0, STAT(STRENGTH_FINISHED, e) - time);
1447         STAT(INVINCIBLE_FINISHED, e) = max(0, STAT(INVINCIBLE_FINISHED, e) - time);
1448         STAT(SUPERWEAPONS_FINISHED, e) = max(0, STAT(SUPERWEAPONS_FINISHED, e) - time);
1449         STAT(BUFF_TIME, e) = max(0, STAT(BUFF_TIME, e) - time);
1450
1451         PREGIVE(e, items);
1452         PREGIVE_WEAPONS(e);
1453         PREGIVE(e, stat_STRENGTH_FINISHED);
1454         PREGIVE(e, stat_INVINCIBLE_FINISHED);
1455         PREGIVE(e, stat_SUPERWEAPONS_FINISHED);
1456         PREGIVE_RESOURCE(e, RES_BULLETS);
1457         PREGIVE_RESOURCE(e, RES_CELLS);
1458         PREGIVE_RESOURCE(e, RES_PLASMA);
1459         PREGIVE_RESOURCE(e, RES_SHELLS);
1460         PREGIVE_RESOURCE(e, RES_ROCKETS);
1461         PREGIVE_RESOURCE(e, RES_FUEL);
1462         PREGIVE_RESOURCE(e, RES_ARMOR);
1463         PREGIVE_RESOURCE(e, RES_HEALTH);
1464
1465         for(i = beginarg; i < endarg; ++i)
1466         {
1467                 cmd = argv(i);
1468
1469                 if(cmd == "0" || stof(cmd))
1470                 {
1471                         val = stof(cmd);
1472                         continue;
1473                 }
1474                 switch(cmd)
1475                 {
1476                         case "no":
1477                                 op = OP_MAX;
1478                                 val = 0;
1479                                 continue;
1480                         case "max":
1481                                 op = OP_MAX;
1482                                 continue;
1483                         case "min":
1484                                 op = OP_MIN;
1485                                 continue;
1486                         case "plus":
1487                                 op = OP_PLUS;
1488                                 continue;
1489                         case "minus":
1490                                 op = OP_MINUS;
1491                                 continue;
1492                         case "ALL":
1493                                 got += GiveBit(e, items, ITEM_JetpackRegen.m_itemid, op, val);
1494                                 got += GiveValue(e, stat_STRENGTH_FINISHED, op, val);
1495                                 got += GiveValue(e, stat_INVINCIBLE_FINISHED, op, val);
1496                                 got += GiveValue(e, stat_SUPERWEAPONS_FINISHED, op, val);
1497                                 got += GiveBit(e, items, IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS, op, val);
1498                         case "all":
1499                                 got += GiveBit(e, items, ITEM_Jetpack.m_itemid, op, val);
1500                                 got += GiveResourceValue(e, RES_HEALTH, op, val);
1501                                 got += GiveResourceValue(e, RES_ARMOR, op, val);
1502                         case "allweapons":
1503                                 FOREACH(Weapons, it != WEP_Null && !(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_SPECIALATTACK)), got += GiveWeapon(e, it.m_id, op, val));
1504                         //case "allbuffs": // all buffs makes a player god, do not want!
1505                                 //FOREACH(Buffs, it != BUFF_Null, got += GiveBuff(e, it.m_itemid, op, val));
1506                         case "allammo":
1507                                 got += GiveResourceValue(e, RES_CELLS, op, val);
1508                                 got += GiveResourceValue(e, RES_PLASMA, op, val);
1509                                 got += GiveResourceValue(e, RES_SHELLS, op, val);
1510                                 got += GiveResourceValue(e, RES_BULLETS, op, val);
1511                                 got += GiveResourceValue(e, RES_ROCKETS, op, val);
1512                                 got += GiveResourceValue(e, RES_FUEL, op, val);
1513                                 break;
1514                         case "unlimited_ammo":
1515                                 // this is from a time when unlimited superweapons were handled together with ammo in some parts of the code
1516                                 got += GiveBit(e, items, IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS, op, val);
1517                                 break;
1518                         case "unlimited_weapon_ammo":
1519                                 got += GiveBit(e, items, IT_UNLIMITED_AMMO, op, val);
1520                                 break;
1521                         case "unlimited_superweapons":
1522                                 got += GiveBit(e, items, IT_UNLIMITED_SUPERWEAPONS, op, val);
1523                                 break;
1524                         case "jetpack":
1525                                 got += GiveBit(e, items, ITEM_Jetpack.m_itemid, op, val);
1526                                 break;
1527                         case "fuel_regen":
1528                                 got += GiveBit(e, items, ITEM_JetpackRegen.m_itemid, op, val);
1529                                 break;
1530                         case "strength":
1531                                 got += GiveValue(e, stat_STRENGTH_FINISHED, op, val);
1532                                 break;
1533                         case "invincible":
1534                                 got += GiveValue(e, stat_INVINCIBLE_FINISHED, op, val);
1535                                 break;
1536                         case "superweapons":
1537                                 got += GiveValue(e, stat_SUPERWEAPONS_FINISHED, op, val);
1538                                 break;
1539                         case "cells":
1540                                 got += GiveResourceValue(e, RES_CELLS, op, val);
1541                                 break;
1542                         case "plasma":
1543                                 got += GiveResourceValue(e, RES_PLASMA, op, val);
1544                                 break;
1545                         case "shells":
1546                                 got += GiveResourceValue(e, RES_SHELLS, op, val);
1547                                 break;
1548                         case "nails":
1549                         case "bullets":
1550                                 got += GiveResourceValue(e, RES_BULLETS, op, val);
1551                                 break;
1552                         case "rockets":
1553                                 got += GiveResourceValue(e, RES_ROCKETS, op, val);
1554                                 break;
1555                         case "health":
1556                                 got += GiveResourceValue(e, RES_HEALTH, op, val);
1557                                 break;
1558                         case "armor":
1559                                 got += GiveResourceValue(e, RES_ARMOR, op, val);
1560                                 break;
1561                         case "fuel":
1562                                 got += GiveResourceValue(e, RES_FUEL, op, val);
1563                                 break;
1564                         default:
1565                                 FOREACH(Buffs, it != BUFF_Null && buff_Available(it) && Buff_UndeprecateName(cmd) == it.netname,
1566                                 {
1567                                         got += GiveBuff(e, it, op, val);
1568                                         break;
1569                                 });
1570                                 FOREACH(Weapons, it != WEP_Null && W_UndeprecateName(cmd) == it.netname, {
1571                     got += GiveWeapon(e, it.m_id, op, val);
1572                     break;
1573                                 });
1574                                 break;
1575                 }
1576                 val = 999;
1577                 op = OP_SET;
1578         }
1579
1580         POSTGIVE_BIT(e, items, ITEM_JetpackRegen.m_itemid, SND_ITEMPICKUP, SND_Null);
1581         POSTGIVE_BIT(e, items, IT_UNLIMITED_SUPERWEAPONS, SND_POWERUP, SND_POWEROFF);
1582         POSTGIVE_BIT(e, items, IT_UNLIMITED_AMMO, SND_POWERUP, SND_POWEROFF);
1583         POSTGIVE_BIT(e, items, ITEM_Jetpack.m_itemid, SND_ITEMPICKUP, SND_Null);
1584         FOREACH(Weapons, it != WEP_Null, {
1585                 POSTGIVE_WEAPON(e, it, SND_WEAPONPICKUP, SND_Null);
1586                 if(!(save_weapons & (it.m_wepset)))
1587                         if(STAT(WEAPONS, e) & (it.m_wepset))
1588                                 it.wr_init(it);
1589         });
1590         POSTGIVE_VALUE(e, stat_STRENGTH_FINISHED, 1, SND_POWERUP, SND_POWEROFF);
1591         POSTGIVE_VALUE(e, stat_INVINCIBLE_FINISHED, 1, SND_Shield, SND_POWEROFF);
1592         //POSTGIVE_VALUE(e, stat_SUPERWEAPONS_FINISHED, 1, SND_Null, SND_Null);
1593         POSTGIVE_RESOURCE(e, RES_BULLETS, 0, SND_ITEMPICKUP, SND_Null);
1594         POSTGIVE_RESOURCE(e, RES_CELLS, 0, SND_ITEMPICKUP, SND_Null);
1595         POSTGIVE_RESOURCE(e, RES_PLASMA, 0, SND_ITEMPICKUP, SND_Null);
1596         POSTGIVE_RESOURCE(e, RES_SHELLS, 0, SND_ITEMPICKUP, SND_Null);
1597         POSTGIVE_RESOURCE(e, RES_ROCKETS, 0, SND_ITEMPICKUP, SND_Null);
1598         POSTGIVE_RES_ROT(e, RES_FUEL, 1, pauserotfuel_finished, autocvar_g_balance_pause_fuel_rot, pauseregen_finished, autocvar_g_balance_pause_fuel_regen, SND_ITEMPICKUP, SND_Null);
1599         POSTGIVE_RES_ROT(e, RES_ARMOR, 1, pauserotarmor_finished, autocvar_g_balance_pause_armor_rot, pauseregen_finished, autocvar_g_balance_pause_health_regen, SND_ARMOR25, SND_Null);
1600         POSTGIVE_RES_ROT(e, RES_HEALTH, 1, pauserothealth_finished, autocvar_g_balance_pause_health_rot, pauseregen_finished, autocvar_g_balance_pause_health_regen, SND_MEGAHEALTH, SND_Null);
1601
1602         if(STAT(SUPERWEAPONS_FINISHED, e) <= 0)
1603                 if(!g_weaponarena && (STAT(WEAPONS, e) & WEPSET_SUPERWEAPONS))
1604                         STAT(SUPERWEAPONS_FINISHED, e) = autocvar_g_balance_superweapons_time;
1605
1606         if(STAT(STRENGTH_FINISHED, e) <= 0)
1607                 STAT(STRENGTH_FINISHED, e) = 0;
1608         else
1609                 STAT(STRENGTH_FINISHED, e) += time;
1610         if(STAT(INVINCIBLE_FINISHED, e) <= 0)
1611                 STAT(INVINCIBLE_FINISHED, e) = 0;
1612         else
1613                 STAT(INVINCIBLE_FINISHED, e) += time;
1614         if(STAT(SUPERWEAPONS_FINISHED, e) <= 0)
1615                 STAT(SUPERWEAPONS_FINISHED, e) = 0;
1616         else
1617                 STAT(SUPERWEAPONS_FINISHED, e) += time;
1618         if(STAT(BUFF_TIME, e) <= 0)
1619                 STAT(BUFF_TIME, e) = 0;
1620         else
1621                 STAT(BUFF_TIME, e) += time;
1622
1623         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1624         {
1625                 .entity weaponentity = weaponentities[slot];
1626                 if(e.(weaponentity).m_weapon != WEP_Null || slot == 0)
1627                 if(!(STAT(WEAPONS, e) & WepSet_FromWeapon(e.(weaponentity).m_switchweapon)))
1628                         _switchweapon |= BIT(slot);
1629         }
1630
1631         if(_switchweapon)
1632         {
1633                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1634                 {
1635                         .entity weaponentity = weaponentities[slot];
1636                         if(_switchweapon & BIT(slot))
1637                         {
1638                                 Weapon wep = w_getbestweapon(e, weaponentity);
1639                                 if(wep != e.(weaponentity).m_switchweapon)
1640                                         W_SwitchWeapon_Force(e, wep, weaponentity);
1641                         }
1642                 }
1643         }
1644
1645         return got;
1646 }