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