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