]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/t_items.qc
e3a2c8be439a5bcb5d3bc5dd3341856cbc0a2e74
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / t_items.qc
1 #include "t_items.qh"
2
3 #include "items/_mod.qh"
4
5 #if defined(SVQC)
6
7     #include "../server/bot/api.qh"
8
9     #include <server/mutators/_mod.qh>
10
11     #include "../server/weapons/common.qh"
12     #include "../server/weapons/selection.qh"
13     #include "../server/weapons/weaponsystem.qh"
14
15     #include "constants.qh"
16     #include <common/deathtypes/all.qh>
17     #include <common/notifications/all.qh>
18         #include "triggers/subs.qh"
19     #include "util.qh"
20
21     #include <common/monsters/_mod.qh>
22
23     #include <common/weapons/_all.qh>
24
25     #include <common/mutators/mutator/buffs/buffs.qh>
26
27     #include "../lib/warpzone/util_server.qh"
28 #elif defined(CSQC)
29         #include "physics/movetypes/movetypes.qh"
30         #include <common/weapons/_all.qh>
31         #include "../lib/csqcmodel/cl_model.qh"
32         #include "../lib/csqcmodel/common.qh"
33 #endif
34
35 REGISTER_NET_LINKED(ENT_CLIENT_ITEM)
36
37 #ifdef CSQC
38 bool autocvar_cl_ghost_items_vehicle = true;
39 .vector item_glowmod;
40 void Item_SetAlpha(entity this)
41 {
42         bool veh_hud = (hud && autocvar_cl_ghost_items_vehicle);
43
44         if(!veh_hud && (this.ItemStatus & ITS_AVAILABLE))
45         {
46                 this.alpha = 1;
47                 this.colormod = '1 1 1';
48                 this.glowmod = this.item_glowmod;
49         }
50         else
51         {
52                 if (autocvar_cl_ghost_items_color)
53                 {
54                         this.alpha = autocvar_cl_ghost_items;
55                         this.colormod = this.glowmod = autocvar_cl_ghost_items_color;
56                 }
57                 else
58                         this.alpha = -1;
59         }
60
61         if((!veh_hud) && (this.ItemStatus & ITS_STAYWEP))
62         {
63                 this.colormod = this.glowmod = autocvar_cl_weapon_stay_color;
64                 this.alpha = autocvar_cl_weapon_stay_alpha;
65         }
66
67         this.drawmask = ((this.alpha <= 0) ? 0 : MASK_NORMAL);
68 }
69
70 void ItemDraw(entity this)
71 {
72     if(this.gravity)
73     {
74         Movetype_Physics_MatchServer(this, false);
75         if(IS_ONGROUND(this))
76         { // For some reason avelocity gets set to '0 0 0' here ...
77             this.oldorigin = this.origin;
78             this.gravity = 0;
79
80             if(autocvar_cl_animate_items)
81             { // ... so reset it if animations are requested.
82                 if(this.ItemStatus & ITS_ANIMATE1)
83                     this.avelocity = '0 180 0';
84
85                 if(this.ItemStatus & ITS_ANIMATE2)
86                     this.avelocity = '0 -90 0';
87             }
88
89             // delay is for blocking item's position for a while;
90             // it's a workaround for dropped weapons that receive the position
91             // another time right after they spawn overriding animation position
92             this.onground_time = time + 0.5;
93         }
94     }
95     else if (autocvar_cl_animate_items)
96     {
97         if(this.ItemStatus & ITS_ANIMATE1)
98         {
99             this.angles += this.avelocity * frametime;
100             float fade_in = bound(0, time - this.onground_time, 1);
101             setorigin(this, this.oldorigin + fade_in * ('0 0 10' + '0 0 8' * sin((time - this.onground_time) * 2)));
102         }
103
104         if(this.ItemStatus & ITS_ANIMATE2)
105         {
106             this.angles += this.avelocity * frametime;
107             float fade_in = bound(0, time - this.onground_time, 1);
108             setorigin(this, this.oldorigin + fade_in * ('0 0 8' + '0 0 4' * sin((time - this.onground_time) * 3)));
109         }
110     }
111
112     Item_SetAlpha(this);
113 }
114
115 void ItemDrawSimple(entity this)
116 {
117     if(this.gravity)
118     {
119         Movetype_Physics_MatchServer(this, false);
120
121         if(IS_ONGROUND(this))
122             this.gravity = 0;
123     }
124
125     Item_SetAlpha(this);
126 }
127
128 void Item_PreDraw(entity this)
129 {
130         if(warpzone_warpzones_exist)
131         {
132                 setpredraw(this, func_null); // no need to keep running this
133                 return;
134         }
135         float alph;
136         vector org = getpropertyvec(VF_ORIGIN);
137         //if(!checkpvs(org, this)) // this makes sense as long as we don't support recursive warpzones
138                 //alph = 0; // this shouldn't be needed, since items behind walls are culled anyway
139         if(this.fade_start)
140         {
141                 if(vdist(org - this.origin, >, this.fade_end))
142                         alph = 0; // save on some processing
143                 else if(vdist(org - this.origin, <, this.fade_start))
144                         alph = 1; // more processing saved
145                 else
146                         alph = bound(0, (this.fade_end - vlen(org - this.origin - 0.5 * (this.mins + this.maxs))) / (this.fade_end - this.fade_start), 1);
147         }
148         else
149                 alph = 1;
150         //printf("%v <-> %v\n", view_origin, this.origin + 0.5 * (this.mins + this.maxs));
151         if(!hud && (this.ItemStatus & ITS_AVAILABLE))
152                 this.alpha = alph;
153         if(alph <= 0)
154                 this.drawmask = 0;
155         //else
156                 //this.drawmask = MASK_NORMAL; // reset by the setalpha function
157 }
158
159 void ItemRemove(entity this)
160 {
161         if(this.mdl)
162                 strunzone(this.mdl);
163 }
164
165 NET_HANDLE(ENT_CLIENT_ITEM, bool isnew)
166 {
167     int sf = ReadByte();
168
169     if(sf & ISF_LOCATION)
170     {
171         this.origin_x = ReadCoord();
172         this.origin_y = ReadCoord();
173         this.origin_z = ReadCoord();
174         setorigin(this, this.origin);
175         this.oldorigin = this.origin;
176     }
177
178     if(sf & ISF_ANGLES)
179     {
180         this.angles_x = ReadAngle();
181         this.angles_y = ReadAngle();
182         this.angles_z = ReadAngle();
183     }
184
185     if(sf & ISF_SIZE)
186     {
187         float use_bigsize = ReadByte();
188         setsize(this, '-16 -16 0', (use_bigsize) ? '16 16 48' : '16 16 32');
189     }
190
191     if(sf & ISF_STATUS) // need to read/write status first so model can handle simple, fb etc.
192     {
193         this.ItemStatus = ReadByte();
194
195         Item_SetAlpha(this);
196
197         if(autocvar_cl_fullbright_items)
198             if(this.ItemStatus & ITS_ALLOWFB)
199                 this.effects |= EF_FULLBRIGHT;
200
201         if(this.ItemStatus & ITS_GLOW)
202         {
203             if(this.ItemStatus & ITS_AVAILABLE)
204                 this.effects |= (EF_ADDITIVE | EF_FULLBRIGHT);
205             else
206                  this.effects &= ~(EF_ADDITIVE | EF_FULLBRIGHT);
207         }
208     }
209
210     if(sf & ISF_MODEL)
211     {
212         this.drawmask  = MASK_NORMAL;
213                 set_movetype(this, MOVETYPE_TOSS);
214                 if (isnew) IL_PUSH(g_drawables, this);
215         this.draw       = ItemDraw;
216         this.solid = SOLID_TRIGGER;
217         //this.flags |= FL_ITEM;
218
219         bool use_bigsize = ReadByte();
220
221         this.fade_end = ReadShort();
222         this.fade_start = ReadShort();
223         if(!warpzone_warpzones_exist && this.fade_start && !autocvar_cl_items_nofade)
224                 setpredraw(this, Item_PreDraw);
225
226         if(this.mdl)
227             strunzone(this.mdl);
228
229         this.mdl = "";
230         string _fn = ReadString();
231
232         if(autocvar_cl_simple_items && (this.ItemStatus & ITS_ALLOWSI))
233         {
234             string _fn2 = substring(_fn, 0 , strlen(_fn) -4);
235             this.draw = ItemDrawSimple;
236
237             if(fexists(strcat(_fn2, autocvar_cl_simpleitems_postfix, ".md3")))
238                 this.mdl = strzone(strcat(_fn2, autocvar_cl_simpleitems_postfix, ".md3"));
239             else if(fexists(strcat(_fn2, autocvar_cl_simpleitems_postfix, ".dpm")))
240                 this.mdl = strzone(strcat(_fn2, autocvar_cl_simpleitems_postfix, ".dpm"));
241             else if(fexists(strcat(_fn2, autocvar_cl_simpleitems_postfix, ".iqm")))
242                 this.mdl = strzone(strcat(_fn2, autocvar_cl_simpleitems_postfix, ".iqm"));
243             else if(fexists(strcat(_fn2, autocvar_cl_simpleitems_postfix, ".mdl")))
244                 this.mdl = strzone(strcat(_fn2, autocvar_cl_simpleitems_postfix, ".mdl"));
245             else
246             {
247                 this.draw = ItemDraw;
248                 LOG_TRACE("Simple item requested for ", _fn, " but no model exists for it");
249             }
250         }
251
252         if(this.draw != ItemDrawSimple)
253             this.mdl = strzone(_fn);
254
255
256         if(this.mdl == "")
257             LOG_TRACE("^1WARNING!^7 this.mdl is unset for item ", this.classname, ", tell tZork about this!");
258
259         precache_model(this.mdl);
260         _setmodel(this, this.mdl);
261
262         setsize(this, '-16 -16 0', (use_bigsize) ? '16 16 48' : '16 16 32');
263     }
264
265     if(sf & ISF_COLORMAP)
266     {
267         this.colormap = ReadShort();
268         this.item_glowmod_x = ReadByte() / 255.0;
269         this.item_glowmod_y = ReadByte() / 255.0;
270         this.item_glowmod_z = ReadByte() / 255.0;
271     }
272
273     if(sf & ISF_DROP)
274     {
275         this.gravity = 1;
276         this.pushable = true;
277         //this.angles = '0 0 0';
278         set_movetype(this, MOVETYPE_TOSS);
279         this.velocity_x = ReadCoord();
280         this.velocity_y = ReadCoord();
281         this.velocity_z = ReadCoord();
282         setorigin(this, this.oldorigin);
283
284         if(!this.move_time)
285         {
286             this.move_time = time;
287             this.spawntime = time;
288         }
289         else
290             this.move_time = max(this.move_time, time);
291     }
292
293     if(autocvar_cl_animate_items)
294     {
295         if(this.ItemStatus & ITS_ANIMATE1)
296             this.avelocity = '0 180 0';
297
298         if(this.ItemStatus & ITS_ANIMATE2)
299             this.avelocity = '0 -90 0';
300     }
301
302     this.entremove = ItemRemove;
303
304     return true;
305 }
306
307 #endif
308
309 #ifdef SVQC
310 bool ItemSend(entity this, entity to, int sf)
311 {
312         if(this.gravity)
313                 sf |= ISF_DROP;
314         else
315                 sf &= ~ISF_DROP;
316
317         WriteHeader(MSG_ENTITY, ENT_CLIENT_ITEM);
318         WriteByte(MSG_ENTITY, sf);
319
320         //WriteByte(MSG_ENTITY, this.cnt);
321         if(sf & ISF_LOCATION)
322         {
323                 WriteCoord(MSG_ENTITY, this.origin.x);
324                 WriteCoord(MSG_ENTITY, this.origin.y);
325                 WriteCoord(MSG_ENTITY, this.origin.z);
326         }
327
328         if(sf & ISF_ANGLES)
329         {
330                 WriteAngle(MSG_ENTITY, this.angles_x);
331                 WriteAngle(MSG_ENTITY, this.angles_y);
332                 WriteAngle(MSG_ENTITY, this.angles_z);
333         }
334
335         if(sf & ISF_SIZE)
336         {
337                 Pickup p = this.itemdef;
338                 WriteByte(MSG_ENTITY, p.instanceOfPowerup || p.instanceOfHealth || p.instanceOfArmor);
339         }
340
341         if(sf & ISF_STATUS)
342                 WriteByte(MSG_ENTITY, this.ItemStatus);
343
344         if(sf & ISF_MODEL)
345         {
346                 Pickup p = this.itemdef;
347                 WriteByte(MSG_ENTITY, p.instanceOfPowerup || p.instanceOfHealth || p.instanceOfArmor);
348                 WriteShort(MSG_ENTITY, this.fade_end);
349                 WriteShort(MSG_ENTITY, this.fade_start);
350
351                 if(this.mdl == "")
352                         LOG_TRACE("^1WARNING!^7 this.mdl is unset for item ", this.classname, "expect a crash just about now");
353
354                 WriteString(MSG_ENTITY, this.mdl);
355         }
356
357
358         if(sf & ISF_COLORMAP)
359         {
360                 WriteShort(MSG_ENTITY, this.colormap);
361                 WriteByte(MSG_ENTITY, this.glowmod.x * 255.0);
362         WriteByte(MSG_ENTITY, this.glowmod.y * 255.0);
363         WriteByte(MSG_ENTITY, this.glowmod.z * 255.0);
364         }
365
366         if(sf & ISF_DROP)
367         {
368                 WriteCoord(MSG_ENTITY, this.velocity.x);
369                 WriteCoord(MSG_ENTITY, this.velocity.y);
370                 WriteCoord(MSG_ENTITY, this.velocity.z);
371         }
372
373         return true;
374 }
375
376 void ItemUpdate(entity this)
377 {
378         this.oldorigin = this.origin;
379         this.SendFlags |= ISF_LOCATION;
380 }
381
382 void UpdateItemAfterTeleport(entity this)
383 {
384         if(getSendEntity(this) == ItemSend)
385                 ItemUpdate(this);
386 }
387
388 bool have_pickup_item(entity this)
389 {
390         if(this.itemdef.instanceOfPowerup)
391         {
392                 if(autocvar_g_powerups > 0)
393                         return true;
394                 if(autocvar_g_powerups == 0)
395                         return false;
396         }
397         else
398         {
399                 if(autocvar_g_pickup_items > 0)
400                         return true;
401                 if(autocvar_g_pickup_items == 0)
402                         return false;
403                 if(g_weaponarena)
404                         if(this.weapons || this.itemdef.instanceOfAmmo) // no item or ammo pickups in weaponarena
405                                 return false;
406         }
407         return true;
408 }
409
410 /*
411 float Item_Customize()
412 {
413         if(this.spawnshieldtime)
414                 return true;
415         if(this.weapons & ~other.weapons)
416         {
417                 this.colormod = '0 0 0';
418                 this.glowmod = this.colormod;
419                 this.alpha = 0.5 + 0.5 * g_ghost_items; // halfway more alpha
420                 return true;
421         }
422         else
423         {
424                 if(g_ghost_items)
425                 {
426                         this.colormod = stov(autocvar_g_ghost_items_color);
427                         this.glowmod = this.colormod;
428                         this.alpha = g_ghost_items;
429                         return true;
430                 }
431                 else
432                         return false;
433         }
434 }
435 */
436
437 void Item_Show (entity e, float mode)
438 {
439         e.effects &= ~(EF_ADDITIVE | EF_STARDUST | EF_FULLBRIGHT | EF_NODEPTHTEST);
440         e.ItemStatus &= ~ITS_STAYWEP;
441         entity def = e.itemdef;
442         if (mode > 0)
443         {
444                 // make the item look normal, and be touchable
445                 e.model = e.mdl;
446                 e.solid = SOLID_TRIGGER;
447                 e.spawnshieldtime = 1;
448                 e.ItemStatus |= ITS_AVAILABLE;
449         }
450         else if (mode < 0)
451         {
452                 // hide the item completely
453                 e.model = string_null;
454                 e.solid = SOLID_NOT;
455                 e.spawnshieldtime = 1;
456                 e.ItemStatus &= ~ITS_AVAILABLE;
457         }
458         else
459         {
460                 bool nostay = def.instanceOfWeaponPickup ? !!(def.m_weapon.weapons & WEPSET_SUPERWEAPONS) : false // no weapon-stay on superweapons
461                         || e.team // weapon stay isn't supported for teamed weapons
462                         ;
463                 if(def.instanceOfWeaponPickup && !nostay && g_weapon_stay)
464                 {
465                         // make the item translucent and not touchable
466                         e.model = e.mdl;
467                         e.solid = SOLID_TRIGGER; // can STILL be picked up!
468                         e.effects |= EF_STARDUST;
469                         e.spawnshieldtime = 0; // field indicates whether picking it up may give you anything other than the weapon
470                         e.ItemStatus |= (ITS_AVAILABLE | ITS_STAYWEP);
471                 }
472                 else
473                 {
474                         //setmodel(e, "null");
475                         e.solid = SOLID_NOT;
476                         e.colormod = '0 0 0';
477                         //e.glowmod = e.colormod;
478                         e.spawnshieldtime = 1;
479                         e.ItemStatus &= ~ITS_AVAILABLE;
480                 }
481         }
482
483         if (def.m_glow)
484                 e.ItemStatus |= ITS_GLOW;
485
486         if (autocvar_g_nodepthtestitems)
487                 e.effects |= EF_NODEPTHTEST;
488
489
490         if (autocvar_g_fullbrightitems)
491                 e.ItemStatus |= ITS_ALLOWFB;
492
493         if (autocvar_sv_simple_items)
494                 e.ItemStatus |= ITS_ALLOWSI;
495
496         // relink entity (because solid may have changed)
497         setorigin(e, e.origin);
498         e.SendFlags |= ISF_STATUS;
499 }
500
501 void Item_Think(entity this)
502 {
503         this.nextthink = time;
504         if(this.origin != this.oldorigin)
505                 ItemUpdate(this);
506 }
507
508 bool Item_ItemsTime_SpectatorOnly(GameItem it);
509 bool Item_ItemsTime_Allow(GameItem it);
510 float Item_ItemsTime_UpdateTime(entity e, float t);
511 void Item_ItemsTime_SetTime(entity e, float t);
512 void Item_ItemsTime_SetTimesForAllPlayers();
513
514 void Item_Respawn (entity this)
515 {
516         Item_Show(this, 1);
517         sound(this, CH_TRIGGER, this.itemdef.m_respawnsound, VOL_BASE, ATTEN_NORM);     // play respawn sound
518         setorigin(this, this.origin);
519
520     if (Item_ItemsTime_Allow(this.itemdef) || (this.weapons & WEPSET_SUPERWEAPONS))
521         {
522                 float t = Item_ItemsTime_UpdateTime(this, 0);
523                 Item_ItemsTime_SetTime(this, t);
524                 Item_ItemsTime_SetTimesForAllPlayers();
525         }
526
527         setthink(this, Item_Think);
528         this.nextthink = time;
529
530         //Send_Effect(EFFECT_ITEM_RESPAWN, this.origin + this.mins_z * '0 0 1' + '0 0 48', '0 0 0', 1);
531         Send_Effect(EFFECT_ITEM_RESPAWN, CENTER_OR_VIEWOFS(this), '0 0 0', 1);
532 }
533
534 void Item_RespawnCountdown (entity this)
535 {
536         if(this.count >= ITEM_RESPAWN_TICKS)
537         {
538                 if(this.waypointsprite_attached)
539                         WaypointSprite_Kill(this.waypointsprite_attached);
540                 Item_Respawn(this);
541         }
542         else
543         {
544                 this.nextthink = time + 1;
545                 this.count += 1;
546                 if(this.count == 1)
547                 {
548                         do {
549                                 {
550                                         entity wi = Weapons_from(this.weapon);
551                                         if (wi != WEP_Null) {
552                                                 entity wp = WaypointSprite_Spawn(WP_Weapon, 0, 0, this, '0 0 64', NULL, 0, this, waypointsprite_attached, true, RADARICON_Weapon);
553                                                 wp.wp_extra = wi.m_id;
554                                                 break;
555                                         }
556                                 }
557                                 {
558                                         entity ii = this.itemdef;
559                                         if (ii != NULL) {
560                                                 entity wp = WaypointSprite_Spawn(WP_Item, 0, 0, this, '0 0 64', NULL, 0, this, waypointsprite_attached, true, RADARICON_Item);
561                                                 wp.wp_extra = ii.m_id;
562                                                 break;
563                                         }
564                                 }
565                         } while (0);
566                         bool mutator_returnvalue = MUTATOR_CALLHOOK(Item_RespawnCountdown, this);
567             if(this.waypointsprite_attached)
568             {
569                 GameItem def = this.itemdef;
570                 if (Item_ItemsTime_SpectatorOnly(def) && !mutator_returnvalue)
571                     WaypointSprite_UpdateRule(this.waypointsprite_attached, 0, SPRITERULE_SPECTATOR);
572                 WaypointSprite_UpdateBuildFinished(this.waypointsprite_attached, time + ITEM_RESPAWN_TICKS);
573             }
574                 }
575
576                 if(this.waypointsprite_attached)
577                 {
578                         FOREACH_CLIENT(IS_REAL_CLIENT(it), {
579                                 if(this.waypointsprite_attached.waypointsprite_visible_for_player(this.waypointsprite_attached, it, it))
580                                 {
581                                         msg_entity = it;
582                                         soundto(MSG_ONE, this, CH_TRIGGER, SND(ITEMRESPAWNCOUNTDOWN), VOL_BASE, ATTEN_NORM);    // play respawn sound
583                                 }
584                         });
585
586                         WaypointSprite_Ping(this.waypointsprite_attached);
587                         //WaypointSprite_UpdateHealth(this.waypointsprite_attached, this.count);
588                 }
589         }
590 }
591
592 void Item_RespawnThink(entity this)
593 {
594         this.nextthink = time;
595         if(this.origin != this.oldorigin)
596                 ItemUpdate(this);
597
598         if(time >= this.wait)
599                 Item_Respawn(this);
600 }
601
602 void Item_ScheduleRespawnIn(entity e, float t)
603 {
604         // if the respawn time is longer than 10 seconds, show a waypoint, otherwise, just respawn normally
605         if ((Item_ItemsTime_Allow(e.itemdef) || (e.weapons & WEPSET_SUPERWEAPONS) || MUTATOR_CALLHOOK(Item_ScheduleRespawn, e, t)) && (t - ITEM_RESPAWN_TICKS) > 0)
606         {
607                 setthink(e, Item_RespawnCountdown);
608                 e.nextthink = time + max(0, t - ITEM_RESPAWN_TICKS);
609                 e.scheduledrespawntime = e.nextthink + ITEM_RESPAWN_TICKS;
610                 e.count = 0;
611                 if(Item_ItemsTime_Allow(e.itemdef) || (e.weapons & WEPSET_SUPERWEAPONS))
612                 {
613                         t = Item_ItemsTime_UpdateTime(e, e.scheduledrespawntime);
614                         Item_ItemsTime_SetTime(e, t);
615                         Item_ItemsTime_SetTimesForAllPlayers();
616                 }
617         }
618         else
619         {
620                 setthink(e, Item_RespawnThink);
621                 e.nextthink = time;
622                 e.scheduledrespawntime = time + t;
623                 e.wait = time + t;
624
625                 if(Item_ItemsTime_Allow(e.itemdef) || (e.weapons & WEPSET_SUPERWEAPONS))
626                 {
627                         t = Item_ItemsTime_UpdateTime(e, e.scheduledrespawntime);
628                         Item_ItemsTime_SetTime(e, t);
629                         Item_ItemsTime_SetTimesForAllPlayers();
630                 }
631         }
632 }
633
634 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*");
635 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");
636 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");
637
638 float adjust_respawntime(float normal_respawntime) {
639         float r = autocvar_g_pickup_respawntime_scaling_reciprocal;
640         float o = autocvar_g_pickup_respawntime_scaling_offset;
641         float l = autocvar_g_pickup_respawntime_scaling_linear;
642
643         if (r == 0 && l == 1) {
644                 return normal_respawntime;
645         }
646
647         CheckAllowedTeams(NULL);
648         GetTeamCounts(NULL);
649         int players = 0;
650         if (c1 != -1) players += c1;
651         if (c2 != -1) players += c2;
652         if (c3 != -1) players += c3;
653         if (c4 != -1) players += c4;
654
655         if (players >= 2) {
656                 return normal_respawntime * (r / (players + o) + l);
657         } else {
658                 return normal_respawntime;
659         }
660 }
661
662 void Item_ScheduleRespawn(entity e)
663 {
664         if(e.respawntime > 0)
665         {
666                 Item_Show(e, 0);
667
668                 float adjusted_respawntime = adjust_respawntime(e.respawntime);
669                 //LOG_INFOF("item %s will respawn in %f", e.classname, adjusted_respawntime);
670
671                 // range: adjusted_respawntime - respawntimejitter .. adjusted_respawntime + respawntimejitter
672                 float actual_time = adjusted_respawntime + crandom() * e.respawntimejitter;
673                 Item_ScheduleRespawnIn(e, actual_time);
674         }
675         else // if respawntime is -1, this item does not respawn
676                 Item_Show(e, -1);
677 }
678
679 void Item_ScheduleInitialRespawn(entity e)
680 {
681         Item_Show(e, 0);
682         Item_ScheduleRespawnIn(e, max(0, game_starttime - time) + ((e.respawntimestart) ? e.respawntimestart : ITEM_RESPAWNTIME_INITIAL(e)));
683 }
684
685 int GetResourceType(.float resource_property)
686 {
687         switch (resource_property)
688         {
689                 case health: { return RESOURCE_HEALTH; }
690                 case armorvalue: { return RESOURCE_ARMOR; }
691                 case ammo_shells: { return RESOURCE_SHELLS; }
692                 case ammo_nails: { return RESOURCE_BULLETS; }
693                 case ammo_rockets: { return RESOURCE_ROCKETS; }
694                 case ammo_cells: { return RESOURCE_CELLS; }
695                 case ammo_plasma: { return RESOURCE_PLASMA; }
696                 case ammo_fuel: { return RESOURCE_FUEL; }
697         }
698         error("GetResourceType: Invalid property.");
699         return 0;
700 }
701
702 .float GetResourceProperty(int resource_type)
703 {
704         switch (resource_type)
705         {
706                 case RESOURCE_HEALTH: { return health; }
707                 case RESOURCE_ARMOR: { return armorvalue; }
708                 case RESOURCE_SHELLS: { return ammo_shells; }
709                 case RESOURCE_BULLETS: { return ammo_nails; }
710                 case RESOURCE_ROCKETS: { return ammo_rockets; }
711                 case RESOURCE_CELLS: { return ammo_cells; }
712                 case RESOURCE_PLASMA: { return ammo_plasma; }
713                 case RESOURCE_FUEL: { return ammo_fuel; }
714         }
715         error("GetResourceProperty: Invalid resource type.");
716         return health;
717 }
718
719 float GetResourceLimit(entity e, int resource_type)
720 {
721         float limit;
722         switch (resource_type)
723         {
724                 case RESOURCE_HEALTH:
725                 {
726                         limit = autocvar_g_balance_health_limit;
727                         break;
728                 }
729                 case RESOURCE_ARMOR:
730                 {
731                         limit = autocvar_g_balance_armor_limit;
732                         break;
733                 }
734                 case RESOURCE_SHELLS:
735                 {
736                         limit = g_pickup_shells_max;
737                         break;
738                 }
739                 case RESOURCE_BULLETS:
740                 {
741                         limit = g_pickup_nails_max;
742                         break;
743                 }
744                 case RESOURCE_ROCKETS:
745                 {
746                         limit = g_pickup_rockets_max;
747                         break;
748                 }
749                 case RESOURCE_CELLS:
750                 {
751                         limit = g_pickup_cells_max;
752                         break;
753                 }
754                 case RESOURCE_PLASMA:
755                 {
756                         limit = g_pickup_plasma_max;
757                         break;
758                 }
759                 case RESOURCE_FUEL:
760                 {
761                         limit = autocvar_g_balance_fuel_limit;
762                         break;
763                 }
764                 default:
765                 {
766                         error("GetResourceLimit: Invalid resource type.");
767                         return 0;
768                 }
769         }
770         MUTATOR_CALLHOOK(GetResourceLimit, e, resource_type, limit);
771         limit = M_ARGV(2, float);
772         if (limit > RESOURCE_AMOUNT_HARD_LIMIT)
773         {
774                 limit = RESOURCE_AMOUNT_HARD_LIMIT;
775         }
776         return limit;
777 }
778
779 void GiveResource(entity receiver, int resource_type, float amount)
780 {
781         if (amount == 0)
782         {
783                 return;
784         }
785         bool forbid = MUTATOR_CALLHOOK(GiveResource, receiver, resource_type,
786                 amount);
787         if (forbid)
788         {
789                 return;
790         }
791         resource_type = M_ARGV(1, int);
792         amount = M_ARGV(2, float);
793         .float resource_property = GetResourceProperty(resource_type);
794         float max_amount = GetResourceLimit(receiver, resource_type);
795         receiver.(resource_property) = bound(receiver.(resource_property),
796                 receiver.(resource_property) + amount, max_amount);
797         switch (resource_type)
798         {
799                 case RESOURCE_HEALTH:
800                 {
801                         receiver.pauserothealth_finished =
802                                 max(receiver.pauserothealth_finished, time +
803                                 autocvar_g_balance_pause_health_rot);
804                         return;
805                 }
806                 case RESOURCE_ARMOR:
807                 {
808                         receiver.pauserotarmor_finished =
809                                 max(receiver.pauserotarmor_finished, time +
810                                 autocvar_g_balance_pause_armor_rot);
811                         return;
812                 }
813                 case RESOURCE_FUEL:
814                 {
815                         receiver.pauserotfuel_finished = max(receiver.pauserotfuel_finished,
816                                 time + autocvar_g_balance_pause_fuel_rot);
817                         return;
818                 }
819         }
820 }
821
822 void GiveResourceViaProperty(entity receiver, .float resource_property,
823         float amount)
824 {
825         GiveResource(receiver, GetResourceType(resource_property), amount);
826 }
827
828 void GivePlayerRandomWeapons(entity player, int num_weapons,
829         string weapon_names, float shells, float bullets, float rockets,
830         float cells, float plasma)
831 {
832         if (num_weapons == 0)
833         {
834                 return;
835         }
836         int num_potential_weapons = tokenize_console(weapon_names);
837         for (int i = 0; i < num_weapons; ++i)
838         {
839                 RandomSelection_Init();
840                 for (int j = 0; j < num_potential_weapons; ++j)
841                 {
842                         string weapon = argv(j);
843                         FOREACH(Weapons, it != WEP_Null,
844                         {
845                                 // Finding a weapon which player doesn't have.
846                                 if (!(player.weapons & it.m_wepset) && (it.netname == weapon))
847                                 {
848                                         RandomSelection_AddEnt(it, 1, 1);
849                                         break;
850                                 }
851                         });
852                 }
853                 if (RandomSelection_chosen_ent == NULL)
854                 {
855                         return;
856                 }
857                 player.weapons |= RandomSelection_chosen_ent.m_wepset;
858                 switch (RandomSelection_chosen_ent.ammo_field)
859                 {
860                         case (ammo_shells):
861                         {
862                                 if (player.ammo_shells != 0)
863                                 {
864                                         break;
865                                 }
866                                 GivePlayerResource(player, RESOURCE_SHELLS, shells);
867                                 break;
868                         }
869                         case (ammo_nails):
870                         {
871                                 if (player.ammo_nails != 0)
872                                 {
873                                         break;
874                                 }
875                                 GivePlayerResource(player, RESOURCE_BULLETS, bullets);
876                                 break;
877                         }
878                         case (ammo_rockets):
879                         {
880                                 if (player.ammo_rockets != 0)
881                                 {
882                                         break;
883                                 }
884                                 GivePlayerResource(player, RESOURCE_ROCKETS, rockets);
885                                 break;
886                         }
887                         case (ammo_cells):
888                         {
889                                 if (player.ammo_cells != 0)
890                                 {
891                                         break;
892                                 }
893                                 GivePlayerResource(player, RESOURCE_CELLS, cells);
894                                 break;
895                         }
896                         case (ammo_plasma):
897                         {
898                                 if (player.ammo_plasma != 0)
899                                 {
900                                         break;
901                                 }
902                                 GivePlayerResource(player, RESOURCE_PLASMA, plasma);
903                                 break;
904                         }
905                 }
906         }
907 }
908
909 float Item_GiveAmmoTo(entity item, entity player, .float ammotype, float ammomax)
910 {
911         if (!item.(ammotype))
912                 return false;
913
914         if (item.spawnshieldtime)
915         {
916                 if ((player.(ammotype) < ammomax) || item.pickup_anyway > 0)
917                 {
918                         float amount = item.(ammotype);
919                         if ((player.(ammotype) + amount) > ammomax)
920                         {
921                                 amount = ammomax - player.(ammotype);
922                         }
923                         GiveResourceViaProperty(player, ammotype, amount);
924                         return true;
925                 }
926         }
927         else if(g_weapon_stay == 2)
928         {
929                 float mi = min(item.(ammotype), ammomax);
930                 if (player.(ammotype) < mi)
931                 {
932                         GiveResourceViaProperty(player, ammotype, mi - player.(ammotype));
933                 }
934                 return true;
935         }
936         return false;
937 }
938
939 float Item_GiveTo(entity item, entity player)
940 {
941         float pickedup;
942
943         // if nothing happens to player, just return without taking the item
944         pickedup = false;
945         int _switchweapon = 0;
946         // in case the player has autoswitch enabled do the following:
947         // if the player is using their best weapon before items are given, they
948         // probably want to switch to an even better weapon after items are given
949
950         if(CS(player).autoswitch)
951         {
952                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
953                 {
954                         .entity weaponentity = weaponentities[slot];
955                         if(player.(weaponentity).m_weapon != WEP_Null || slot == 0)
956                         {
957                                 if(player.(weaponentity).m_switchweapon == w_getbestweapon(player, weaponentity))
958                                         _switchweapon |= BIT(slot);
959
960                                 if(!(player.weapons & WepSet_FromWeapon(player.(weaponentity).m_switchweapon)))
961                                         _switchweapon |= BIT(slot);
962                         }
963                 }
964         }
965         pickedup |= Item_GiveAmmoTo(item, player, health, item.max_health);
966         pickedup |= Item_GiveAmmoTo(item, player, armorvalue, item.max_armorvalue);
967         pickedup |= Item_GiveAmmoTo(item, player, ammo_shells, g_pickup_shells_max);
968         pickedup |= Item_GiveAmmoTo(item, player, ammo_nails, g_pickup_nails_max);
969         pickedup |= Item_GiveAmmoTo(item, player, ammo_rockets, g_pickup_rockets_max);
970         pickedup |= Item_GiveAmmoTo(item, player, ammo_cells, g_pickup_cells_max);
971         pickedup |= Item_GiveAmmoTo(item, player, ammo_plasma, g_pickup_plasma_max);
972         pickedup |= Item_GiveAmmoTo(item, player, ammo_fuel, g_pickup_fuel_max);
973         if (item.itemdef.instanceOfWeaponPickup)
974         {
975                 WepSet w;
976                 w = item.weapons;
977                 w &= ~player.weapons;
978
979                 if (w || (item.spawnshieldtime && item.pickup_anyway > 0))
980                 {
981                         pickedup = true;
982                         FOREACH(Weapons, it != WEP_Null, {
983                                 if(w & (it.m_wepset))
984                                 {
985                                         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
986                                         {
987                                                 .entity weaponentity = weaponentities[slot];
988                                                 if(player.(weaponentity).m_weapon != WEP_Null || slot == 0)
989                                                         W_DropEvent(wr_pickup, player, it.m_id, item, weaponentity);
990                                         }
991                                         W_GiveWeapon(player, it.m_id);
992                                 }
993                         });
994                 }
995         }
996
997         if (item.itemdef.instanceOfPowerup)
998         {
999                 if ((item.itemdef == ITEM_JetpackRegen) && !(player.items & IT_FUEL_REGEN))
1000                         Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_ITEM_FUELREGEN_GOT);
1001                 else if ((item.itemdef == ITEM_Jetpack) && !(player.items & IT_JETPACK))
1002                         Send_Notification(NOTIF_ONE, player, MSG_CENTER, CENTER_ITEM_JETPACK_GOT);
1003         }
1004
1005         int its;
1006         if((its = (item.items - (item.items & player.items)) & IT_PICKUPMASK))
1007         {
1008                 pickedup = true;
1009                 player.items |= its;
1010                 Send_Notification(NOTIF_ONE, player, MSG_INFO, INFO_ITEM_WEAPON_GOT, item.netname);
1011         }
1012
1013         if (item.strength_finished)
1014         {
1015                 pickedup = true;
1016                 player.strength_finished = max(player.strength_finished, time) + item.strength_finished;
1017         }
1018         if (item.invincible_finished)
1019         {
1020                 pickedup = true;
1021                 player.invincible_finished = max(player.invincible_finished, time) + item.invincible_finished;
1022         }
1023         if (item.superweapons_finished)
1024         {
1025                 pickedup = true;
1026                 player.superweapons_finished = max(player.superweapons_finished, time) + item.superweapons_finished;
1027         }
1028
1029 LABEL(skip)
1030
1031         // always eat teamed entities
1032         if(item.team)
1033                 pickedup = true;
1034
1035         if (!pickedup)
1036                 return 0;
1037
1038         // crude hack to enforce switching weapons
1039         if(g_cts && item.itemdef.instanceOfWeaponPickup)
1040         {
1041                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1042                 {
1043                         .entity weaponentity = weaponentities[slot];
1044                         if(player.(weaponentity).m_weapon != WEP_Null || slot == 0)
1045                                 W_SwitchWeapon_Force(player, Weapons_from(item.weapon), weaponentity);
1046                 }
1047                 return 1;
1048         }
1049
1050         if(_switchweapon)
1051         {
1052                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1053                 {
1054                         .entity weaponentity = weaponentities[slot];
1055                         if(_switchweapon & BIT(slot))
1056                         if(player.(weaponentity).m_switchweapon != w_getbestweapon(player, weaponentity))
1057                                 W_SwitchWeapon_Force(player, w_getbestweapon(player, weaponentity), weaponentity);
1058                 }
1059         }
1060
1061         return 1;
1062 }
1063
1064 void Item_Touch(entity this, entity toucher)
1065 {
1066
1067         // remove the item if it's currnetly in a NODROP brush or hits a NOIMPACT surface (such as sky)
1068         if (this.classname == "droppedweapon")
1069         {
1070                 if (ITEM_TOUCH_NEEDKILL())
1071                 {
1072                         delete(this);
1073                         return;
1074                 }
1075         }
1076
1077         if(!(toucher.flags & FL_PICKUPITEMS)
1078         || STAT(FROZEN, toucher)
1079         || IS_DEAD(toucher)
1080         || (this.solid != SOLID_TRIGGER)
1081         || (this.owner == toucher)
1082         || (time < this.item_spawnshieldtime)
1083         ) { return; }
1084
1085         switch (MUTATOR_CALLHOOK(ItemTouch, this, toucher))
1086         {
1087                 case MUT_ITEMTOUCH_RETURN: { return; }
1088                 case MUT_ITEMTOUCH_PICKUP: { toucher = M_ARGV(1, entity); goto pickup; }
1089         }
1090
1091         toucher = M_ARGV(1, entity);
1092
1093         if (this.classname == "droppedweapon")
1094         {
1095                 this.strength_finished = max(0, this.strength_finished - time);
1096                 this.invincible_finished = max(0, this.invincible_finished - time);
1097                 this.superweapons_finished = max(0, this.superweapons_finished - time);
1098         }
1099         entity it = this.itemdef;
1100         bool gave = ITEM_HANDLE(Pickup, it, this, toucher);
1101         if (!gave)
1102         {
1103                 if (this.classname == "droppedweapon")
1104                 {
1105                         // undo what we did above
1106                         this.strength_finished += time;
1107                         this.invincible_finished += time;
1108                         this.superweapons_finished += time;
1109                 }
1110                 return;
1111         }
1112
1113 LABEL(pickup)
1114
1115         toucher.last_pickup = time;
1116
1117         Send_Effect(EFFECT_ITEM_PICKUP, CENTER_OR_VIEWOFS(this), '0 0 0', 1);
1118         _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);
1119
1120         if (this.classname == "droppedweapon")
1121                 delete(this);
1122         else if (this.spawnshieldtime)
1123         {
1124                 entity e;
1125                 if(this.team)
1126                 {
1127                         RandomSelection_Init();
1128                         IL_EACH(g_items, it.team == this.team,
1129                         {
1130                                 if(it.itemdef) // is a registered item
1131                                 {
1132                                         Item_Show(it, -1);
1133                                         RandomSelection_AddEnt(it, it.cnt, 0);
1134                                 }
1135                         });
1136                         e = RandomSelection_chosen_ent;
1137                         Item_Show(e, 1); // reset its state so it is visible (extra sendflags doesn't matter, this happens anyway)
1138                 }
1139                 else
1140                         e = this;
1141                 Item_ScheduleRespawn(e);
1142         }
1143 }
1144
1145 void Item_Reset(entity this)
1146 {
1147         Item_Show(this, !this.state);
1148         setorigin(this, this.origin);
1149
1150         if (this.classname != "droppedweapon")
1151         {
1152                 setthink(this, Item_Think);
1153                 this.nextthink = time;
1154
1155                 if (this.waypointsprite_attached)
1156                         WaypointSprite_Kill(this.waypointsprite_attached);
1157
1158                 if (this.itemdef.instanceOfPowerup || (this.weapons & WEPSET_SUPERWEAPONS)) // do not spawn powerups initially!
1159                         Item_ScheduleInitialRespawn(this);
1160         }
1161 }
1162
1163 void Item_FindTeam(entity this)
1164 {
1165         entity e;
1166
1167         if(this.effects & EF_NODRAW)
1168         {
1169                 // marker for item team search
1170                 LOG_TRACE("Initializing item team ", ftos(this.team));
1171                 RandomSelection_Init();
1172                 IL_EACH(g_items, it.team == this.team,
1173                 {
1174                         if(it.itemdef) // is a registered item
1175                                 RandomSelection_AddEnt(it, it.cnt, 0);
1176                 });
1177
1178                 e = RandomSelection_chosen_ent;
1179                 e.state = 0;
1180                 Item_Show(e, 1);
1181
1182                 IL_EACH(g_items, it.team == this.team,
1183                 {
1184                         if(it.itemdef) // is a registered item
1185                         {
1186                                 if(it != e)
1187                                 {
1188                                         // make it non-spawned
1189                                         Item_Show(it, -1);
1190                                         it.state = 1; // state 1 = initially hidden item, apparently
1191                                 }
1192                                 it.effects &= ~EF_NODRAW;
1193                         }
1194                 });
1195
1196                 Item_Reset(this);
1197         }
1198 }
1199
1200 // Savage: used for item garbage-collection
1201 void RemoveItem(entity this)
1202 {
1203         if(wasfreed(this) || !this) { return; }
1204         Send_Effect(EFFECT_ITEM_PICKUP, CENTER_OR_VIEWOFS(this), '0 0 0', 1);
1205         delete(this);
1206 }
1207
1208 // pickup evaluation functions
1209 // these functions decide how desirable an item is to the bots
1210
1211 float generic_pickupevalfunc(entity player, entity item) {return item.bot_pickupbasevalue;}
1212
1213 float weapon_pickupevalfunc(entity player, entity item)
1214 {
1215         // See if I have it already
1216         if(player.weapons & item.weapons)
1217         {
1218                 // If I can pick it up
1219                 if(!item.spawnshieldtime)
1220                         return 0;
1221                 return ammo_pickupevalfunc(player, item);
1222         }
1223
1224         // reduce weapon value if bot already got a good arsenal
1225         float c = 1;
1226         int weapons_value = 0;
1227         FOREACH(Weapons, it != WEP_Null && (player.weapons & it.m_wepset), {
1228                 weapons_value += it.bot_pickupbasevalue;
1229         });
1230         c -= bound(0, weapons_value / 20000, 1) * 0.5;
1231
1232         return item.bot_pickupbasevalue * c;
1233 }
1234
1235 float ammo_pickupevalfunc(entity player, entity item)
1236 {
1237         bool need_shells = false, need_nails = false, need_rockets = false, need_cells = false, need_plasma = false, need_fuel = false;
1238         entity wpn = NULL;
1239         float c = 0;
1240         float rating = 0;
1241
1242         // Detect needed ammo
1243         if(item.itemdef.instanceOfWeaponPickup)
1244         {
1245                 entity ammo = NULL;
1246                 if(item.ammo_shells)       { need_shells  = true; ammo = ITEM_Shells;      }
1247                 else if(item.ammo_nails)   { need_nails   = true; ammo = ITEM_Bullets;     }
1248                 else if(item.ammo_rockets) { need_rockets = true; ammo = ITEM_Rockets;     }
1249                 else if(item.ammo_cells)   { need_cells   = true; ammo = ITEM_Cells;       }
1250                 else if(item.ammo_plasma)  { need_plasma  = true; ammo = ITEM_Plasma;      }
1251                 else if(item.ammo_fuel)    { need_fuel    = true; ammo = ITEM_JetpackFuel; }
1252
1253                 if(!ammo)
1254                         return 0;
1255                 wpn = item;
1256                 rating = ammo.m_botvalue;
1257         }
1258         else
1259         {
1260                 FOREACH(Weapons, it != WEP_Null, {
1261                         if(!(player.weapons & (it.m_wepset)))
1262                                 continue;
1263
1264                         switch(it.ammo_field)
1265                         {
1266                                 case ammo_shells:  need_shells  = true; break;
1267                                 case ammo_nails:   need_nails   = true; break;
1268                                 case ammo_rockets: need_rockets = true; break;
1269                                 case ammo_cells:   need_cells   = true; break;
1270                                 case ammo_plasma:  need_plasma  = true; break;
1271                                 case ammo_fuel:    need_fuel    = true; break;
1272                         }
1273                 });
1274                 rating = item.bot_pickupbasevalue;
1275         }
1276
1277         float noammorating = 0.5;
1278
1279         if ((need_shells) && (item.ammo_shells) && (player.ammo_shells < g_pickup_shells_max))
1280                 c = item.ammo_shells / max(noammorating, player.ammo_shells);
1281
1282         if ((need_nails) && (item.ammo_nails) && (player.ammo_nails < g_pickup_nails_max))
1283                 c = item.ammo_nails / max(noammorating, player.ammo_nails);
1284
1285         if ((need_rockets) && (item.ammo_rockets) && (player.ammo_rockets < g_pickup_rockets_max))
1286                 c = item.ammo_rockets / max(noammorating, player.ammo_rockets);
1287
1288         if ((need_cells) && (item.ammo_cells) && (player.ammo_cells < g_pickup_cells_max))
1289                 c = item.ammo_cells / max(noammorating, player.ammo_cells);
1290
1291         if ((need_plasma) && (item.ammo_plasma) && (player.ammo_plasma < g_pickup_plasma_max))
1292                 c = item.ammo_plasma / max(noammorating, player.ammo_plasma);
1293
1294         if ((need_fuel) && (item.ammo_fuel) && (player.ammo_fuel < g_pickup_fuel_max))
1295                 c = item.ammo_fuel / max(noammorating, player.ammo_fuel);
1296
1297         rating *= min(c, 2);
1298         if(wpn)
1299                 rating += wpn.bot_pickupbasevalue * 0.1;
1300         return rating;
1301 }
1302
1303 .int item_group;
1304 .int item_group_count;
1305 float healtharmor_pickupevalfunc(entity player, entity item)
1306 {
1307         float c = 0;
1308         float rating = item.bot_pickupbasevalue;
1309
1310         float itemarmor = item.armorvalue;
1311         float itemhealth = item.health;
1312
1313         if(item.item_group)
1314         {
1315                 itemarmor *= min(4, item.item_group_count);
1316                 itemhealth *= min(4, item.item_group_count);
1317         }
1318
1319         if (itemarmor && (player.armorvalue < item.max_armorvalue))
1320                 c = itemarmor / max(1, player.armorvalue * 2/3 + player.health * 1/3);
1321
1322         if (itemhealth && (player.health < item.max_health))
1323                 c = itemhealth / max(1, player.health);
1324
1325         rating *= min(2, c);
1326         return rating;
1327 }
1328
1329 void Item_Damage(entity this, entity inflictor, entity attacker, float damage, int deathtype, vector hitloc, vector force)
1330 {
1331         if(ITEM_DAMAGE_NEEDKILL(deathtype))
1332                 RemoveItem(this);
1333 }
1334
1335 void item_use(entity this, entity actor, entity trigger)
1336 {
1337         // use the touch function to handle collection
1338         gettouch(this)(this, actor);
1339 }
1340
1341 void _StartItem(entity this, entity def, float defaultrespawntime, float defaultrespawntimejitter)
1342 {
1343         string itemname = def.m_name;
1344         Model itemmodel = def.m_model;
1345     Sound pickupsound = def.m_sound;
1346         float(entity player, entity item) pickupevalfunc = def.m_pickupevalfunc;
1347         float pickupbasevalue = def.m_botvalue;
1348         int itemflags = def.m_itemflags;
1349
1350         startitem_failed = false;
1351
1352         this.item_model_ent = itemmodel;
1353     this.item_pickupsound_ent = pickupsound;
1354
1355     if(def.m_iteminit)
1356         def.m_iteminit(this);
1357
1358         if(!this.respawntime) // both need to be set
1359         {
1360                 this.respawntime = defaultrespawntime;
1361                 this.respawntimejitter = defaultrespawntimejitter;
1362         }
1363
1364         if(!this.pickup_anyway && def.m_pickupanyway)
1365                 this.pickup_anyway = def.m_pickupanyway();
1366
1367         int itemid = def.m_itemid;
1368         this.items = itemid;
1369         int weaponid = def.instanceOfWeaponPickup ? def.m_weapon.m_id : 0;
1370         this.weapon = weaponid;
1371
1372         if(!this.fade_end)
1373         {
1374                 this.fade_start = autocvar_g_items_mindist;
1375                 this.fade_end = autocvar_g_items_maxdist;
1376         }
1377
1378         if(weaponid)
1379                 this.weapons = WepSet_FromWeapon(Weapons_from(weaponid));
1380
1381         this.flags = FL_ITEM | itemflags;
1382         IL_PUSH(g_items, this);
1383
1384         if(MUTATOR_CALLHOOK(FilterItem, this)) // error means we do not want the item
1385         {
1386                 startitem_failed = true;
1387                 delete(this);
1388                 return;
1389         }
1390
1391         // is it a dropped weapon?
1392         if (this.classname == "droppedweapon")
1393         {
1394                 this.reset = SUB_Remove;
1395                 // it's a dropped weapon
1396                 set_movetype(this, MOVETYPE_TOSS);
1397
1398                 // Savage: remove thrown items after a certain period of time ("garbage collection")
1399                 setthink(this, RemoveItem);
1400                 this.nextthink = time + 20;
1401
1402                 this.takedamage = DAMAGE_YES;
1403                 this.event_damage = Item_Damage;
1404
1405                 if(this.strength_finished || this.invincible_finished || this.superweapons_finished)
1406                 {
1407                         // if item is worthless after a timer, have it expire then
1408                         this.nextthink = max(this.strength_finished, this.invincible_finished, this.superweapons_finished);
1409                 }
1410
1411                 // don't drop if in a NODROP zone (such as lava)
1412                 traceline(this.origin, this.origin, MOVE_NORMAL, this);
1413                 if (trace_dpstartcontents & DPCONTENTS_NODROP)
1414                 {
1415                         startitem_failed = true;
1416                         delete(this);
1417                         return;
1418                 }
1419         }
1420         else
1421         {
1422                 if(!have_pickup_item(this))
1423                 {
1424                         startitem_failed = true;
1425                         delete(this);
1426                         return;
1427                 }
1428
1429                 if(this.angles != '0 0 0')
1430                         this.SendFlags |= ISF_ANGLES;
1431
1432                 this.reset = Item_Reset;
1433                 // it's a level item
1434                 if(this.spawnflags & 1)
1435                         this.noalign = 1;
1436                 if (this.noalign > 0)
1437                         set_movetype(this, MOVETYPE_NONE);
1438                 else
1439                         set_movetype(this, MOVETYPE_TOSS);
1440                 // do item filtering according to game mode and other things
1441                 if (this.noalign <= 0)
1442                 {
1443                         // first nudge it off the floor a little bit to avoid math errors
1444                         setorigin(this, this.origin + '0 0 1');
1445                         // set item size before we spawn a spawnfunc_waypoint
1446                         setsize(this, def.m_mins, def.m_maxs);
1447                         this.SendFlags |= ISF_SIZE;
1448                         // note droptofloor returns false if stuck/or would fall too far
1449                         if (!this.noalign)
1450                                 droptofloor(this);
1451                         waypoint_spawnforitem(this);
1452                 }
1453
1454                 /*
1455                  * can't do it that way, as it would break maps
1456                  * TODO make a target_give like entity another way, that perhaps has
1457                  * the weapon name in a key
1458                 if(this.targetname)
1459                 {
1460                         // target_give not yet supported; maybe later
1461                         print("removed targeted ", this.classname, "\n");
1462                         startitem_failed = true;
1463                         delete(this);
1464                         return;
1465                 }
1466                 */
1467
1468                 if(this.targetname != "" && (this.spawnflags & 16))
1469                         this.use = item_use;
1470
1471                 if(autocvar_spawn_debug >= 2)
1472                 {
1473             // why not flags & fl_item?
1474                     FOREACH_ENTITY_RADIUS(this.origin, 3, it.is_item, {
1475                 LOG_TRACE("XXX Found duplicated item: ", itemname, vtos(this.origin));
1476                 LOG_TRACE(" vs ", it.netname, vtos(it.origin));
1477                 error("Mapper sucks.");
1478             });
1479                         this.is_item = true;
1480                 }
1481
1482                 weaponsInMap |= WepSet_FromWeapon(Weapons_from(weaponid));
1483
1484                 precache_model(this.model);
1485                 precache_sound(this.item_pickupsound);
1486
1487                 if (   def.instanceOfPowerup
1488                         || def.instanceOfWeaponPickup
1489                         || (def.instanceOfHealth && def != ITEM_HealthSmall)
1490                         || (def.instanceOfArmor && def != ITEM_ArmorSmall)
1491                         || (itemid & (IT_KEY1 | IT_KEY2))
1492                 ) this.target = "###item###"; // for finding the nearest item using find()
1493
1494                 Item_ItemsTime_SetTime(this, 0);
1495         }
1496
1497         this.bot_pickup = true;
1498         this.bot_pickupevalfunc = pickupevalfunc;
1499         this.bot_pickupbasevalue = pickupbasevalue;
1500         this.mdl = this.model ? this.model : strzone(this.item_model_ent.model_str());
1501         this.netname = itemname;
1502         settouch(this, Item_Touch);
1503         setmodel(this, MDL_Null); // precision set below
1504         //this.effects |= EF_LOWPRECISION;
1505
1506         setsize (this, this.pos1 =  def.m_mins, this.pos2 = def.m_maxs);
1507
1508         this.SendFlags |= ISF_SIZE;
1509
1510         if (!(this.spawnflags & 1024)) {
1511                 if(def.instanceOfPowerup)
1512                         this.ItemStatus |= ITS_ANIMATE1;
1513
1514                 if(this.armorvalue || this.health)
1515                         this.ItemStatus |= ITS_ANIMATE2;
1516         }
1517
1518         if(def.instanceOfWeaponPickup)
1519         {
1520                 if (this.classname != "droppedweapon") // if dropped, colormap is already set up nicely
1521                         this.colormap = 1024; // color shirt=0 pants=0 grey
1522                 else
1523                         this.gravity = 1;
1524                 if (!(this.spawnflags & 1024))
1525                         this.ItemStatus |= ITS_ANIMATE1;
1526                 this.SendFlags |= ISF_COLORMAP;
1527         }
1528
1529         this.state = 0;
1530         if(this.team) // broken, no idea why.
1531         {
1532                 if(!this.cnt)
1533                         this.cnt = 1; // item probability weight
1534
1535                 this.effects |= EF_NODRAW; // marker for item team search
1536                 InitializeEntity(this, Item_FindTeam, INITPRIO_FINDTARGET);
1537         }
1538         else
1539                 Item_Reset(this);
1540
1541         Net_LinkEntity(this, !(def.instanceOfPowerup || def.instanceOfHealth || def.instanceOfArmor), 0, ItemSend);
1542
1543         // call this hook after everything else has been done
1544         if (MUTATOR_CALLHOOK(Item_Spawn, this))
1545         {
1546                 startitem_failed = true;
1547                 delete(this);
1548                 return;
1549         }
1550
1551         setItemGroup(this);
1552 }
1553
1554 void StartItem(entity this, GameItem def)
1555 {
1556     _StartItem(
1557         this,
1558         this.itemdef = def,
1559         def.m_respawntime(), // defaultrespawntime
1560         def.m_respawntimejitter() // defaultrespawntimejitter
1561         );
1562 }
1563
1564 #define IS_SMALL(def) ((def.instanceOfHealth && def == ITEM_HealthSmall) || (def.instanceOfArmor && def == ITEM_ArmorSmall))
1565 int group_count = 1;
1566
1567 void setItemGroup(entity this)
1568 {
1569         if(!IS_SMALL(this.itemdef))
1570                 return;
1571
1572         FOREACH_ENTITY_RADIUS(this.origin, 120, (it != this) && IS_SMALL(it.itemdef),
1573         {
1574                 if(!this.item_group)
1575                 {
1576                         if(!it.item_group)
1577                         {
1578                                 it.item_group = group_count;
1579                                 group_count++;
1580                         }
1581                         this.item_group = it.item_group;
1582                 }
1583                 else // spawning item is already part of a item_group X
1584                 {
1585                         if(!it.item_group)
1586                                 it.item_group = this.item_group;
1587                         else if(it.item_group != this.item_group) // found an item near the spawning item that is part of a different item_group Y
1588                         {
1589                                 int grY = it.item_group;
1590                                 // move all items of item_group Y to item_group X
1591                                 IL_EACH(g_items, IS_SMALL(it.itemdef),
1592                                 {
1593                                         if(it.item_group == grY)
1594                                                 it.item_group = this.item_group;
1595                                 });
1596                         }
1597                 }
1598         });
1599 }
1600
1601 void setItemGroupCount()
1602 {
1603         for (int k = 1; k <= group_count; k++)
1604         {
1605                 int count = 0;
1606                 IL_EACH(g_items, IS_SMALL(it.itemdef) && it.item_group == k, { count++; });
1607                 if (count)
1608                         IL_EACH(g_items, IS_SMALL(it.itemdef) && it.item_group == k, { it.item_group_count = count; });
1609         }
1610 }
1611
1612 spawnfunc(item_rockets)
1613 {
1614     StartItem(this, ITEM_Rockets);
1615 }
1616
1617 spawnfunc(item_bullets)
1618 {
1619         if(!weaponswapping && autocvar_sv_q3acompat_machineshotgunswap &&
1620            (this.classname != "droppedweapon"))
1621         {
1622                 weaponswapping = true;
1623                 spawnfunc_item_shells(this);
1624                 weaponswapping = false;
1625                 return;
1626         }
1627
1628     StartItem(this, ITEM_Bullets);
1629 }
1630
1631 spawnfunc(item_cells)
1632 {
1633         StartItem(this, ITEM_Cells);
1634 }
1635
1636 spawnfunc(item_plasma)
1637 {
1638         StartItem(this, ITEM_Plasma);
1639 }
1640
1641 spawnfunc(item_shells)
1642 {
1643         if(!weaponswapping && autocvar_sv_q3acompat_machineshotgunswap &&
1644            (this.classname != "droppedweapon"))
1645         {
1646                 weaponswapping = true;
1647                 spawnfunc_item_bullets(this);
1648                 weaponswapping = false;
1649                 return;
1650         }
1651
1652         StartItem(this, ITEM_Shells);
1653 }
1654
1655 spawnfunc(item_armor_small)
1656 {
1657         StartItem(this, ITEM_ArmorSmall);
1658 }
1659
1660 spawnfunc(item_armor_medium)
1661 {
1662         StartItem(this, ITEM_ArmorMedium);
1663 }
1664
1665 spawnfunc(item_armor_big)
1666 {
1667         StartItem(this, ITEM_ArmorBig);
1668 }
1669
1670 spawnfunc(item_armor_mega)
1671 {
1672         StartItem(this, ITEM_ArmorMega);
1673 }
1674
1675 spawnfunc(item_health_small)
1676 {
1677         StartItem(this, ITEM_HealthSmall);
1678 }
1679
1680 spawnfunc(item_health_medium)
1681 {
1682     StartItem(this, ITEM_HealthMedium);
1683 }
1684
1685 spawnfunc(item_health_big)
1686 {
1687         StartItem(this, ITEM_HealthBig);
1688 }
1689
1690 spawnfunc(item_health_mega)
1691 {
1692     StartItem(this, ITEM_HealthMega);
1693 }
1694
1695 // support old misnamed entities
1696 spawnfunc(item_armor1) { spawnfunc_item_armor_small(this); }  // FIXME: in Quake this is green armor, in Xonotic maps it is an armor shard
1697 spawnfunc(item_armor25) { spawnfunc_item_armor_mega(this); }
1698 spawnfunc(item_armor_large) { spawnfunc_item_armor_mega(this); }
1699 spawnfunc(item_health1) { spawnfunc_item_health_small(this); }
1700 spawnfunc(item_health25) { spawnfunc_item_health_medium(this); }
1701 spawnfunc(item_health_large) { spawnfunc_item_health_big(this); }
1702 spawnfunc(item_health100) { spawnfunc_item_health_mega(this); }
1703
1704 spawnfunc(item_strength)
1705 {
1706         StartItem(this, ITEM_Strength);
1707 }
1708
1709 spawnfunc(item_invincible)
1710 {
1711         StartItem(this, ITEM_Shield);
1712 }
1713
1714 // compatibility:
1715 spawnfunc(item_quad) { this.classname = "item_strength";spawnfunc_item_strength(this);}
1716
1717 void target_items_use(entity this, entity actor, entity trigger)
1718 {
1719         if(actor.classname == "droppedweapon")
1720         {
1721                 EXACTTRIGGER_TOUCH(this, trigger);
1722                 delete(actor);
1723                 return;
1724         }
1725
1726         if (!IS_PLAYER(actor) || IS_DEAD(actor))
1727                 return;
1728
1729         if(trigger.solid == SOLID_TRIGGER)
1730         {
1731                 EXACTTRIGGER_TOUCH(this, trigger);
1732         }
1733
1734         IL_EACH(g_items, it.enemy == actor && it.classname == "droppedweapon",
1735         {
1736                 delete(it);
1737         });
1738
1739         if(GiveItems(actor, 0, tokenize_console(this.netname)))
1740                 centerprint(actor, this.message);
1741 }
1742
1743 spawnfunc(target_items)
1744 {
1745         int n;
1746         string s;
1747
1748         this.use = target_items_use;
1749         if(!this.strength_finished)
1750                 this.strength_finished = autocvar_g_balance_powerup_strength_time;
1751         if(!this.invincible_finished)
1752                 this.invincible_finished = autocvar_g_balance_powerup_invincible_time;
1753         if(!this.superweapons_finished)
1754                 this.superweapons_finished = autocvar_g_balance_superweapons_time;
1755
1756         n = tokenize_console(this.netname);
1757         if(argv(0) == "give")
1758         {
1759                 this.netname = substring(this.netname, argv_start_index(1), argv_end_index(-1) - argv_start_index(1));
1760         }
1761         else
1762         {
1763                 for(int j = 0; j < n; ++j)
1764                 {
1765                         if     (argv(j) == "unlimited_ammo")         this.items |= IT_UNLIMITED_AMMO;
1766                         else if(argv(j) == "unlimited_weapon_ammo")  this.items |= IT_UNLIMITED_WEAPON_AMMO;
1767                         else if(argv(j) == "unlimited_superweapons") this.items |= IT_UNLIMITED_SUPERWEAPONS;
1768                         else if(argv(j) == "strength")               this.items |= ITEM_Strength.m_itemid;
1769                         else if(argv(j) == "invincible")             this.items |= ITEM_Shield.m_itemid;
1770                         else if(argv(j) == "superweapons")           this.items |= IT_SUPERWEAPON;
1771                         else if(argv(j) == "jetpack")                this.items |= ITEM_Jetpack.m_itemid;
1772                         else if(argv(j) == "fuel_regen")             this.items |= ITEM_JetpackRegen.m_itemid;
1773                         else
1774                         {
1775                                 FOREACH(Buffs, it != BUFF_Null,
1776                                 {
1777                                         s = Buff_UndeprecateName(argv(j));
1778                                         if(s == it.m_name)
1779                                         {
1780                                                 this.buffs |= (it.m_itemid);
1781                                                 break;
1782                                         }
1783                                 });
1784                                 FOREACH(Weapons, it != WEP_Null, {
1785                                         s = W_UndeprecateName(argv(j));
1786                                         if(s == it.netname)
1787                                         {
1788                                                 this.weapons |= (it.m_wepset);
1789                                                 if(this.spawnflags == 0 || this.spawnflags == 2)
1790                                                         it.wr_init(it);
1791                                                 break;
1792                                         }
1793                                 });
1794                         }
1795                 }
1796
1797                 string itemprefix, valueprefix;
1798                 if(this.spawnflags == 0)
1799                 {
1800                         itemprefix = "";
1801                         valueprefix = "";
1802                 }
1803                 else if(this.spawnflags == 1)
1804                 {
1805                         itemprefix = "max ";
1806                         valueprefix = "max ";
1807                 }
1808                 else if(this.spawnflags == 2)
1809                 {
1810                         itemprefix = "min ";
1811                         valueprefix = "min ";
1812                 }
1813                 else if(this.spawnflags == 4)
1814                 {
1815                         itemprefix = "minus ";
1816                         valueprefix = "max ";
1817                 }
1818                 else
1819                 {
1820                         error("invalid spawnflags");
1821                         itemprefix = valueprefix = string_null;
1822                 }
1823
1824                 this.netname = "";
1825                 this.netname = sprintf("%s %s%d %s", this.netname, itemprefix, boolean(this.items & IT_UNLIMITED_WEAPON_AMMO), "unlimited_weapon_ammo");
1826                 this.netname = sprintf("%s %s%d %s", this.netname, itemprefix, boolean(this.items & IT_UNLIMITED_SUPERWEAPONS), "unlimited_superweapons");
1827                 this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, this.strength_finished * boolean(this.items & ITEM_Strength.m_itemid), "strength");
1828                 this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, this.invincible_finished * boolean(this.items & ITEM_Shield.m_itemid), "invincible");
1829                 this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, this.superweapons_finished * boolean(this.items & IT_SUPERWEAPON), "superweapons");
1830                 this.netname = sprintf("%s %s%d %s", this.netname, itemprefix, boolean(this.items & ITEM_Jetpack.m_itemid), "jetpack");
1831                 this.netname = sprintf("%s %s%d %s", this.netname, itemprefix, boolean(this.items & ITEM_JetpackRegen.m_itemid), "fuel_regen");
1832                 if(this.ammo_shells != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.ammo_shells), "shells");
1833                 if(this.ammo_nails != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.ammo_nails), "nails");
1834                 if(this.ammo_rockets != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.ammo_rockets), "rockets");
1835                 if(this.ammo_cells != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.ammo_cells), "cells");
1836                 if(this.ammo_plasma != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.ammo_plasma), "plasma");
1837                 if(this.ammo_fuel != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.ammo_fuel), "fuel");
1838                 if(this.health != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.health), "health");
1839                 if(this.armorvalue != 0) this.netname = sprintf("%s %s%d %s", this.netname, valueprefix, max(0, this.armorvalue), "armor");
1840                 FOREACH(Buffs, it != BUFF_Null, this.netname = sprintf("%s %s%d %s", this.netname, itemprefix, !!(this.buffs & (it.m_itemid)), it.m_name));
1841                 FOREACH(Weapons, it != WEP_Null, this.netname = sprintf("%s %s%d %s", this.netname, itemprefix, !!(this.weapons & (it.m_wepset)), it.netname));
1842         }
1843         this.netname = strzone(this.netname);
1844         //print(this.netname, "\n");
1845
1846         n = tokenize_console(this.netname);
1847         for(int j = 0; j < n; ++j)
1848         {
1849                 FOREACH(Weapons, it != WEP_Null && W_UndeprecateName(argv(j)) == it.netname, {
1850             it.wr_init(it);
1851             break;
1852                 });
1853         }
1854 }
1855
1856 spawnfunc(item_fuel)
1857 {
1858         StartItem(this, ITEM_JetpackFuel);
1859 }
1860
1861 spawnfunc(item_fuel_regen)
1862 {
1863         if(start_items & ITEM_JetpackRegen.m_itemid)
1864         {
1865                 spawnfunc_item_fuel(this);
1866                 return;
1867         }
1868         StartItem(this, ITEM_JetpackRegen);
1869 }
1870
1871 spawnfunc(item_jetpack)
1872 {
1873         if(start_items & ITEM_Jetpack.m_itemid)
1874         {
1875                 spawnfunc_item_fuel(this);
1876                 return;
1877         }
1878         StartItem(this, ITEM_Jetpack);
1879 }
1880
1881 float GiveWeapon(entity e, float wpn, float op, float val)
1882 {
1883         WepSet v0, v1;
1884         WepSet s = WepSet_FromWeapon(Weapons_from(wpn));
1885         v0 = (e.weapons & s);
1886         switch(op)
1887         {
1888                 case OP_SET:
1889                         if(val > 0)
1890                                 e.weapons |= s;
1891                         else
1892                                 e.weapons &= ~s;
1893                         break;
1894                 case OP_MIN:
1895                 case OP_PLUS:
1896                         if(val > 0)
1897                                 e.weapons |= s;
1898                         break;
1899                 case OP_MAX:
1900                         if(val <= 0)
1901                                 e.weapons &= ~s;
1902                         break;
1903                 case OP_MINUS:
1904                         if(val > 0)
1905                                 e.weapons &= ~s;
1906                         break;
1907         }
1908         v1 = (e.weapons & s);
1909         return (v0 != v1);
1910 }
1911
1912 bool GiveBuff(entity e, Buff thebuff, int op, int val)
1913 {
1914         bool had_buff = (e.buffs & thebuff.m_itemid);
1915         switch(op)
1916         {
1917                 case OP_SET:
1918                         if(val > 0)
1919                                 e.buffs |= thebuff.m_itemid;
1920                         else
1921                                 e.buffs &= ~thebuff.m_itemid;
1922                         break;
1923                 case OP_MIN:
1924                 case OP_PLUS:
1925                         if(val > 0)
1926                                 e.buffs |= thebuff.m_itemid;
1927                         break;
1928                 case OP_MAX:
1929                         if(val <= 0)
1930                                 e.buffs &= ~thebuff.m_itemid;
1931                         break;
1932                 case OP_MINUS:
1933                         if(val > 0)
1934                                 e.buffs &= ~thebuff.m_itemid;
1935                         break;
1936         }
1937         bool have_buff = (e.buffs & thebuff.m_itemid);
1938         return (had_buff != have_buff);
1939 }
1940
1941 void GiveSound(entity e, float v0, float v1, float t, Sound snd_incr, Sound snd_decr)
1942 {
1943         if(v1 == v0)
1944                 return;
1945         if(v1 <= v0 - t)
1946         {
1947                 if(snd_decr != NULL)
1948                         sound (e, CH_TRIGGER, snd_decr, VOL_BASE, ATTEN_NORM);
1949         }
1950         else if(v0 >= v0 + t)
1951         {
1952                 if(snd_incr != NULL)
1953                         sound (e, CH_TRIGGER, snd_incr, VOL_BASE, ATTEN_NORM);
1954         }
1955 }
1956
1957 void GiveRot(entity e, float v0, float v1, .float rotfield, float rottime, .float regenfield, float regentime)
1958 {
1959         if(v0 < v1)
1960                 e.(rotfield) = max(e.(rotfield), time + rottime);
1961         else if(v0 > v1)
1962                 e.(regenfield) = max(e.(regenfield), time + regentime);
1963 }
1964 float GiveItems(entity e, float beginarg, float endarg)
1965 {
1966         float got, i, val, op;
1967         string cmd;
1968
1969         val = 999;
1970         op = OP_SET;
1971
1972         got = 0;
1973
1974         int _switchweapon = 0;
1975
1976         if(CS(e).autoswitch)
1977         {
1978                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1979                 {
1980                         .entity weaponentity = weaponentities[slot];
1981                         if(e.(weaponentity).m_weapon != WEP_Null || slot == 0)
1982                         if(e.(weaponentity).m_switchweapon == w_getbestweapon(e, weaponentity))
1983                                 _switchweapon |= BIT(slot);
1984                 }
1985         }
1986
1987         e.strength_finished = max(0, e.strength_finished - time);
1988         e.invincible_finished = max(0, e.invincible_finished - time);
1989         e.superweapons_finished = max(0, e.superweapons_finished - time);
1990
1991         PREGIVE(e, items);
1992         PREGIVE_WEAPONS(e);
1993         PREGIVE(e, strength_finished);
1994         PREGIVE(e, invincible_finished);
1995         PREGIVE(e, superweapons_finished);
1996         PREGIVE(e, ammo_nails);
1997         PREGIVE(e, ammo_cells);
1998         PREGIVE(e, ammo_plasma);
1999         PREGIVE(e, ammo_shells);
2000         PREGIVE(e, ammo_rockets);
2001         PREGIVE(e, ammo_fuel);
2002         PREGIVE(e, armorvalue);
2003         PREGIVE(e, health);
2004
2005         for(i = beginarg; i < endarg; ++i)
2006         {
2007                 cmd = argv(i);
2008
2009                 if(cmd == "0" || stof(cmd))
2010                 {
2011                         val = stof(cmd);
2012                         continue;
2013                 }
2014                 switch(cmd)
2015                 {
2016                         case "no":
2017                                 op = OP_MAX;
2018                                 val = 0;
2019                                 continue;
2020                         case "max":
2021                                 op = OP_MAX;
2022                                 continue;
2023                         case "min":
2024                                 op = OP_MIN;
2025                                 continue;
2026                         case "plus":
2027                                 op = OP_PLUS;
2028                                 continue;
2029                         case "minus":
2030                                 op = OP_MINUS;
2031                                 continue;
2032                         case "ALL":
2033                                 got += GiveBit(e, items, ITEM_JetpackRegen.m_itemid, op, val);
2034                                 got += GiveValue(e, strength_finished, op, val);
2035                                 got += GiveValue(e, invincible_finished, op, val);
2036                                 got += GiveValue(e, superweapons_finished, op, val);
2037                                 got += GiveBit(e, items, IT_UNLIMITED_AMMO, op, val);
2038                         case "all":
2039                                 got += GiveBit(e, items, ITEM_Jetpack.m_itemid, op, val);
2040                                 got += GiveValue(e, health, op, val);
2041                                 got += GiveValue(e, armorvalue, op, val);
2042                         case "allweapons":
2043                                 FOREACH(Weapons, it != WEP_Null && !(it.spawnflags & WEP_FLAG_MUTATORBLOCKED), got += GiveWeapon(e, it.m_id, op, val));
2044                         //case "allbuffs": // all buffs makes a player god, do not want!
2045                                 //FOREACH(Buffs, it != BUFF_Null, got += GiveBuff(e, it.m_itemid, op, val));
2046                         case "allammo":
2047                                 got += GiveValue(e, ammo_cells, op, val);
2048                                 got += GiveValue(e, ammo_plasma, op, val);
2049                                 got += GiveValue(e, ammo_shells, op, val);
2050                                 got += GiveValue(e, ammo_nails, op, val);
2051                                 got += GiveValue(e, ammo_rockets, op, val);
2052                                 got += GiveValue(e, ammo_fuel, op, val);
2053                                 break;
2054                         case "unlimited_ammo":
2055                                 got += GiveBit(e, items, IT_UNLIMITED_AMMO, op, val);
2056                                 break;
2057                         case "unlimited_weapon_ammo":
2058                                 got += GiveBit(e, items, IT_UNLIMITED_WEAPON_AMMO, op, val);
2059                                 break;
2060                         case "unlimited_superweapons":
2061                                 got += GiveBit(e, items, IT_UNLIMITED_SUPERWEAPONS, op, val);
2062                                 break;
2063                         case "jetpack":
2064                                 got += GiveBit(e, items, ITEM_Jetpack.m_itemid, op, val);
2065                                 break;
2066                         case "fuel_regen":
2067                                 got += GiveBit(e, items, ITEM_JetpackRegen.m_itemid, op, val);
2068                                 break;
2069                         case "strength":
2070                                 got += GiveValue(e, strength_finished, op, val);
2071                                 break;
2072                         case "invincible":
2073                                 got += GiveValue(e, invincible_finished, op, val);
2074                                 break;
2075                         case "superweapons":
2076                                 got += GiveValue(e, superweapons_finished, op, val);
2077                                 break;
2078                         case "cells":
2079                                 got += GiveValue(e, ammo_cells, op, val);
2080                                 break;
2081                         case "plasma":
2082                                 got += GiveValue(e, ammo_plasma, op, val);
2083                                 break;
2084                         case "shells":
2085                                 got += GiveValue(e, ammo_shells, op, val);
2086                                 break;
2087                         case "nails":
2088                         case "bullets":
2089                                 got += GiveValue(e, ammo_nails, op, val);
2090                                 break;
2091                         case "rockets":
2092                                 got += GiveValue(e, ammo_rockets, op, val);
2093                                 break;
2094                         case "health":
2095                                 got += GiveValue(e, health, op, val);
2096                                 break;
2097                         case "armor":
2098                                 got += GiveValue(e, armorvalue, op, val);
2099                                 break;
2100                         case "fuel":
2101                                 got += GiveValue(e, ammo_fuel, op, val);
2102                                 break;
2103                         default:
2104                                 FOREACH(Buffs, it != BUFF_Null && Buff_UndeprecateName(cmd) == it.m_name,
2105                                 {
2106                                         got += GiveBuff(e, it, op, val);
2107                                         break;
2108                                 });
2109                                 FOREACH(Weapons, it != WEP_Null && W_UndeprecateName(cmd) == it.netname, {
2110                     got += GiveWeapon(e, it.m_id, op, val);
2111                     break;
2112                                 });
2113                                 break;
2114                 }
2115                 val = 999;
2116                 op = OP_SET;
2117         }
2118
2119         POSTGIVE_BIT(e, items, ITEM_JetpackRegen.m_itemid, SND_ITEMPICKUP, SND_Null);
2120         POSTGIVE_BIT(e, items, IT_UNLIMITED_SUPERWEAPONS, SND_POWERUP, SND_POWEROFF);
2121         POSTGIVE_BIT(e, items, IT_UNLIMITED_WEAPON_AMMO, SND_POWERUP, SND_POWEROFF);
2122         POSTGIVE_BIT(e, items, ITEM_Jetpack.m_itemid, SND_ITEMPICKUP, SND_Null);
2123         FOREACH(Weapons, it != WEP_Null, {
2124                 POSTGIVE_WEAPON(e, it, SND_WEAPONPICKUP, SND_Null);
2125                 if(!(save_weapons & (it.m_wepset)))
2126                         if(e.weapons & (it.m_wepset))
2127                                 it.wr_init(it);
2128         });
2129         POSTGIVE_VALUE(e, strength_finished, 1, SND_POWERUP, SND_POWEROFF);
2130         POSTGIVE_VALUE(e, invincible_finished, 1, SND_Shield, SND_POWEROFF);
2131         //POSTGIVE_VALUE(e, superweapons_finished, 1, SND_Null, SND_Null);
2132         POSTGIVE_VALUE(e, ammo_nails, 0, SND_ITEMPICKUP, SND_Null);
2133         POSTGIVE_VALUE(e, ammo_cells, 0, SND_ITEMPICKUP, SND_Null);
2134         POSTGIVE_VALUE(e, ammo_plasma, 0, SND_ITEMPICKUP, SND_Null);
2135         POSTGIVE_VALUE(e, ammo_shells, 0, SND_ITEMPICKUP, SND_Null);
2136         POSTGIVE_VALUE(e, ammo_rockets, 0, SND_ITEMPICKUP, SND_Null);
2137         POSTGIVE_VALUE_ROT(e, ammo_fuel, 1, pauserotfuel_finished, autocvar_g_balance_pause_fuel_rot, pauseregen_finished, autocvar_g_balance_pause_fuel_regen, SND_ITEMPICKUP, SND_Null);
2138         POSTGIVE_VALUE_ROT(e, armorvalue, 1, pauserotarmor_finished, autocvar_g_balance_pause_armor_rot, pauseregen_finished, autocvar_g_balance_pause_health_regen, SND_ARMOR25, SND_Null);
2139         POSTGIVE_VALUE_ROT(e, health, 1, pauserothealth_finished, autocvar_g_balance_pause_health_rot, pauseregen_finished, autocvar_g_balance_pause_health_regen, SND_MEGAHEALTH, SND_Null);
2140
2141         if(e.superweapons_finished <= 0)
2142                 if(e.weapons & WEPSET_SUPERWEAPONS)
2143                         e.superweapons_finished = autocvar_g_balance_superweapons_time;
2144
2145         if(e.strength_finished <= 0)
2146                 e.strength_finished = 0;
2147         else
2148                 e.strength_finished += time;
2149         if(e.invincible_finished <= 0)
2150                 e.invincible_finished = 0;
2151         else
2152                 e.invincible_finished += time;
2153         if(e.superweapons_finished <= 0)
2154                 e.superweapons_finished = 0;
2155         else
2156                 e.superweapons_finished += time;
2157
2158         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
2159         {
2160                 .entity weaponentity = weaponentities[slot];
2161                 if(e.(weaponentity).m_weapon != WEP_Null || slot == 0)
2162                 if(!(e.weapons & WepSet_FromWeapon(e.(weaponentity).m_switchweapon)))
2163                         _switchweapon |= BIT(slot);
2164         }
2165
2166         if(_switchweapon)
2167         {
2168                 for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
2169                 {
2170                         .entity weaponentity = weaponentities[slot];
2171                         if(_switchweapon & BIT(slot))
2172                         {
2173                                 Weapon wep = w_getbestweapon(e, weaponentity);
2174                                 if(wep != e.(weaponentity).m_switchweapon)
2175                                         W_SwitchWeapon_Force(e, wep, weaponentity);
2176                         }
2177                 }
2178         }
2179
2180         return got;
2181 }
2182 #endif