b731bcde2468c9b0f5f3a618d0babd2115be3de5
[xonotic/darkplaces.git] / prvm_cmds.c
1 // AK
2 // Basically every vm builtin cmd should be in here.
3 // All 3 builtin and extension lists can be found here
4 // cause large (I think they will) parts are from pr_cmds the same copyright like in pr_cmds
5 // also applies here
6
7 #include "quakedef.h"
8
9 #include "prvm_cmds.h"
10 #include "libcurl.h"
11 #include <time.h>
12
13 #include "cl_collision.h"
14 #include "clvm_cmds.h"
15 #include "csprogs.h"
16 #include "ft2.h"
17 #include "mdfour.h"
18
19 extern cvar_t prvm_backtraceforwarnings;
20 #ifdef USEODE
21 extern dllhandle_t ode_dll;
22 #endif
23
24 // LadyHavoc: changed this to NOT use a return statement, so that it can be used in functions that must return a value
25 void VM_Warning(prvm_prog_t *prog, const char *fmt, ...)
26 {
27         va_list argptr;
28         char msg[MAX_INPUTLINE];
29         static double recursive = -1;
30
31         va_start(argptr,fmt);
32         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
33         va_end(argptr);
34
35         Con_Printf(CON_WARN "%s", msg);
36
37         // TODO: either add a cvar/cmd to control the state dumping or replace some of the calls with Con_Printf [9/13/2006 Black]
38         if(prvm_backtraceforwarnings.integer && recursive != host.realtime) // NOTE: this compares to the time, just in case if PRVM_PrintState causes a Host_Error and keeps recursive set
39         {
40                 recursive = host.realtime;
41                 PRVM_PrintState(prog, 0);
42                 recursive = -1;
43         }
44 }
45
46
47 //============================================================================
48 // Common
49
50 // TODO DONE: move vm_files and vm_fssearchlist to prvm_prog_t struct
51 // TODO: move vm_files and vm_fssearchlist back [9/13/2006 Black]
52 // TODO: (move vm_files and vm_fssearchlist to prvm_prog_t struct again) [2007-01-23 LadyHavoc]
53 // TODO: will this war ever end? [2007-01-23 LadyHavoc]
54
55 void VM_CheckEmptyString(prvm_prog_t *prog, const char *s)
56 {
57         if (ISWHITESPACE(s[0]))
58                 prog->error_cmd("%s: Bad string", prog->name);
59 }
60
61 qbool PRVM_ConsoleCommand (prvm_prog_t *prog, const char *text, int *func, qbool preserve_self, int curself, double ptime, qbool prog_loaded, const char *error_message)
62 {
63         int restorevm_tempstringsbuf_cursize;
64         int save_self = 0; // hush compiler warning
65         qbool r = false;
66
67         if(!prog_loaded)
68                 return false;
69
70         if(func)
71         {
72                 if(preserve_self)
73                         save_self = PRVM_gameglobaledict(self);
74                 if(ptime)
75                         PRVM_gameglobalfloat(time) = ptime;
76                 PRVM_gameglobaledict(self) = curself;
77                 restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
78                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, text);
79                 prog->ExecuteProgram(prog, *func, error_message);
80                 prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
81                 if(preserve_self)
82                         PRVM_gameglobaledict(self) = save_self;
83                 r = (int) PRVM_G_FLOAT(OFS_RETURN) != 0;
84         }
85
86         return r;
87 }
88
89 void VM_GenerateFrameGroupBlend(prvm_prog_t *prog, framegroupblend_t *framegroupblend, const prvm_edict_t *ed)
90 {
91         // self.frame is the interpolation target (new frame)
92         // self.frame1time is the animation base time for the interpolation target
93         // self.frame2 is the interpolation start (previous frame)
94         // self.frame2time is the animation base time for the interpolation start
95         // self.lerpfrac is the interpolation strength for self.frame2
96         // self.lerpfrac3 is the interpolation strength for self.frame3
97         // self.lerpfrac4 is the interpolation strength for self.frame4
98         // pitch angle on a player model where the animator set up 5 sets of
99         // animations and the csqc simply lerps between sets)
100         framegroupblend[0].frame = (int) PRVM_gameedictfloat(ed, frame     );
101         framegroupblend[1].frame = (int) PRVM_gameedictfloat(ed, frame2    );
102         framegroupblend[2].frame = (int) PRVM_gameedictfloat(ed, frame3    );
103         framegroupblend[3].frame = (int) PRVM_gameedictfloat(ed, frame4    );
104         framegroupblend[0].start =       PRVM_gameedictfloat(ed, frame1time);
105         framegroupblend[1].start =       PRVM_gameedictfloat(ed, frame2time);
106         framegroupblend[2].start =       PRVM_gameedictfloat(ed, frame3time);
107         framegroupblend[3].start =       PRVM_gameedictfloat(ed, frame4time);
108         framegroupblend[1].lerp  =       PRVM_gameedictfloat(ed, lerpfrac  );
109         framegroupblend[2].lerp  =       PRVM_gameedictfloat(ed, lerpfrac3 );
110         framegroupblend[3].lerp  =       PRVM_gameedictfloat(ed, lerpfrac4 );
111         // assume that the (missing) lerpfrac1 is whatever remains after lerpfrac2+lerpfrac3+lerpfrac4 are summed
112         framegroupblend[0].lerp = 1 - framegroupblend[1].lerp - framegroupblend[2].lerp - framegroupblend[3].lerp;
113 }
114
115 // LadyHavoc: quite tempting to break apart this function to reuse the
116 //            duplicated code, but I suspect it is better for performance
117 //            this way
118 void VM_FrameBlendFromFrameGroupBlend(frameblend_t *frameblend, const framegroupblend_t *framegroupblend, const model_t *model, double curtime)
119 {
120         int sub2, numframes, f, i, k;
121         int isfirstframegroup = true;
122         int nolerp;
123         double sublerp, lerp, d;
124         const animscene_t *scene;
125         const framegroupblend_t *g;
126         frameblend_t *blend = frameblend;
127
128         memset(blend, 0, MAX_FRAMEBLENDS * sizeof(*blend));
129
130         // rpolzer: Not testing isanimated here - a model might have
131         // "animations" that move no vertices (but only bones), thus rendering
132         // may assume it's not animated while processing can't.
133         if (!model)
134         {
135                 blend[0].lerp = 1;
136                 return;
137         }
138
139         nolerp = ((model->type == mod_sprite) ? !r_lerpsprites.integer : !r_lerpmodels.integer) || (model->nolerp == true);
140         numframes = model->numframes;
141         for (k = 0, g = framegroupblend;k < MAX_FRAMEGROUPBLENDS;k++, g++)
142         {
143                 f = g->frame;
144                 if ((unsigned int)f >= (unsigned int)numframes)
145                 {
146                         if (developer_extra.integer)
147                                 Con_DPrintf("VM_FrameBlendFromFrameGroupBlend: no such frame %d in model %s\n", f, model->name);
148                         f = 0;
149                 }
150                 d = lerp = g->lerp;
151                 if (lerp <= 0)
152                         continue;
153                 if (nolerp)
154                 {
155                         if (isfirstframegroup)
156                         {
157                                 d = lerp = 1;
158                                 isfirstframegroup = false;
159                         }
160                         else
161                                 continue;
162                 }
163                 if (model->animscenes)
164                 {
165                         scene = model->animscenes + f;
166                         f = scene->firstframe;
167                         if (scene->framecount > 1)
168                         {
169                                 // this code path is only used on .zym models and torches
170                                 sublerp = scene->framerate * (curtime - g->start);
171                                 f = (int) floor(sublerp);
172                                 sublerp -= f;
173                                 sub2 = f + 1;
174                                 if (sublerp < (1.0 / 65536.0f))
175                                         sublerp = 0;
176                                 if (sublerp > (65535.0f / 65536.0f))
177                                         sublerp = 1;
178                                 if (nolerp)
179                                         sublerp = 0;
180                                 if (scene->loop)
181                                 {
182                                         f = (f % scene->framecount);
183                                         sub2 = (sub2 % scene->framecount);
184                                 }
185                                 f = bound(0, f, (scene->framecount - 1)) + scene->firstframe;
186                                 sub2 = bound(0, sub2, (scene->framecount - 1)) + scene->firstframe;
187                                 d = sublerp * lerp;
188                                 // two framelerps produced from one animation
189                                 if (d > 0)
190                                 {
191                                         for (i = 0;i < MAX_FRAMEBLENDS;i++)
192                                         {
193                                                 if (blend[i].lerp <= 0 || blend[i].subframe == sub2)
194                                                 {
195                                                         blend[i].subframe = sub2;
196                                                         blend[i].lerp += d;
197                                                         break;
198                                                 }
199                                         }
200                                 }
201                                 d = (1 - sublerp) * lerp;
202                         }
203                 }
204                 if (d > 0)
205                 {
206                         for (i = 0;i < MAX_FRAMEBLENDS;i++)
207                         {
208                                 if (blend[i].lerp <= 0 || blend[i].subframe == f)
209                                 {
210                                         blend[i].subframe = f;
211                                         blend[i].lerp += d;
212                                         break;
213                                 }
214                         }
215                 }
216         }
217 }
218
219 void VM_UpdateEdictSkeleton(prvm_prog_t *prog, prvm_edict_t *ed, const model_t *edmodel, const frameblend_t *frameblend)
220 {
221         if (ed->priv.server->skeleton.model != edmodel)
222         {
223                 VM_RemoveEdictSkeleton(prog, ed);
224                 ed->priv.server->skeleton.model = edmodel;
225         }
226         if (!ed->priv.server->skeleton.model || !ed->priv.server->skeleton.model->num_bones)
227         {
228                 if(ed->priv.server->skeleton.relativetransforms)
229                         Mem_Free(ed->priv.server->skeleton.relativetransforms);
230                 ed->priv.server->skeleton.relativetransforms = NULL;
231                 return;
232         }
233
234         {
235                 int skeletonindex = -1;
236                 skeleton_t *skeleton;
237                 skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
238                 if (skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones)
239                 {
240                         // custom skeleton controlled by the game (FTE_CSQC_SKELETONOBJECTS)
241                         if (!ed->priv.server->skeleton.relativetransforms)
242                                 ed->priv.server->skeleton.relativetransforms = (matrix4x4_t *)Mem_Alloc(prog->progs_mempool, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
243                         memcpy(ed->priv.server->skeleton.relativetransforms, skeleton->relativetransforms, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
244                 }
245                 else
246                 {
247                         if(ed->priv.server->skeleton.relativetransforms)
248                                 Mem_Free(ed->priv.server->skeleton.relativetransforms);
249                         ed->priv.server->skeleton.relativetransforms = NULL;
250                 }
251         }
252 }
253
254 void VM_RemoveEdictSkeleton(prvm_prog_t *prog, prvm_edict_t *ed)
255 {
256         if (ed->priv.server->skeleton.relativetransforms)
257                 Mem_Free(ed->priv.server->skeleton.relativetransforms);
258         memset(&ed->priv.server->skeleton, 0, sizeof(ed->priv.server->skeleton));
259 }
260
261
262
263
264 //============================================================================
265 //BUILT-IN FUNCTIONS
266
267 void VM_VarString(prvm_prog_t *prog, int first, char *out, int outlength)
268 {
269         int i;
270         const char *s;
271         char *outend;
272
273         outend = out + outlength - 1;
274         for (i = first;i < prog->argc && out < outend;i++)
275         {
276                 s = PRVM_G_STRING((OFS_PARM0+i*3));
277                 while (out < outend && *s)
278                         *out++ = *s++;
279         }
280         *out++ = 0;
281 }
282
283 /*
284 =================
285 VM_checkextension
286
287 returns true if the extension is supported by the server
288
289 checkextension(extensionname)
290 =================
291 */
292
293 // kind of helper function
294 static qbool checkextension(prvm_prog_t *prog, const char *name)
295 {
296         const char **e;
297
298         for (e = prog->extensionstring;*e;e++)
299         {
300                 if(!strcasecmp(*e, name))
301                 {
302 #ifdef USEODE
303                         // special sheck for ODE
304                         if (!strncasecmp("DP_PHYSICS_ODE", name, 14))
305                         {
306 #ifndef LINK_TO_LIBODE
307                                 return ode_dll ? true : false;
308 #else
309 #ifdef LINK_TO_LIBODE
310                                 return true;
311 #else
312                                 return false;
313 #endif
314 #endif
315                         }
316 #endif
317
318                         // special sheck for d0_blind_id
319                         if (!strcasecmp("DP_CRYPTO", name))
320                                 return Crypto_Available();
321                         if (!strcasecmp("DP_QC_DIGEST_SHA256", name))
322                                 return Crypto_Available();
323
324                         return true;
325                 }
326         }
327         return false;
328 }
329
330 void VM_checkextension(prvm_prog_t *prog)
331 {
332         VM_SAFEPARMCOUNT(1,VM_checkextension);
333
334         PRVM_G_FLOAT(OFS_RETURN) = checkextension(prog, PRVM_G_STRING(OFS_PARM0));
335 }
336
337 /*
338 =================
339 VM_error
340
341 This is a TERMINAL error, which will kill off the entire prog.
342 Dumps self.
343
344 error(value)
345 =================
346 */
347 void VM_error(prvm_prog_t *prog)
348 {
349         prvm_edict_t    *ed;
350         char string[VM_STRINGTEMP_LENGTH];
351
352         VM_VarString(prog, 0, string, sizeof(string));
353         Con_Printf(CON_ERROR "======%s ERROR in %s:\n%s\n", prog->name, PRVM_GetString(prog, prog->xfunction->s_name), string);
354         ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
355         PRVM_ED_Print(prog, ed, NULL);
356
357         prog->error_cmd("%s: Program error in function %s:\n%s\nTip: read above for entity information\n", prog->name, PRVM_GetString(prog, prog->xfunction->s_name), string);
358 }
359
360 /*
361 =================
362 VM_objerror
363
364 Dumps out self, then an error message.  The program is aborted and self is
365 removed, but the level can continue.
366
367 objerror(value)
368 =================
369 */
370 void VM_objerror(prvm_prog_t *prog)
371 {
372         prvm_edict_t    *ed;
373         char string[VM_STRINGTEMP_LENGTH];
374
375         VM_VarString(prog, 0, string, sizeof(string));
376         Con_Printf(CON_ERROR "======OBJECT ERROR======\n"); // , prog->name, PRVM_GetString(prog->xfunction->s_name), string); // or include them? FIXME
377         ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
378         PRVM_ED_Print(prog, ed, NULL);
379         PRVM_ED_Free (prog, ed);
380         Con_Printf(CON_ERROR "%s OBJECT ERROR in %s:\n%s\nTip: read above for entity information\n", prog->name, PRVM_GetString(prog, prog->xfunction->s_name), string);
381 }
382
383 /*
384 =================
385 VM_print
386
387 print to console
388
389 print(...[string])
390 =================
391 */
392 void VM_print(prvm_prog_t *prog)
393 {
394         char string[VM_STRINGTEMP_LENGTH];
395
396         VM_VarString(prog, 0, string, sizeof(string));
397         Con_Print(string);
398 }
399
400 /*
401 =================
402 VM_bprint
403
404 broadcast print to everyone on server
405
406 bprint(...[string])
407 =================
408 */
409 void VM_bprint(prvm_prog_t *prog)
410 {
411         char string[VM_STRINGTEMP_LENGTH];
412
413         if(!sv.active)
414         {
415                 VM_Warning(prog, "VM_bprint: game is not server(%s) !\n", prog->name);
416                 return;
417         }
418
419         VM_VarString(prog, 0, string, sizeof(string));
420         SV_BroadcastPrint(string);
421 }
422
423 /*
424 =================
425 VM_sprint (menu & client but only if server.active == true)
426
427 single print to a specific client
428
429 sprint(float clientnum,...[string])
430 =================
431 */
432 void VM_sprint(prvm_prog_t *prog)
433 {
434         client_t        *client;
435         int                     clientnum;
436         char string[VM_STRINGTEMP_LENGTH];
437
438         VM_SAFEPARMCOUNTRANGE(1, 8, VM_sprint);
439
440         //find client for this entity
441         clientnum = (int)PRVM_G_FLOAT(OFS_PARM0);
442         if (!sv.active  || clientnum < 0 || clientnum >= svs.maxclients || !svs.clients[clientnum].active)
443         {
444                 VM_Warning(prog, "VM_sprint: %s: invalid client or server is not active !\n", prog->name);
445                 return;
446         }
447
448         client = svs.clients + clientnum;
449         if (!client->netconnection)
450                 return;
451
452         VM_VarString(prog, 1, string, sizeof(string));
453         MSG_WriteChar(&client->netconnection->message,svc_print);
454         MSG_WriteString(&client->netconnection->message, string);
455 }
456
457 /*
458 =================
459 VM_centerprint
460
461 single print to the screen
462
463 centerprint(value)
464 =================
465 */
466 void VM_centerprint(prvm_prog_t *prog)
467 {
468         char string[VM_STRINGTEMP_LENGTH];
469
470         VM_SAFEPARMCOUNTRANGE(1, 8, VM_centerprint);
471         VM_VarString(prog, 0, string, sizeof(string));
472         SCR_CenterPrint(string);
473 }
474
475 /*
476 =================
477 VM_normalize
478
479 vector normalize(vector)
480 =================
481 */
482 void VM_normalize(prvm_prog_t *prog)
483 {
484         prvm_vec_t      *value1;
485         vec3_t  newvalue;
486         double  f;
487
488         VM_SAFEPARMCOUNT(1,VM_normalize);
489
490         value1 = PRVM_G_VECTOR(OFS_PARM0);
491
492         f = VectorLength2(value1);
493         if (f)
494         {
495                 f = 1.0 / sqrt(f);
496                 VectorScale(value1, f, newvalue);
497         }
498         else
499                 VectorClear(newvalue);
500
501         VectorCopy (newvalue, PRVM_G_VECTOR(OFS_RETURN));
502 }
503
504 /*
505 =================
506 VM_vlen
507
508 scalar vlen(vector)
509 =================
510 */
511 void VM_vlen(prvm_prog_t *prog)
512 {
513         VM_SAFEPARMCOUNT(1,VM_vlen);
514         PRVM_G_FLOAT(OFS_RETURN) = VectorLength(PRVM_G_VECTOR(OFS_PARM0));
515 }
516
517 /*
518 =================
519 VM_vectoyaw
520
521 float vectoyaw(vector)
522 =================
523 */
524 void VM_vectoyaw(prvm_prog_t *prog)
525 {
526         prvm_vec_t      *value1;
527         prvm_vec_t      yaw;
528
529         VM_SAFEPARMCOUNT(1,VM_vectoyaw);
530
531         value1 = PRVM_G_VECTOR(OFS_PARM0);
532
533         if (value1[1] == 0 && value1[0] == 0)
534                 yaw = 0;
535         else
536         {
537                 yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI);
538                 if (yaw < 0)
539                         yaw += 360;
540         }
541
542         PRVM_G_FLOAT(OFS_RETURN) = yaw;
543 }
544
545
546 /*
547 =================
548 VM_vectoangles
549
550 vector vectoangles(vector[, vector])
551 =================
552 */
553 void VM_vectoangles(prvm_prog_t *prog)
554 {
555         vec3_t result, forward, up;
556         VM_SAFEPARMCOUNTRANGE(1, 2,VM_vectoangles);
557
558         VectorCopy(PRVM_G_VECTOR(OFS_PARM0), forward);
559         if (prog->argc >= 2)
560         {
561                 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), up);
562                 AnglesFromVectors(result, forward, up, true);
563         }
564         else
565                 AnglesFromVectors(result, forward, NULL, true);
566         VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
567 }
568
569 /*
570 =================
571 VM_random
572
573 Returns a number from 0<= num < 1
574
575 float random()
576 =================
577 */
578 void VM_random(prvm_prog_t *prog)
579 {
580         VM_SAFEPARMCOUNT(0,VM_random);
581
582         PRVM_G_FLOAT(OFS_RETURN) = lhrandom(0, 1);
583 }
584
585 /*
586 =========
587 VM_localsound
588
589 localsound(string sample)
590 =========
591 */
592 void VM_localsound(prvm_prog_t *prog)
593 {
594         const char *s;
595
596         VM_SAFEPARMCOUNT(1,VM_localsound);
597
598         s = PRVM_G_STRING(OFS_PARM0);
599
600         if(!S_LocalSound (s))
601         {
602                 PRVM_G_FLOAT(OFS_RETURN) = -4;
603                 VM_Warning(prog, "VM_localsound: Failed to play %s for %s !\n", s, prog->name);
604                 return;
605         }
606
607         PRVM_G_FLOAT(OFS_RETURN) = 1;
608 }
609
610 /*
611 =================
612 VM_break
613
614 break()
615 =================
616 */
617 void VM_break(prvm_prog_t *prog)
618 {
619         prog->error_cmd("%s: break statement", prog->name);
620 }
621
622 //============================================================================
623
624 /*
625 =================
626 VM_localcmd_local
627
628 Sends text over to the client's execution buffer
629
630 [localcmd (string, ...) or]
631 cmd (string, ...)
632 =================
633 */
634 void VM_localcmd_local(prvm_prog_t *prog)
635 {
636         char string[VM_STRINGTEMP_LENGTH];
637         VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd_local);
638         VM_VarString(prog, 0, string, sizeof(string));
639         Cbuf_AddText(cmd_local, string);
640 }
641
642 /*
643 =================
644 VM_localcmd_server
645
646 Sends text over to the server's execution buffer
647
648 [localcmd (string, ...) or]
649 cmd (string, ...)
650 =================
651 */
652 void VM_localcmd_server(prvm_prog_t *prog)
653 {
654         char string[VM_STRINGTEMP_LENGTH];
655         VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd_server);
656         VM_VarString(prog, 0, string, sizeof(string));
657         Cbuf_AddText(cmd_local, string);
658 }
659
660 static qbool PRVM_Cvar_ReadOk(prvm_prog_t *prog, const char *string)
661 {
662         cvar_t *cvar;
663         cvar = Cvar_FindVar(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask);
664         return ((cvar) && ((cvar->flags & CF_PRIVATE) == 0));
665 }
666
667 /*
668 =================
669 VM_cvar
670
671 float cvar (string)
672 =================
673 */
674 void VM_cvar(prvm_prog_t *prog)
675 {
676         char string[VM_STRINGTEMP_LENGTH];
677         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
678         VM_VarString(prog, 0, string, sizeof(string));
679         VM_CheckEmptyString(prog, string);
680         PRVM_G_FLOAT(OFS_RETURN) = PRVM_Cvar_ReadOk(prog, string) ? Cvar_VariableValue(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask) : 0;
681 }
682
683 /*
684 =================
685 VM_cvar
686
687 float cvar_type (string)
688 float CVAR_TYPEFLAG_EXISTS = 1;
689 float CVAR_TYPEFLAG_SAVED = 2;
690 float CVAR_TYPEFLAG_PRIVATE = 4;
691 float CVAR_TYPEFLAG_ENGINE = 8;
692 float CVAR_TYPEFLAG_HASDESCRIPTION = 16;
693 float CVAR_TYPEFLAG_READONLY = 32;
694 =================
695 */
696 void VM_cvar_type(prvm_prog_t *prog)
697 {
698         char string[VM_STRINGTEMP_LENGTH];
699         cvar_t *cvar;
700         int ret;
701
702         VM_SAFEPARMCOUNTRANGE(1, 8, VM_cvar_type);
703         VM_VarString(prog, 0, string, sizeof(string));
704         VM_CheckEmptyString(prog, string);
705         cvar = Cvar_FindVar(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask);
706
707
708         if(!cvar)
709         {
710                 PRVM_G_FLOAT(OFS_RETURN) = 0;
711                 return; // CVAR_TYPE_NONE
712         }
713
714         ret = 1; // CVAR_EXISTS
715         if(cvar->flags & CF_ARCHIVE)
716                 ret |= 2; // CVAR_TYPE_SAVED
717         if(cvar->flags & CF_PRIVATE)
718                 ret |= 4; // CVAR_TYPE_PRIVATE
719         if(!(cvar->flags & CF_ALLOCATED))
720                 ret |= 8; // CVAR_TYPE_ENGINE
721         if(cvar->description != cvar_dummy_description)
722                 ret |= 16; // CVAR_TYPE_HASDESCRIPTION
723         if(cvar->flags & CF_READONLY)
724                 ret |= 32; // CVAR_TYPE_READONLY
725         
726         PRVM_G_FLOAT(OFS_RETURN) = ret;
727 }
728
729 /*
730 =================
731 VM_cvar_string
732
733 const string    VM_cvar_string (string, ...)
734 =================
735 */
736 void VM_cvar_string(prvm_prog_t *prog)
737 {
738         char string[VM_STRINGTEMP_LENGTH];
739         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_string);
740         VM_VarString(prog, 0, string, sizeof(string));
741         VM_CheckEmptyString(prog, string);
742         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, PRVM_Cvar_ReadOk(prog, string) ? Cvar_VariableString(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask) : "");
743 }
744
745
746 /*
747 ========================
748 VM_cvar_defstring
749
750 const string    VM_cvar_defstring (string, ...)
751 ========================
752 */
753 void VM_cvar_defstring(prvm_prog_t *prog)
754 {
755         char string[VM_STRINGTEMP_LENGTH];
756         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_defstring);
757         VM_VarString(prog, 0, string, sizeof(string));
758         VM_CheckEmptyString(prog, string);
759         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, Cvar_VariableDefString(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask));
760 }
761
762 /*
763 ========================
764 VM_cvar_defstring
765
766 const string    VM_cvar_description (string, ...)
767 ========================
768 */
769 void VM_cvar_description(prvm_prog_t *prog)
770 {
771         char string[VM_STRINGTEMP_LENGTH];
772         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_description);
773         VM_VarString(prog, 0, string, sizeof(string));
774         VM_CheckEmptyString(prog, string);
775         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, Cvar_VariableDescription(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask));
776 }
777 /*
778 =================
779 VM_cvar_set
780
781 void cvar_set (string,string, ...)
782 =================
783 */
784 void VM_cvar_set(prvm_prog_t *prog)
785 {
786         const char *name;
787         char string[VM_STRINGTEMP_LENGTH];
788         VM_SAFEPARMCOUNTRANGE(2,8,VM_cvar_set);
789         VM_VarString(prog, 1, string, sizeof(string));
790         name = PRVM_G_STRING(OFS_PARM0);
791         VM_CheckEmptyString(prog, name);
792         Cvar_Set(prog->console_cmd->cvars, name, string);
793 }
794
795 /*
796 =========
797 VM_dprint
798
799 dprint(...[string])
800 =========
801 */
802 void VM_dprint(prvm_prog_t *prog)
803 {
804         char string[VM_STRINGTEMP_LENGTH];
805         VM_SAFEPARMCOUNTRANGE(1, 8, VM_dprint);
806         VM_VarString(prog, 0, string, sizeof(string));
807 #if 1
808         Con_DPrintf("%s", string);
809 #else
810         Con_DPrintf("%s: %s", prog->name, string);
811 #endif
812 }
813
814 /*
815 =========
816 VM_ftos
817
818 string  ftos(float)
819 =========
820 */
821
822 void VM_ftos(prvm_prog_t *prog)
823 {
824         prvm_vec_t v;
825         char s[128];
826
827         VM_SAFEPARMCOUNT(1, VM_ftos);
828
829         v = PRVM_G_FLOAT(OFS_PARM0);
830
831         if ((prvm_vec_t)((prvm_int_t)v) == v)
832                 dpsnprintf(s, sizeof(s), "%.0f", v);
833         else
834                 dpsnprintf(s, sizeof(s), "%f", v);
835         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s);
836 }
837
838 /*
839 =========
840 VM_fabs
841
842 float   fabs(float)
843 =========
844 */
845
846 void VM_fabs(prvm_prog_t *prog)
847 {
848         prvm_vec_t v;
849
850         VM_SAFEPARMCOUNT(1,VM_fabs);
851
852         v = PRVM_G_FLOAT(OFS_PARM0);
853         PRVM_G_FLOAT(OFS_RETURN) = fabs(v);
854 }
855
856 /*
857 =========
858 VM_vtos
859
860 string  vtos(vector)
861 =========
862 */
863
864 void VM_vtos(prvm_prog_t *prog)
865 {
866         char s[512];
867
868         VM_SAFEPARMCOUNT(1,VM_vtos);
869
870         dpsnprintf (s, sizeof(s), "'%5.1f %5.1f %5.1f'", PRVM_G_VECTOR(OFS_PARM0)[0], PRVM_G_VECTOR(OFS_PARM0)[1], PRVM_G_VECTOR(OFS_PARM0)[2]);
871         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s);
872 }
873
874 /*
875 =========
876 VM_etos
877
878 string  etos(entity)
879 =========
880 */
881
882 void VM_etos(prvm_prog_t *prog)
883 {
884         char s[128];
885
886         VM_SAFEPARMCOUNT(1, VM_etos);
887
888         dpsnprintf (s, sizeof(s), "entity %i", PRVM_G_EDICTNUM(OFS_PARM0));
889         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s);
890 }
891
892 /*
893 =========
894 VM_stof
895
896 float stof(...[string])
897 =========
898 */
899 void VM_stof(prvm_prog_t *prog)
900 {
901         char string[VM_STRINGTEMP_LENGTH];
902         VM_SAFEPARMCOUNTRANGE(1, 8, VM_stof);
903         VM_VarString(prog, 0, string, sizeof(string));
904         PRVM_G_FLOAT(OFS_RETURN) = atof(string);
905 }
906
907 /*
908 ========================
909 VM_itof
910
911 float itof(int ent)
912 ========================
913 */
914 void VM_itof(prvm_prog_t *prog)
915 {
916         VM_SAFEPARMCOUNT(1, VM_itof);
917         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
918 }
919
920 /*
921 ========================
922 VM_ftoe
923
924 entity ftoe(float num)
925 ========================
926 */
927 void VM_ftoe(prvm_prog_t *prog)
928 {
929         prvm_int_t ent;
930         VM_SAFEPARMCOUNT(1, VM_ftoe);
931
932         ent = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM0);
933         if (ent < 0 || ent >= prog->max_edicts || PRVM_PROG_TO_EDICT(ent)->free)
934                 ent = 0; // return world instead of a free or invalid entity
935
936         PRVM_G_INT(OFS_RETURN) = ent;
937 }
938
939 /*
940 ========================
941 VM_etof
942
943 float etof(entity ent)
944 ========================
945 */
946 void VM_etof(prvm_prog_t *prog)
947 {
948         VM_SAFEPARMCOUNT(1, VM_etof);
949         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICTNUM(OFS_PARM0);
950 }
951
952 /*
953 =========
954 VM_strftime
955
956 string strftime(float uselocaltime, string[, string ...])
957 =========
958 */
959 void VM_strftime(prvm_prog_t *prog)
960 {
961         time_t t;
962 #if _MSC_VER >= 1400
963         struct tm tm;
964         int tmresult;
965 #else
966         struct tm *tm;
967 #endif
968         char fmt[VM_STRINGTEMP_LENGTH];
969         char result[VM_STRINGTEMP_LENGTH];
970         VM_SAFEPARMCOUNTRANGE(2, 8, VM_strftime);
971         VM_VarString(prog, 1, fmt, sizeof(fmt));
972         t = time(NULL);
973 #if _MSC_VER >= 1400
974         if (PRVM_G_FLOAT(OFS_PARM0))
975                 tmresult = localtime_s(&tm, &t);
976         else
977                 tmresult = gmtime_s(&tm, &t);
978         if (!tmresult)
979 #else
980         if (PRVM_G_FLOAT(OFS_PARM0))
981                 tm = localtime(&t);
982         else
983                 tm = gmtime(&t);
984         if (!tm)
985 #endif
986         {
987                 PRVM_G_INT(OFS_RETURN) = 0;
988                 return;
989         }
990 #if _MSC_VER >= 1400
991         strftime(result, sizeof(result), fmt, &tm);
992 #else
993         strftime(result, sizeof(result), fmt, tm);
994 #endif
995         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, result);
996 }
997
998 /*
999 =========
1000 VM_spawn
1001
1002 entity spawn()
1003 =========
1004 */
1005
1006 void VM_spawn(prvm_prog_t *prog)
1007 {
1008         prvm_edict_t    *ed;
1009         VM_SAFEPARMCOUNT(0, VM_spawn);
1010         prog->xfunction->builtinsprofile += 20;
1011         ed = PRVM_ED_Alloc(prog);
1012         VM_RETURN_EDICT(ed);
1013 }
1014
1015 /*
1016 =========
1017 VM_remove
1018
1019 remove(entity e)
1020 =========
1021 */
1022
1023 void VM_remove(prvm_prog_t *prog)
1024 {
1025         prvm_edict_t    *ed;
1026         prog->xfunction->builtinsprofile += 20;
1027
1028         VM_SAFEPARMCOUNT(1, VM_remove);
1029
1030         ed = PRVM_G_EDICT(OFS_PARM0);
1031         if( PRVM_NUM_FOR_EDICT(ed) <= prog->reserved_edicts )
1032         {
1033                 if (developer.integer > 0)
1034                         VM_Warning(prog, "VM_remove: tried to remove the null entity or a reserved entity!\n" );
1035         }
1036         else if( ed->free )
1037         {
1038                 if (developer.integer > 0)
1039                         VM_Warning(prog, "VM_remove: tried to remove an already freed entity!\n" );
1040         }
1041         else
1042                 PRVM_ED_Free (prog, ed);
1043 }
1044
1045 /*
1046 =========
1047 VM_find
1048
1049 entity  find(entity start, .string field, string match)
1050 =========
1051 */
1052
1053 void VM_find(prvm_prog_t *prog)
1054 {
1055         int             e;
1056         int             f;
1057         const char      *s, *t;
1058         prvm_edict_t    *ed;
1059
1060         VM_SAFEPARMCOUNT(3,VM_find);
1061
1062         e = PRVM_G_EDICTNUM(OFS_PARM0);
1063         f = PRVM_G_INT(OFS_PARM1);
1064         s = PRVM_G_STRING(OFS_PARM2);
1065
1066         // LadyHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1067         // expects it to find all the monsters, so we must be careful to support
1068         // searching for ""
1069
1070         for (e++ ; e < prog->num_edicts ; e++)
1071         {
1072                 prog->xfunction->builtinsprofile++;
1073                 ed = PRVM_EDICT_NUM(e);
1074                 if (ed->free)
1075                         continue;
1076                 t = PRVM_E_STRING(ed,f);
1077                 if (!t)
1078                         t = "";
1079                 if (!strcmp(t,s))
1080                 {
1081                         VM_RETURN_EDICT(ed);
1082                         return;
1083                 }
1084         }
1085
1086         VM_RETURN_EDICT(prog->edicts);
1087 }
1088
1089 /*
1090 =========
1091 VM_findfloat
1092
1093   entity        findfloat(entity start, .float field, float match)
1094   entity        findentity(entity start, .entity field, entity match)
1095 =========
1096 */
1097 // LadyHavoc: added this for searching float, int, and entity reference fields
1098 void VM_findfloat(prvm_prog_t *prog)
1099 {
1100         int             e;
1101         int             f;
1102         prvm_vec_t      s;
1103         prvm_edict_t    *ed;
1104
1105         VM_SAFEPARMCOUNT(3,VM_findfloat);
1106
1107         e = PRVM_G_EDICTNUM(OFS_PARM0);
1108         f = PRVM_G_INT(OFS_PARM1);
1109         s = PRVM_G_FLOAT(OFS_PARM2);
1110
1111         for (e++ ; e < prog->num_edicts ; e++)
1112         {
1113                 prog->xfunction->builtinsprofile++;
1114                 ed = PRVM_EDICT_NUM(e);
1115                 if (ed->free)
1116                         continue;
1117                 if (PRVM_E_FLOAT(ed,f) == s)
1118                 {
1119                         VM_RETURN_EDICT(ed);
1120                         return;
1121                 }
1122         }
1123
1124         VM_RETURN_EDICT(prog->edicts);
1125 }
1126
1127 /*
1128 =========
1129 VM_findchain
1130
1131 entity  findchain(.string field, string match)
1132 =========
1133 */
1134 // chained search for strings in entity fields
1135 // entity(.string field, string match) findchain = #402;
1136 void VM_findchain(prvm_prog_t *prog)
1137 {
1138         int             i;
1139         int             f;
1140         const char      *s, *t;
1141         prvm_edict_t    *ent, *chain;
1142         int chainfield;
1143
1144         VM_SAFEPARMCOUNTRANGE(2,3,VM_findchain);
1145
1146         if(prog->argc == 3)
1147                 chainfield = PRVM_G_INT(OFS_PARM2);
1148         else
1149                 chainfield = prog->fieldoffsets.chain;
1150         if (chainfield < 0)
1151                 prog->error_cmd("VM_findchain: %s doesnt have the specified chain field !", prog->name);
1152
1153         chain = prog->edicts;
1154
1155         f = PRVM_G_INT(OFS_PARM0);
1156         s = PRVM_G_STRING(OFS_PARM1);
1157
1158         // LadyHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1159         // expects it to find all the monsters, so we must be careful to support
1160         // searching for ""
1161
1162         ent = PRVM_NEXT_EDICT(prog->edicts);
1163         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1164         {
1165                 prog->xfunction->builtinsprofile++;
1166                 if (ent->free)
1167                         continue;
1168                 t = PRVM_E_STRING(ent,f);
1169                 if (!t)
1170                         t = "";
1171                 if (strcmp(t,s))
1172                         continue;
1173
1174                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_NUM_FOR_EDICT(chain);
1175                 chain = ent;
1176         }
1177
1178         VM_RETURN_EDICT(chain);
1179 }
1180
1181 /*
1182 =========
1183 VM_findchainfloat
1184
1185 entity  findchainfloat(.string field, float match)
1186 entity  findchainentity(.string field, entity match)
1187 =========
1188 */
1189 // LadyHavoc: chained search for float, int, and entity reference fields
1190 // entity(.string field, float match) findchainfloat = #403;
1191 void VM_findchainfloat(prvm_prog_t *prog)
1192 {
1193         int             i;
1194         int             f;
1195         prvm_vec_t      s;
1196         prvm_edict_t    *ent, *chain;
1197         int chainfield;
1198
1199         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainfloat);
1200
1201         if(prog->argc == 3)
1202                 chainfield = PRVM_G_INT(OFS_PARM2);
1203         else
1204                 chainfield = prog->fieldoffsets.chain;
1205         if (chainfield < 0)
1206                 prog->error_cmd("VM_findchain: %s doesnt have the specified chain field !", prog->name);
1207
1208         chain = (prvm_edict_t *)prog->edicts;
1209
1210         f = PRVM_G_INT(OFS_PARM0);
1211         s = PRVM_G_FLOAT(OFS_PARM1);
1212
1213         ent = PRVM_NEXT_EDICT(prog->edicts);
1214         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1215         {
1216                 prog->xfunction->builtinsprofile++;
1217                 if (ent->free)
1218                         continue;
1219                 if (PRVM_E_FLOAT(ent,f) != s)
1220                         continue;
1221
1222                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1223                 chain = ent;
1224         }
1225
1226         VM_RETURN_EDICT(chain);
1227 }
1228
1229 /*
1230 ========================
1231 VM_findflags
1232
1233 entity  findflags(entity start, .float field, float match)
1234 ========================
1235 */
1236 // LadyHavoc: search for flags in float fields
1237 void VM_findflags(prvm_prog_t *prog)
1238 {
1239         prvm_int_t      e;
1240         prvm_int_t      f;
1241         prvm_int_t      s;
1242         prvm_edict_t    *ed;
1243
1244         VM_SAFEPARMCOUNT(3, VM_findflags);
1245
1246
1247         e = PRVM_G_EDICTNUM(OFS_PARM0);
1248         f = PRVM_G_INT(OFS_PARM1);
1249         s = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM2);
1250
1251         for (e++ ; e < prog->num_edicts ; e++)
1252         {
1253                 prog->xfunction->builtinsprofile++;
1254                 ed = PRVM_EDICT_NUM(e);
1255                 if (ed->free)
1256                         continue;
1257                 if (!PRVM_E_FLOAT(ed,f))
1258                         continue;
1259                 if ((prvm_int_t)PRVM_E_FLOAT(ed,f) & s)
1260                 {
1261                         VM_RETURN_EDICT(ed);
1262                         return;
1263                 }
1264         }
1265
1266         VM_RETURN_EDICT(prog->edicts);
1267 }
1268
1269 /*
1270 ========================
1271 VM_findchainflags
1272
1273 entity  findchainflags(.float field, float match)
1274 ========================
1275 */
1276 // LadyHavoc: chained search for flags in float fields
1277 void VM_findchainflags(prvm_prog_t *prog)
1278 {
1279         prvm_int_t              i;
1280         prvm_int_t              f;
1281         prvm_int_t              s;
1282         prvm_edict_t    *ent, *chain;
1283         int chainfield;
1284
1285         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainflags);
1286
1287         if(prog->argc == 3)
1288                 chainfield = PRVM_G_INT(OFS_PARM2);
1289         else
1290                 chainfield = prog->fieldoffsets.chain;
1291         if (chainfield < 0)
1292                 prog->error_cmd("VM_findchain: %s doesnt have the specified chain field !", prog->name);
1293
1294         chain = (prvm_edict_t *)prog->edicts;
1295
1296         f = PRVM_G_INT(OFS_PARM0);
1297         s = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM1);
1298
1299         ent = PRVM_NEXT_EDICT(prog->edicts);
1300         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1301         {
1302                 prog->xfunction->builtinsprofile++;
1303                 if (ent->free)
1304                         continue;
1305                 if (!PRVM_E_FLOAT(ent,f))
1306                         continue;
1307                 if (!((prvm_int_t)PRVM_E_FLOAT(ent,f) & s))
1308                         continue;
1309
1310                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1311                 chain = ent;
1312         }
1313
1314         VM_RETURN_EDICT(chain);
1315 }
1316
1317 /*
1318 =========
1319 VM_precache_sound
1320
1321 string  precache_sound (string sample)
1322 =========
1323 */
1324 void VM_precache_sound(prvm_prog_t *prog)
1325 {
1326         const char *s;
1327
1328         VM_SAFEPARMCOUNT(1, VM_precache_sound);
1329
1330         s = PRVM_G_STRING(OFS_PARM0);
1331         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1332         //VM_CheckEmptyString(prog, s);
1333
1334         if(snd_initialized.integer && !S_PrecacheSound(s, true, true))
1335         {
1336                 VM_Warning(prog, "VM_precache_sound: Failed to load %s for %s\n", s, prog->name);
1337                 return;
1338         }
1339 }
1340
1341 /*
1342 =================
1343 VM_precache_file
1344
1345 returns the same string as output
1346
1347 does nothing, only used by qcc to build .pak archives
1348 =================
1349 */
1350 void VM_precache_file(prvm_prog_t *prog)
1351 {
1352         VM_SAFEPARMCOUNT(1,VM_precache_file);
1353         // precache_file is only used to copy files with qcc, it does nothing
1354         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1355 }
1356
1357 /*
1358 =========
1359 VM_coredump
1360
1361 coredump()
1362 =========
1363 */
1364 void VM_coredump(prvm_prog_t *prog)
1365 {
1366         VM_SAFEPARMCOUNT(0,VM_coredump);
1367
1368         Cbuf_AddText(cmd_local, "prvm_edicts ");
1369         Cbuf_AddText(cmd_local, prog->name);
1370         Cbuf_AddText(cmd_local, "\n");
1371 }
1372
1373 /*
1374 =========
1375 VM_stackdump
1376
1377 stackdump()
1378 =========
1379 */
1380 void VM_stackdump(prvm_prog_t *prog)
1381 {
1382         VM_SAFEPARMCOUNT(0, VM_stackdump);
1383
1384         PRVM_StackTrace(prog);
1385 }
1386
1387 /*
1388 =========
1389 VM_crash
1390
1391 crash()
1392 =========
1393 */
1394
1395 void VM_crash(prvm_prog_t *prog)
1396 {
1397         VM_SAFEPARMCOUNT(0, VM_crash);
1398
1399         prog->error_cmd("Crash called by %s",prog->name);
1400 }
1401
1402 /*
1403 =========
1404 VM_traceon
1405
1406 traceon()
1407 =========
1408 */
1409 void VM_traceon(prvm_prog_t *prog)
1410 {
1411         VM_SAFEPARMCOUNT(0,VM_traceon);
1412
1413         prog->trace = true;
1414 }
1415
1416 /*
1417 =========
1418 VM_traceoff
1419
1420 traceoff()
1421 =========
1422 */
1423 void VM_traceoff(prvm_prog_t *prog)
1424 {
1425         VM_SAFEPARMCOUNT(0,VM_traceoff);
1426
1427         prog->trace = false;
1428 }
1429
1430 /*
1431 =========
1432 VM_eprint
1433
1434 eprint(entity e)
1435 =========
1436 */
1437 void VM_eprint(prvm_prog_t *prog)
1438 {
1439         VM_SAFEPARMCOUNT(1,VM_eprint);
1440
1441         PRVM_ED_PrintNum (prog, PRVM_G_EDICTNUM(OFS_PARM0), NULL);
1442 }
1443
1444 /*
1445 =========
1446 VM_rint
1447
1448 float   rint(float)
1449 =========
1450 */
1451 void VM_rint(prvm_prog_t *prog)
1452 {
1453         prvm_vec_t f;
1454         VM_SAFEPARMCOUNT(1,VM_rint);
1455
1456         f = PRVM_G_FLOAT(OFS_PARM0);
1457         if (f > 0)
1458                 PRVM_G_FLOAT(OFS_RETURN) = floor(f + 0.5);
1459         else
1460                 PRVM_G_FLOAT(OFS_RETURN) = ceil(f - 0.5);
1461 }
1462
1463 /*
1464 =========
1465 VM_floor
1466
1467 float   floor(float)
1468 =========
1469 */
1470 void VM_floor(prvm_prog_t *prog)
1471 {
1472         VM_SAFEPARMCOUNT(1,VM_floor);
1473
1474         PRVM_G_FLOAT(OFS_RETURN) = floor(PRVM_G_FLOAT(OFS_PARM0));
1475 }
1476
1477 /*
1478 =========
1479 VM_ceil
1480
1481 float   ceil(float)
1482 =========
1483 */
1484 void VM_ceil(prvm_prog_t *prog)
1485 {
1486         VM_SAFEPARMCOUNT(1,VM_ceil);
1487
1488         PRVM_G_FLOAT(OFS_RETURN) = ceil(PRVM_G_FLOAT(OFS_PARM0));
1489 }
1490
1491
1492 /*
1493 =============
1494 VM_nextent
1495
1496 entity  nextent(entity)
1497 =============
1498 */
1499 void VM_nextent(prvm_prog_t *prog)
1500 {
1501         int             i;
1502         prvm_edict_t    *ent;
1503
1504         VM_SAFEPARMCOUNT(1, VM_nextent);
1505
1506         i = PRVM_G_EDICTNUM(OFS_PARM0);
1507         while (1)
1508         {
1509                 prog->xfunction->builtinsprofile++;
1510                 i++;
1511                 if (i == prog->num_edicts)
1512                 {
1513                         VM_RETURN_EDICT(prog->edicts);
1514                         return;
1515                 }
1516                 ent = PRVM_EDICT_NUM(i);
1517                 if (!ent->free)
1518                 {
1519                         VM_RETURN_EDICT(ent);
1520                         return;
1521                 }
1522         }
1523 }
1524
1525 //=============================================================================
1526
1527 /*
1528 ==============
1529 VM_changelevel
1530 server and menu
1531
1532 changelevel(string map)
1533 ==============
1534 */
1535 void VM_changelevel(prvm_prog_t *prog)
1536 {
1537         char vabuf[1024];
1538         VM_SAFEPARMCOUNT(1, VM_changelevel);
1539
1540         if(!sv.active)
1541         {
1542                 VM_Warning(prog, "VM_changelevel: game is not server (%s)\n", prog->name);
1543                 return;
1544         }
1545
1546 // make sure we don't issue two changelevels
1547         if (svs.changelevel_issued)
1548                 return;
1549         svs.changelevel_issued = true;
1550
1551         Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "changelevel %s\n", PRVM_G_STRING(OFS_PARM0)));
1552 }
1553
1554 /*
1555 =========
1556 VM_sin
1557
1558 float   sin(float)
1559 =========
1560 */
1561 void VM_sin(prvm_prog_t *prog)
1562 {
1563         VM_SAFEPARMCOUNT(1,VM_sin);
1564         PRVM_G_FLOAT(OFS_RETURN) = sin(PRVM_G_FLOAT(OFS_PARM0));
1565 }
1566
1567 /*
1568 =========
1569 VM_cos
1570 float   cos(float)
1571 =========
1572 */
1573 void VM_cos(prvm_prog_t *prog)
1574 {
1575         VM_SAFEPARMCOUNT(1,VM_cos);
1576         PRVM_G_FLOAT(OFS_RETURN) = cos(PRVM_G_FLOAT(OFS_PARM0));
1577 }
1578
1579 /*
1580 =========
1581 VM_sqrt
1582
1583 float   sqrt(float)
1584 =========
1585 */
1586 void VM_sqrt(prvm_prog_t *prog)
1587 {
1588         VM_SAFEPARMCOUNT(1,VM_sqrt);
1589         PRVM_G_FLOAT(OFS_RETURN) = sqrt(PRVM_G_FLOAT(OFS_PARM0));
1590 }
1591
1592 /*
1593 =========
1594 VM_asin
1595
1596 float   asin(float)
1597 =========
1598 */
1599 void VM_asin(prvm_prog_t *prog)
1600 {
1601         VM_SAFEPARMCOUNT(1,VM_asin);
1602         PRVM_G_FLOAT(OFS_RETURN) = asin(PRVM_G_FLOAT(OFS_PARM0));
1603 }
1604
1605 /*
1606 =========
1607 VM_acos
1608 float   acos(float)
1609 =========
1610 */
1611 void VM_acos(prvm_prog_t *prog)
1612 {
1613         VM_SAFEPARMCOUNT(1,VM_acos);
1614         PRVM_G_FLOAT(OFS_RETURN) = acos(PRVM_G_FLOAT(OFS_PARM0));
1615 }
1616
1617 /*
1618 =========
1619 VM_atan
1620 float   atan(float)
1621 =========
1622 */
1623 void VM_atan(prvm_prog_t *prog)
1624 {
1625         VM_SAFEPARMCOUNT(1,VM_atan);
1626         PRVM_G_FLOAT(OFS_RETURN) = atan(PRVM_G_FLOAT(OFS_PARM0));
1627 }
1628
1629 /*
1630 =========
1631 VM_atan2
1632 float   atan2(float,float)
1633 =========
1634 */
1635 void VM_atan2(prvm_prog_t *prog)
1636 {
1637         VM_SAFEPARMCOUNT(2,VM_atan2);
1638         PRVM_G_FLOAT(OFS_RETURN) = atan2(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1639 }
1640
1641 /*
1642 =========
1643 VM_tan
1644 float   tan(float)
1645 =========
1646 */
1647 void VM_tan(prvm_prog_t *prog)
1648 {
1649         VM_SAFEPARMCOUNT(1,VM_tan);
1650         PRVM_G_FLOAT(OFS_RETURN) = tan(PRVM_G_FLOAT(OFS_PARM0));
1651 }
1652
1653 /*
1654 =================
1655 VM_randomvec
1656
1657 Returns a vector of length < 1 and > 0
1658
1659 vector randomvec()
1660 =================
1661 */
1662 void VM_randomvec(prvm_prog_t *prog)
1663 {
1664         vec3_t temp;
1665         VM_SAFEPARMCOUNT(0, VM_randomvec);
1666         VectorRandom(temp);
1667         VectorCopy(temp, PRVM_G_VECTOR(OFS_RETURN));
1668 }
1669
1670 //=============================================================================
1671
1672 /*
1673 =========
1674 VM_registercvar
1675
1676 float   registercvar (string name, string value[, float flags])
1677 =========
1678 */
1679 void VM_registercvar(prvm_prog_t *prog)
1680 {
1681         const char *name, *value;
1682         int     flags;
1683
1684         VM_SAFEPARMCOUNTRANGE(2, 3, VM_registercvar);
1685
1686         name = PRVM_G_STRING(OFS_PARM0);
1687         value = PRVM_G_STRING(OFS_PARM1);
1688         flags = prog->argc >= 3 ? (int)PRVM_G_FLOAT(OFS_PARM2) : 0;
1689         PRVM_G_FLOAT(OFS_RETURN) = 0;
1690
1691         if(flags > CF_MAXFLAGSVAL)
1692                 return;
1693
1694 // first check to see if it has already been defined
1695         if (Cvar_FindVar (prog->console_cmd->cvars, name, prog->console_cmd->cvars_flagsmask))
1696                 return;
1697
1698 // check for overlap with a command
1699         if (Cmd_Exists(cmd_local, name))
1700         {
1701                 VM_Warning(prog, "VM_registercvar: %s is a command\n", name);
1702                 return;
1703         }
1704
1705         Cvar_Get(prog->console_cmd->cvars, name, value, prog->console_cmd->cvars_flagsmask | flags, NULL);
1706
1707         PRVM_G_FLOAT(OFS_RETURN) = 1; // success
1708 }
1709
1710
1711 /*
1712 =================
1713 VM_min
1714
1715 returns the minimum of two supplied floats
1716
1717 float min(float a, float b, ...[float])
1718 =================
1719 */
1720 void VM_min(prvm_prog_t *prog)
1721 {
1722         VM_SAFEPARMCOUNTRANGE(2, 8, VM_min);
1723         // LadyHavoc: 3+ argument enhancement suggested by FrikaC
1724         if (prog->argc >= 3)
1725         {
1726                 int i;
1727                 float f = PRVM_G_FLOAT(OFS_PARM0);
1728                 for (i = 1;i < prog->argc;i++)
1729                         if (f > PRVM_G_FLOAT((OFS_PARM0+i*3)))
1730                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1731                 PRVM_G_FLOAT(OFS_RETURN) = f;
1732         }
1733         else
1734                 PRVM_G_FLOAT(OFS_RETURN) = min(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1735 }
1736
1737 /*
1738 =================
1739 VM_max
1740
1741 returns the maximum of two supplied floats
1742
1743 float   max(float a, float b, ...[float])
1744 =================
1745 */
1746 void VM_max(prvm_prog_t *prog)
1747 {
1748         VM_SAFEPARMCOUNTRANGE(2, 8, VM_max);
1749         // LadyHavoc: 3+ argument enhancement suggested by FrikaC
1750         if (prog->argc >= 3)
1751         {
1752                 int i;
1753                 float f = PRVM_G_FLOAT(OFS_PARM0);
1754                 for (i = 1;i < prog->argc;i++)
1755                         if (f < PRVM_G_FLOAT((OFS_PARM0+i*3)))
1756                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1757                 PRVM_G_FLOAT(OFS_RETURN) = f;
1758         }
1759         else
1760                 PRVM_G_FLOAT(OFS_RETURN) = max(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1761 }
1762
1763 /*
1764 =================
1765 VM_bound
1766
1767 returns number bounded by supplied range
1768
1769 float   bound(float min, float value, float max)
1770 =================
1771 */
1772 void VM_bound(prvm_prog_t *prog)
1773 {
1774         VM_SAFEPARMCOUNT(3,VM_bound);
1775         PRVM_G_FLOAT(OFS_RETURN) = bound(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1), PRVM_G_FLOAT(OFS_PARM2));
1776 }
1777
1778 /*
1779 =================
1780 VM_pow
1781
1782 returns a raised to power b
1783
1784 float   pow(float a, float b)
1785 =================
1786 */
1787 void VM_pow(prvm_prog_t *prog)
1788 {
1789         VM_SAFEPARMCOUNT(2,VM_pow);
1790         PRVM_G_FLOAT(OFS_RETURN) = pow(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1791 }
1792
1793 void VM_log(prvm_prog_t *prog)
1794 {
1795         VM_SAFEPARMCOUNT(1,VM_log);
1796         PRVM_G_FLOAT(OFS_RETURN) = log(PRVM_G_FLOAT(OFS_PARM0));
1797 }
1798
1799 void VM_Files_Init(prvm_prog_t *prog)
1800 {
1801         int i;
1802         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1803                 prog->openfiles[i] = NULL;
1804 }
1805
1806 void VM_Files_CloseAll(prvm_prog_t *prog)
1807 {
1808         int i;
1809         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1810         {
1811                 if (prog->openfiles[i])
1812                         FS_Close(prog->openfiles[i]);
1813                 prog->openfiles[i] = NULL;
1814         }
1815 }
1816
1817 static qfile_t *VM_GetFileHandle(prvm_prog_t *prog, int index)
1818 {
1819         if (index < 0 || index >= PRVM_MAX_OPENFILES)
1820         {
1821                 Con_Printf("VM_GetFileHandle: invalid file handle %i used in %s\n", index, prog->name);
1822                 return NULL;
1823         }
1824         if (prog->openfiles[index] == NULL)
1825         {
1826                 Con_Printf("VM_GetFileHandle: no such file handle %i (or file has been closed) in %s\n", index, prog->name);
1827                 return NULL;
1828         }
1829         return prog->openfiles[index];
1830 }
1831
1832 /*
1833 =========
1834 VM_fopen
1835
1836 float   fopen(string filename, float mode)
1837 =========
1838 */
1839 // float(string filename, float mode) fopen = #110;
1840 // opens a file inside quake/gamedir/data/ (mode is FILE_READ, FILE_APPEND, or FILE_WRITE),
1841 // returns fhandle >= 0 if successful, or fhandle < 0 if unable to open file for any reason
1842 void VM_fopen(prvm_prog_t *prog)
1843 {
1844         int filenum, mode;
1845         const char *modestring, *filename;
1846         char vabuf[1024];
1847
1848         VM_SAFEPARMCOUNT(2,VM_fopen);
1849
1850         for (filenum = 0;filenum < PRVM_MAX_OPENFILES;filenum++)
1851                 if (prog->openfiles[filenum] == NULL)
1852                         break;
1853         if (filenum >= PRVM_MAX_OPENFILES)
1854         {
1855                 PRVM_G_FLOAT(OFS_RETURN) = -2;
1856                 VM_Warning(prog, "VM_fopen: %s ran out of file handles (%i)\n", prog->name, PRVM_MAX_OPENFILES);
1857                 return;
1858         }
1859         filename = PRVM_G_STRING(OFS_PARM0);
1860         mode = (int)PRVM_G_FLOAT(OFS_PARM1);
1861         switch(mode)
1862         {
1863         case 0: // FILE_READ
1864                 modestring = "rb";
1865                 prog->openfiles[filenum] = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "data/%s", filename), false);
1866                 if (prog->openfiles[filenum] == NULL)
1867                         prog->openfiles[filenum] = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "%s", filename), false);
1868                 break;
1869         case 1: // FILE_APPEND
1870                 modestring = "a";
1871                 prog->openfiles[filenum] = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "data/%s", filename), modestring, false);
1872                 break;
1873         case 2: // FILE_WRITE
1874                 modestring = "w";
1875                 prog->openfiles[filenum] = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "data/%s", filename), modestring, false);
1876                 break;
1877         default:
1878                 PRVM_G_FLOAT(OFS_RETURN) = -3;
1879                 VM_Warning(prog, "VM_fopen: %s: no such mode %i (valid: 0 = read, 1 = append, 2 = write)\n", prog->name, mode);
1880                 return;
1881         }
1882
1883         if (prog->openfiles[filenum] == NULL)
1884         {
1885                 PRVM_G_FLOAT(OFS_RETURN) = -1;
1886                 if (developer_extra.integer)
1887                         VM_Warning(prog, "VM_fopen: %s: %s mode %s failed\n", prog->name, filename, modestring);
1888         }
1889         else
1890         {
1891                 PRVM_G_FLOAT(OFS_RETURN) = filenum;
1892                 if (developer_extra.integer)
1893                         Con_DPrintf("VM_fopen: %s: %s mode %s opened as #%i\n", prog->name, filename, modestring, filenum);
1894                 prog->openfiles_origin[filenum] = PRVM_AllocationOrigin(prog);
1895         }
1896 }
1897
1898 /*
1899 =========
1900 VM_fclose
1901
1902 fclose(float fhandle)
1903 =========
1904 */
1905 //void(float fhandle) fclose = #111; // closes a file
1906 void VM_fclose(prvm_prog_t *prog)
1907 {
1908         int filenum;
1909
1910         VM_SAFEPARMCOUNT(1,VM_fclose);
1911
1912         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1913         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1914         {
1915                 VM_Warning(prog, "VM_fclose: invalid file handle %i used in %s\n", filenum, prog->name);
1916                 return;
1917         }
1918         if (prog->openfiles[filenum] == NULL)
1919         {
1920                 VM_Warning(prog, "VM_fclose: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
1921                 return;
1922         }
1923         FS_Close(prog->openfiles[filenum]);
1924         prog->openfiles[filenum] = NULL;
1925         if(prog->openfiles_origin[filenum])
1926                 PRVM_Free((char *)prog->openfiles_origin[filenum]);
1927         if (developer_extra.integer)
1928                 Con_DPrintf("VM_fclose: %s: #%i closed\n", prog->name, filenum);
1929 }
1930
1931 /*
1932 =========
1933 VM_fgets
1934
1935 string  fgets(float fhandle)
1936 =========
1937 */
1938 //string(float fhandle) fgets = #112; // reads a line of text from the file and returns as a tempstring
1939 void VM_fgets(prvm_prog_t *prog)
1940 {
1941         int c, end;
1942         char string[VM_STRINGTEMP_LENGTH];
1943         int filenum;
1944
1945         VM_SAFEPARMCOUNT(1,VM_fgets);
1946
1947         // set the return value regardless of any possible errors
1948         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
1949
1950         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1951         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1952         {
1953                 VM_Warning(prog, "VM_fgets: invalid file handle %i used in %s\n", filenum, prog->name);
1954                 return;
1955         }
1956         if (prog->openfiles[filenum] == NULL)
1957         {
1958                 VM_Warning(prog, "VM_fgets: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
1959                 return;
1960         }
1961         end = 0;
1962         for (;;)
1963         {
1964                 c = FS_Getc(prog->openfiles[filenum]);
1965                 if (c == '\r' || c == '\n' || c < 0)
1966                         break;
1967                 if (end < VM_STRINGTEMP_LENGTH - 1)
1968                         string[end++] = c;
1969         }
1970         string[end] = 0;
1971         // remove \n following \r
1972         if (c == '\r')
1973         {
1974                 c = FS_Getc(prog->openfiles[filenum]);
1975                 if (c != '\n')
1976                         FS_UnGetc(prog->openfiles[filenum], (unsigned char)c);
1977         }
1978         if (developer_extra.integer)
1979                 Con_DPrintf("fgets: %s: %s\n", prog->name, string);
1980         if (c >= 0 || end)
1981                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
1982 }
1983
1984 /*
1985 =========
1986 VM_fputs
1987
1988 fputs(float fhandle, string s)
1989 =========
1990 */
1991 //void(float fhandle, string s) fputs = #113; // writes a line of text to the end of the file
1992 void VM_fputs(prvm_prog_t *prog)
1993 {
1994         int stringlength;
1995         char string[VM_STRINGTEMP_LENGTH];
1996         int filenum;
1997
1998         VM_SAFEPARMCOUNT(2,VM_fputs);
1999
2000         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
2001         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
2002         {
2003                 VM_Warning(prog, "VM_fputs: invalid file handle %i used in %s\n", filenum, prog->name);
2004                 return;
2005         }
2006         if (prog->openfiles[filenum] == NULL)
2007         {
2008                 VM_Warning(prog, "VM_fputs: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
2009                 return;
2010         }
2011         VM_VarString(prog, 1, string, sizeof(string));
2012         if ((stringlength = (int)strlen(string)))
2013                 FS_Write(prog->openfiles[filenum], string, stringlength);
2014         if (developer_extra.integer)
2015                 Con_DPrintf("fputs: %s: %s\n", prog->name, string);
2016 }
2017
2018 /*
2019 =========
2020 VM_writetofile
2021
2022         writetofile(float fhandle, entity ent)
2023 =========
2024 */
2025 void VM_writetofile(prvm_prog_t *prog)
2026 {
2027         prvm_edict_t * ent;
2028         qfile_t *file;
2029
2030         VM_SAFEPARMCOUNT(2, VM_writetofile);
2031
2032         file = VM_GetFileHandle(prog, (int)PRVM_G_FLOAT(OFS_PARM0));
2033         if( !file )
2034         {
2035                 VM_Warning(prog, "VM_writetofile: invalid or closed file handle\n");
2036                 return;
2037         }
2038
2039         ent = PRVM_G_EDICT(OFS_PARM1);
2040         if(ent->free)
2041         {
2042                 VM_Warning(prog, "VM_writetofile: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2043                 return;
2044         }
2045
2046         PRVM_ED_Write (prog, file, ent);
2047 }
2048
2049 // KrimZon - DP_QC_ENTITYDATA
2050 /*
2051 =========
2052 VM_numentityfields
2053
2054 float() numentityfields
2055 Return the number of entity fields - NOT offsets
2056 =========
2057 */
2058 void VM_numentityfields(prvm_prog_t *prog)
2059 {
2060         PRVM_G_FLOAT(OFS_RETURN) = prog->numfielddefs;
2061 }
2062
2063 // KrimZon - DP_QC_ENTITYDATA
2064 /*
2065 =========
2066 VM_entityfieldname
2067
2068 string(float fieldnum) entityfieldname
2069 Return name of the specified field as a string, or empty if the field is invalid (warning)
2070 =========
2071 */
2072 void VM_entityfieldname(prvm_prog_t *prog)
2073 {
2074         mdef_t *d;
2075         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2076
2077         if (i < 0 || i >= prog->numfielddefs)
2078         {
2079                 VM_Warning(prog, "VM_entityfieldname: %s: field index out of bounds\n", prog->name);
2080                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
2081                 return;
2082         }
2083
2084         d = &prog->fielddefs[i];
2085         PRVM_G_INT(OFS_RETURN) = d->s_name; // presuming that s_name points to a string already
2086 }
2087
2088 // KrimZon - DP_QC_ENTITYDATA
2089 /*
2090 =========
2091 VM_entityfieldtype
2092
2093 float(float fieldnum) entityfieldtype
2094 =========
2095 */
2096 void VM_entityfieldtype(prvm_prog_t *prog)
2097 {
2098         mdef_t *d;
2099         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2100         
2101         if (i < 0 || i >= prog->numfielddefs)
2102         {
2103                 VM_Warning(prog, "VM_entityfieldtype: %s: field index out of bounds\n", prog->name);
2104                 PRVM_G_FLOAT(OFS_RETURN) = -1.0;
2105                 return;
2106         }
2107         
2108         d = &prog->fielddefs[i];
2109         PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t)d->type;
2110 }
2111
2112 // KrimZon - DP_QC_ENTITYDATA
2113 /*
2114 =========
2115 VM_getentityfieldstring
2116
2117 string(float fieldnum, entity ent) getentityfieldstring
2118 =========
2119 */
2120 void VM_getentityfieldstring(prvm_prog_t *prog)
2121 {
2122         // put the data into a string
2123         mdef_t *d;
2124         int type, j;
2125         prvm_eval_t *val;
2126         prvm_edict_t * ent;
2127         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2128         char valuebuf[MAX_INPUTLINE];
2129         
2130         if (i < 0 || i >= prog->numfielddefs)
2131         {
2132         VM_Warning(prog, "VM_entityfielddata: %s: field index out of bounds\n", prog->name);
2133                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
2134                 return;
2135         }
2136         
2137         d = &prog->fielddefs[i];
2138         
2139         // get the entity
2140         ent = PRVM_G_EDICT(OFS_PARM1);
2141         if(ent->free)
2142         {
2143                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
2144                 VM_Warning(prog, "VM_entityfielddata: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2145                 return;
2146         }
2147         val = (prvm_eval_t *)(ent->fields.fp + d->ofs);
2148         
2149         // if it's 0 or blank, return an empty string
2150         type = d->type & ~DEF_SAVEGLOBAL;
2151         for (j=0 ; j<prvm_type_size[type] ; j++)
2152                 if (val->ivector[j])
2153                         break;
2154         if (j == prvm_type_size[type])
2155         {
2156                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
2157                 return;
2158         }
2159                 
2160         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, PRVM_UglyValueString(prog, (etype_t)d->type, val, valuebuf, sizeof(valuebuf)));
2161 }
2162
2163 // KrimZon - DP_QC_ENTITYDATA
2164 /*
2165 =========
2166 VM_putentityfieldstring
2167
2168 float(float fieldnum, entity ent, string s) putentityfieldstring
2169 =========
2170 */
2171 void VM_putentityfieldstring(prvm_prog_t *prog)
2172 {
2173         mdef_t *d;
2174         prvm_edict_t * ent;
2175         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2176
2177         if (i < 0 || i >= prog->numfielddefs)
2178         {
2179         VM_Warning(prog, "VM_entityfielddata: %s: field index out of bounds\n", prog->name);
2180                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2181                 return;
2182         }
2183
2184         d = &prog->fielddefs[i];
2185
2186         // get the entity
2187         ent = PRVM_G_EDICT(OFS_PARM1);
2188         if(ent->free)
2189         {
2190                 VM_Warning(prog, "VM_entityfielddata: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2191                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2192                 return;
2193         }
2194
2195         // parse the string into the value
2196         PRVM_G_FLOAT(OFS_RETURN) = ( PRVM_ED_ParseEpair(prog, ent, d, PRVM_G_STRING(OFS_PARM2), false) ) ? 1.0f : 0.0f;
2197 }
2198
2199 /*
2200 =========
2201 VM_strlen
2202
2203 float   strlen(string s)
2204 =========
2205 */
2206 //float(string s) strlen = #114; // returns how many characters are in a string
2207 void VM_strlen(prvm_prog_t *prog)
2208 {
2209         VM_SAFEPARMCOUNT(1,VM_strlen);
2210
2211         //PRVM_G_FLOAT(OFS_RETURN) = strlen(PRVM_G_STRING(OFS_PARM0));
2212         PRVM_G_FLOAT(OFS_RETURN) = u8_strlen(PRVM_G_STRING(OFS_PARM0));
2213 }
2214
2215 // DRESK - Decolorized String
2216 /*
2217 =========
2218 VM_strdecolorize
2219
2220 string  strdecolorize(string s)
2221 =========
2222 */
2223 // string (string s) strdecolorize = #472; // returns the passed in string with color codes stripped
2224 void VM_strdecolorize(prvm_prog_t *prog)
2225 {
2226         char szNewString[VM_STRINGTEMP_LENGTH];
2227         const char *szString;
2228
2229         // Prepare Strings
2230         VM_SAFEPARMCOUNT(1,VM_strdecolorize);
2231         szString = PRVM_G_STRING(OFS_PARM0);
2232         COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), true);
2233         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString);
2234 }
2235
2236 // DRESK - String Length (not counting color codes)
2237 /*
2238 =========
2239 VM_strlennocol
2240
2241 float   strlennocol(string s)
2242 =========
2243 */
2244 // float(string s) strlennocol = #471; // returns how many characters are in a string not including color codes
2245 // For example, ^2Dresk returns a length of 5
2246 void VM_strlennocol(prvm_prog_t *prog)
2247 {
2248         const char *szString;
2249         int nCnt;
2250
2251         VM_SAFEPARMCOUNT(1,VM_strlennocol);
2252
2253         szString = PRVM_G_STRING(OFS_PARM0);
2254
2255         //nCnt = (int)COM_StringLengthNoColors(szString, 0, NULL);
2256         nCnt = (int)u8_COM_StringLengthNoColors(szString, 0, NULL);
2257
2258         PRVM_G_FLOAT(OFS_RETURN) = nCnt;
2259 }
2260
2261 // DRESK - String to Uppercase and Lowercase
2262 /*
2263 =========
2264 VM_strtolower
2265
2266 string  strtolower(string s)
2267 =========
2268 */
2269 // string (string s) strtolower = #480; // returns passed in string in lowercase form
2270 void VM_strtolower(prvm_prog_t *prog)
2271 {
2272         char szNewString[VM_STRINGTEMP_LENGTH];
2273         const char *szString;
2274
2275         // Prepare Strings
2276         VM_SAFEPARMCOUNT(1,VM_strtolower);
2277         szString = PRVM_G_STRING(OFS_PARM0);
2278
2279         COM_ToLowerString(szString, szNewString, sizeof(szNewString) );
2280
2281         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString);
2282 }
2283
2284 /*
2285 =========
2286 VM_strtoupper
2287
2288 string  strtoupper(string s)
2289 =========
2290 */
2291 // string (string s) strtoupper = #481; // returns passed in string in uppercase form
2292 void VM_strtoupper(prvm_prog_t *prog)
2293 {
2294         char szNewString[VM_STRINGTEMP_LENGTH];
2295         const char *szString;
2296
2297         // Prepare Strings
2298         VM_SAFEPARMCOUNT(1,VM_strtoupper);
2299         szString = PRVM_G_STRING(OFS_PARM0);
2300
2301         COM_ToUpperString(szString, szNewString, sizeof(szNewString) );
2302
2303         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString);
2304 }
2305
2306 /*
2307 =========
2308 VM_strcat
2309
2310 string strcat(string,string,...[string])
2311 =========
2312 */
2313 //string(string s1, string s2) strcat = #115;
2314 // concatenates two strings (for example "abc", "def" would return "abcdef")
2315 // and returns as a tempstring
2316 void VM_strcat(prvm_prog_t *prog)
2317 {
2318         char s[VM_STRINGTEMP_LENGTH];
2319         VM_SAFEPARMCOUNTRANGE(1, 8, VM_strcat);
2320
2321         VM_VarString(prog, 0, s, sizeof(s));
2322         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s);
2323 }
2324
2325 /*
2326 =========
2327 VM_substring
2328
2329 string  substring(string s, float start, float length)
2330 =========
2331 */
2332 // string(string s, float start, float length) substring = #116;
2333 // returns a section of a string as a tempstring
2334 void VM_substring(prvm_prog_t *prog)
2335 {
2336         int start, length;
2337         int u_slength = 0, u_start;
2338         size_t u_length;
2339         const char *s;
2340         char string[VM_STRINGTEMP_LENGTH];
2341
2342         VM_SAFEPARMCOUNT(3,VM_substring);
2343
2344         /*
2345         s = PRVM_G_STRING(OFS_PARM0);
2346         start = (int)PRVM_G_FLOAT(OFS_PARM1);
2347         length = (int)PRVM_G_FLOAT(OFS_PARM2);
2348         slength = strlen(s);
2349
2350         if (start < 0) // FTE_STRINGS feature
2351                 start += slength;
2352         start = bound(0, start, slength);
2353
2354         if (length < 0) // FTE_STRINGS feature
2355                 length += slength - start + 1;
2356         maxlen = min((int)sizeof(string) - 1, slength - start);
2357         length = bound(0, length, maxlen);
2358
2359         memcpy(string, s + start, length);
2360         string[length] = 0;
2361         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2362         */
2363         
2364         s = PRVM_G_STRING(OFS_PARM0);
2365         start = (int)PRVM_G_FLOAT(OFS_PARM1);
2366         length = (int)PRVM_G_FLOAT(OFS_PARM2);
2367
2368         if (start < 0) // FTE_STRINGS feature
2369         {
2370                 u_slength = (int)u8_strlen(s);
2371                 start += u_slength;
2372                 start = bound(0, start, u_slength);
2373         }
2374
2375         if (length < 0) // FTE_STRINGS feature
2376         {
2377                 if (!u_slength) // it's not calculated when it's not needed above
2378                         u_slength = (int)u8_strlen(s);
2379                 length += u_slength - start + 1;
2380         }
2381                 
2382         // positive start, positive length
2383         u_start = u8_byteofs(s, start, NULL);
2384         if (u_start < 0)
2385         {
2386                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
2387                 return;
2388         }
2389         u_length = u8_bytelen(s + u_start, length);
2390         if (u_length >= sizeof(string)-1)
2391                 u_length = sizeof(string)-1;
2392         
2393         memcpy(string, s + u_start, u_length);
2394         string[u_length] = 0;
2395         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2396 }
2397
2398 /*
2399 =========
2400 VM_strreplace
2401
2402 string(string search, string replace, string subject) strreplace = #484;
2403 =========
2404 */
2405 // replaces all occurrences of search with replace in the string subject, and returns the result
2406 void VM_strreplace(prvm_prog_t *prog)
2407 {
2408         int i, j, si;
2409         const char *search, *replace, *subject;
2410         char string[VM_STRINGTEMP_LENGTH];
2411         int search_len, replace_len, subject_len;
2412
2413         VM_SAFEPARMCOUNT(3,VM_strreplace);
2414
2415         search = PRVM_G_STRING(OFS_PARM0);
2416         replace = PRVM_G_STRING(OFS_PARM1);
2417         subject = PRVM_G_STRING(OFS_PARM2);
2418
2419         search_len = (int)strlen(search);
2420         replace_len = (int)strlen(replace);
2421         subject_len = (int)strlen(subject);
2422
2423         si = 0;
2424         for (i = 0; i <= subject_len - search_len; i++)
2425         {
2426                 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2427                         if (subject[i+j] != search[j])
2428                                 break;
2429                 if (j == search_len)
2430                 {
2431                         // NOTE: if search_len == 0, we always hit THIS case, and never the other
2432                         // found it at offset 'i'
2433                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2434                                 string[si++] = replace[j];
2435                         if(search_len > 0)
2436                         {
2437                                 i += search_len - 1;
2438                         }
2439                         else
2440                         {
2441                                 // the above would subtract 1 from i... so we
2442                                 // don't do that, but instead output the next
2443                                 // char
2444                                 if (si < (int)sizeof(string) - 1)
2445                                         string[si++] = subject[i];
2446                         }
2447                 }
2448                 else
2449                 {
2450                         // in THIS case, we know search_len > 0, thus i < subject_len
2451                         // not found
2452                         if (si < (int)sizeof(string) - 1)
2453                                 string[si++] = subject[i];
2454                 }
2455         }
2456         // remaining chars (these cannot match)
2457         for (; i < subject_len; i++)
2458                 if (si < (int)sizeof(string) - 1)
2459                         string[si++] = subject[i];
2460         string[si] = '\0';
2461
2462         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2463 }
2464
2465 /*
2466 =========
2467 VM_strireplace
2468
2469 string(string search, string replace, string subject) strireplace = #485;
2470 =========
2471 */
2472 // case-insensitive version of strreplace
2473 void VM_strireplace(prvm_prog_t *prog)
2474 {
2475         int i, j, si;
2476         const char *search, *replace, *subject;
2477         char string[VM_STRINGTEMP_LENGTH];
2478         int search_len, replace_len, subject_len;
2479
2480         VM_SAFEPARMCOUNT(3, VM_strireplace);
2481
2482         search = PRVM_G_STRING(OFS_PARM0);
2483         replace = PRVM_G_STRING(OFS_PARM1);
2484         subject = PRVM_G_STRING(OFS_PARM2);
2485
2486         search_len = (int)strlen(search);
2487         replace_len = (int)strlen(replace);
2488         subject_len = (int)strlen(subject);
2489
2490         si = 0;
2491         for (i = 0; i <= subject_len - search_len; i++)
2492         {
2493                 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2494                         if (tolower(subject[i+j]) != tolower(search[j]))
2495                                 break;
2496                 if (j == search_len)
2497                 {
2498                         // NOTE: if search_len == 0, we always hit THIS case, and never the other
2499                         // found it at offset 'i'
2500                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2501                                 string[si++] = replace[j];
2502                         if(search_len > 0)
2503                         {
2504                                 i += search_len - 1;
2505                         }
2506                         else
2507                         {
2508                                 // the above would subtract 1 from i... so we
2509                                 // don't do that, but instead output the next
2510                                 // char
2511                                 if (si < (int)sizeof(string) - 1)
2512                                         string[si++] = subject[i];
2513                         }
2514                 }
2515                 else
2516                 {
2517                         // in THIS case, we know search_len > 0, thus i < subject_len
2518                         // not found
2519                         if (si < (int)sizeof(string) - 1)
2520                                 string[si++] = subject[i];
2521                 }
2522         }
2523         // remaining chars (these cannot match)
2524         for (; i < subject_len; i++)
2525                 if (si < (int)sizeof(string) - 1)
2526                         string[si++] = subject[i];
2527         string[si] = '\0';
2528
2529         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2530 }
2531
2532 /*
2533 =========
2534 VM_stov
2535
2536 vector  stov(string s)
2537 =========
2538 */
2539 //vector(string s) stov = #117; // returns vector value from a string
2540 void VM_stov(prvm_prog_t *prog)
2541 {
2542         char string[VM_STRINGTEMP_LENGTH];
2543
2544         VM_SAFEPARMCOUNT(1,VM_stov);
2545
2546         VM_VarString(prog, 0, string, sizeof(string));
2547         Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
2548 }
2549
2550 /*
2551 =========
2552 VM_strzone
2553
2554 string  strzone(string s)
2555 =========
2556 */
2557 //string(string s, ...) strzone = #118; // makes a copy of a string into the string zone and returns it, this is often used to keep around a tempstring for longer periods of time (tempstrings are replaced often)
2558 void VM_strzone(prvm_prog_t *prog)
2559 {
2560         char *out;
2561         char string[VM_STRINGTEMP_LENGTH];
2562         size_t alloclen;
2563
2564         VM_SAFEPARMCOUNT(1,VM_strzone);
2565
2566         VM_VarString(prog, 0, string, sizeof(string));
2567         alloclen = strlen(string) + 1;
2568         PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(prog, alloclen, &out);
2569         memcpy(out, string, alloclen);
2570 }
2571
2572 /*
2573 =========
2574 VM_strunzone
2575
2576 strunzone(string s)
2577 =========
2578 */
2579 //void(string s) strunzone = #119; // removes a copy of a string from the string zone (you can not use that string again or it may crash!!!)
2580 void VM_strunzone(prvm_prog_t *prog)
2581 {
2582         VM_SAFEPARMCOUNT(1,VM_strunzone);
2583         PRVM_FreeString(prog, PRVM_G_INT(OFS_PARM0));
2584 }
2585
2586 /*
2587 =========
2588 VM_tokenize
2589
2590 float tokenize(string s)
2591 =========
2592 */
2593 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
2594 //this function originally written by KrimZon, made shorter by LadyHavoc
2595 //20040203: rewritten by LadyHavoc (no longer uses allocations)
2596 static int num_tokens = 0;
2597 static int tokens[VM_STRINGTEMP_LENGTH / 2];
2598 static int tokens_startpos[VM_STRINGTEMP_LENGTH / 2];
2599 static int tokens_endpos[VM_STRINGTEMP_LENGTH / 2];
2600 static char tokenize_string[VM_STRINGTEMP_LENGTH];
2601 void VM_tokenize (prvm_prog_t *prog)
2602 {
2603         const char *p;
2604
2605         VM_SAFEPARMCOUNT(1,VM_tokenize);
2606
2607         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2608         p = tokenize_string;
2609
2610         num_tokens = 0;
2611         for(;;)
2612         {
2613                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2614                         break;
2615
2616                 // skip whitespace here to find token start pos
2617                 while(*p && ISWHITESPACE(*p))
2618                         ++p;
2619
2620                 tokens_startpos[num_tokens] = p - tokenize_string;
2621                 if(!COM_ParseToken_VM_Tokenize(&p, false))
2622                         break;
2623                 tokens_endpos[num_tokens] = p - tokenize_string;
2624                 tokens[num_tokens] = PRVM_SetTempString(prog, com_token);
2625                 ++num_tokens;
2626         }
2627
2628         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2629 }
2630
2631 //float(string s) tokenize = #514; // takes apart a string into individal words (access them with argv), returns how many
2632 void VM_tokenize_console (prvm_prog_t *prog)
2633 {
2634         const char *p;
2635
2636         VM_SAFEPARMCOUNT(1, VM_tokenize_console);
2637
2638         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2639         p = tokenize_string;
2640
2641         num_tokens = 0;
2642         for(;;)
2643         {
2644                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2645                         break;
2646
2647                 // skip whitespace here to find token start pos
2648                 while(*p && ISWHITESPACE(*p))
2649                         ++p;
2650
2651                 tokens_startpos[num_tokens] = p - tokenize_string;
2652                 if(!COM_ParseToken_Console(&p))
2653                         break;
2654                 tokens_endpos[num_tokens] = p - tokenize_string;
2655                 tokens[num_tokens] = PRVM_SetTempString(prog, com_token);
2656                 ++num_tokens;
2657         }
2658
2659         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2660 }
2661
2662 /*
2663 =========
2664 VM_tokenizebyseparator
2665
2666 float tokenizebyseparator(string s, string separator1, ...)
2667 =========
2668 */
2669 //float(string s, string separator1, ...) tokenizebyseparator = #479; // takes apart a string into individal words (access them with argv), returns how many
2670 //this function returns the token preceding each instance of a separator (of
2671 //which there can be multiple), and the text following the last separator
2672 //useful for parsing certain kinds of data like IP addresses
2673 //example:
2674 //numnumbers = tokenizebyseparator("10.1.2.3", ".");
2675 //returns 4 and the tokens "10" "1" "2" "3".
2676 void VM_tokenizebyseparator (prvm_prog_t *prog)
2677 {
2678         int j, k;
2679         int numseparators;
2680         int separatorlen[7];
2681         const char *separators[7];
2682         const char *p, *p0;
2683         const char *token;
2684         char tokentext[MAX_INPUTLINE];
2685
2686         VM_SAFEPARMCOUNTRANGE(2, 8,VM_tokenizebyseparator);
2687
2688         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2689         p = tokenize_string;
2690
2691         numseparators = 0;
2692         for (j = 1;j < prog->argc;j++)
2693         {
2694                 // skip any blank separator strings
2695                 const char *s = PRVM_G_STRING(OFS_PARM0+j*3);
2696                 if (!s[0])
2697                         continue;
2698                 separators[numseparators] = s;
2699                 separatorlen[numseparators] = (int)strlen(s);
2700                 numseparators++;
2701         }
2702
2703         num_tokens = 0;
2704         j = 0;
2705
2706         while (num_tokens < (int)(sizeof(tokens)/sizeof(tokens[0])))
2707         {
2708                 token = tokentext + j;
2709                 tokens_startpos[num_tokens] = p - tokenize_string;
2710                 p0 = p;
2711                 while (*p)
2712                 {
2713                         for (k = 0;k < numseparators;k++)
2714                         {
2715                                 if (!strncmp(p, separators[k], separatorlen[k]))
2716                                 {
2717                                         p += separatorlen[k];
2718                                         break;
2719                                 }
2720                         }
2721                         if (k < numseparators)
2722                                 break;
2723                         if (j < (int)sizeof(tokentext)-1)
2724                                 tokentext[j++] = *p;
2725                         p++;
2726                         p0 = p;
2727                 }
2728                 tokens_endpos[num_tokens] = p0 - tokenize_string;
2729                 if (j >= (int)sizeof(tokentext))
2730                         break;
2731                 tokentext[j++] = 0;
2732                 tokens[num_tokens++] = PRVM_SetTempString(prog, token);
2733                 if (!*p)
2734                         break;
2735         }
2736
2737         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2738 }
2739
2740 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
2741 //this function originally written by KrimZon, made shorter by LadyHavoc
2742 void VM_argv (prvm_prog_t *prog)
2743 {
2744         int token_num;
2745
2746         VM_SAFEPARMCOUNT(1,VM_argv);
2747
2748         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2749
2750         if(token_num < 0)
2751                 token_num += num_tokens;
2752
2753         if (token_num >= 0 && token_num < num_tokens)
2754                 PRVM_G_INT(OFS_RETURN) = tokens[token_num];
2755         else
2756                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2757 }
2758
2759 //float(float n) argv_start_index = #515; // returns the start index of a token
2760 void VM_argv_start_index (prvm_prog_t *prog)
2761 {
2762         int token_num;
2763
2764         VM_SAFEPARMCOUNT(1,VM_argv);
2765
2766         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2767
2768         if(token_num < 0)
2769                 token_num += num_tokens;
2770
2771         if (token_num >= 0 && token_num < num_tokens)
2772                 PRVM_G_FLOAT(OFS_RETURN) = tokens_startpos[token_num];
2773         else
2774                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2775 }
2776
2777 //float(float n) argv_end_index = #516; // returns the end index of a token
2778 void VM_argv_end_index (prvm_prog_t *prog)
2779 {
2780         int token_num;
2781
2782         VM_SAFEPARMCOUNT(1,VM_argv);
2783
2784         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2785
2786         if(token_num < 0)
2787                 token_num += num_tokens;
2788
2789         if (token_num >= 0 && token_num < num_tokens)
2790                 PRVM_G_FLOAT(OFS_RETURN) = tokens_endpos[token_num];
2791         else
2792                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2793 }
2794
2795 /*
2796 =========
2797 VM_isserver
2798
2799 float   isserver()
2800 =========
2801 */
2802 void VM_isserver(prvm_prog_t *prog)
2803 {
2804         VM_SAFEPARMCOUNT(0, VM_isserver);
2805
2806         PRVM_G_FLOAT(OFS_RETURN) = sv.active;
2807 }
2808
2809 /*
2810 =========
2811 VM_clientcount
2812
2813 float   clientcount()
2814 =========
2815 */
2816 void VM_clientcount(prvm_prog_t *prog)
2817 {
2818         VM_SAFEPARMCOUNT(0,VM_clientcount);
2819
2820         PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
2821 }
2822
2823 /*
2824 =========
2825 VM_clientstate
2826
2827 float   clientstate()
2828 =========
2829 */
2830 void VM_clientstate(prvm_prog_t *prog)
2831 {
2832         VM_SAFEPARMCOUNT(0,VM_clientstate);
2833
2834
2835         switch( cls.state ) {
2836                 case ca_uninitialized:
2837                 case ca_dedicated:
2838                         PRVM_G_FLOAT(OFS_RETURN) = 0;
2839                         break;
2840                 case ca_disconnected:
2841                         PRVM_G_FLOAT(OFS_RETURN) = 1;
2842                         break;
2843                 case ca_connected:
2844                         PRVM_G_FLOAT(OFS_RETURN) = 2;
2845                         break;
2846                 default:
2847                         // should never be reached!
2848                         break;
2849         }
2850 }
2851
2852 /*
2853 =========
2854 VM_getostype
2855
2856 float   getostype(prvm_prog_t *prog)
2857 =========
2858 */ // not used at the moment -> not included in the common list
2859 void VM_getostype(prvm_prog_t *prog)
2860 {
2861         VM_SAFEPARMCOUNT(0,VM_getostype);
2862
2863         /*
2864         OS_WINDOWS
2865         OS_LINUX
2866         OS_MAC - not supported
2867         */
2868
2869 #ifdef WIN32
2870         PRVM_G_FLOAT(OFS_RETURN) = 0;
2871 #elif defined(MACOSX)
2872         PRVM_G_FLOAT(OFS_RETURN) = 2;
2873 #else
2874         PRVM_G_FLOAT(OFS_RETURN) = 1;
2875 #endif
2876 }
2877
2878 /*
2879 =========
2880 VM_gettime
2881
2882 float   gettime(prvm_prog_t *prog)
2883 =========
2884 */
2885 float CDAudio_GetPosition(void);
2886 void VM_gettime(prvm_prog_t *prog)
2887 {
2888         int timer_index;
2889
2890         VM_SAFEPARMCOUNTRANGE(0,1,VM_gettime);
2891
2892         if(prog->argc == 0)
2893         {
2894                 PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t) host.realtime;
2895         }
2896         else
2897         {
2898                 timer_index = (int) PRVM_G_FLOAT(OFS_PARM0);
2899                 switch(timer_index)
2900                 {
2901                         case 0: // GETTIME_FRAMESTART
2902                                 PRVM_G_FLOAT(OFS_RETURN) = host.realtime;
2903                                 break;
2904                         case 1: // GETTIME_REALTIME
2905                                 PRVM_G_FLOAT(OFS_RETURN) = Sys_DirtyTime();
2906                                 break;
2907                         case 2: // GETTIME_HIRES
2908                                 PRVM_G_FLOAT(OFS_RETURN) = (Sys_DirtyTime() - host.dirtytime);
2909                                 break;
2910                         case 3: // GETTIME_UPTIME
2911                                 PRVM_G_FLOAT(OFS_RETURN) = host.realtime;
2912                                 break;
2913                         case 4: // GETTIME_CDTRACK
2914                                 PRVM_G_FLOAT(OFS_RETURN) = CDAudio_GetPosition();
2915                                 break;
2916                         default:
2917                                 VM_Warning(prog, "VM_gettime: %s: unsupported timer specified, returning realtime\n", prog->name);
2918                                 PRVM_G_FLOAT(OFS_RETURN) = host.realtime;
2919                                 break;
2920                 }
2921         }
2922 }
2923
2924 /*
2925 =========
2926 VM_getsoundtime
2927
2928 float   getsoundtime(prvm_prog_t *prog)
2929 =========
2930 */
2931
2932 void VM_getsoundtime (prvm_prog_t *prog)
2933 {
2934         int entnum, entchannel;
2935         VM_SAFEPARMCOUNT(2,VM_getsoundtime);
2936
2937         if (prog == SVVM_prog)
2938                 entnum = PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
2939         else if (prog == CLVM_prog)
2940                 entnum = MAX_EDICTS + PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
2941         else
2942         {
2943                 VM_Warning(prog, "VM_getsoundtime: %s: not supported on this progs\n", prog->name);
2944                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2945                 return;
2946         }
2947         entchannel = (int)PRVM_G_FLOAT(OFS_PARM1);
2948         entchannel = CHAN_USER2ENGINE(entchannel);
2949         if (!IS_CHAN(entchannel))
2950                 VM_Warning(prog, "VM_getsoundtime: %s: bad channel %i\n", prog->name, entchannel);
2951         PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t)S_GetEntChannelPosition(entnum, entchannel);
2952 }
2953
2954 /*
2955 =========
2956 VM_GetSoundLen
2957
2958 string  soundlength (string sample)
2959 =========
2960 */
2961 void VM_soundlength (prvm_prog_t *prog)
2962 {
2963         const char *s;
2964
2965         VM_SAFEPARMCOUNT(1, VM_soundlength);
2966
2967         s = PRVM_G_STRING(OFS_PARM0);
2968         PRVM_G_FLOAT(OFS_RETURN) = S_SoundLength(s);
2969 }
2970
2971 /*
2972 =========
2973 VM_loadfromdata
2974
2975 loadfromdata(string data)
2976 =========
2977 */
2978 void VM_loadfromdata(prvm_prog_t *prog)
2979 {
2980         VM_SAFEPARMCOUNT(1, VM_loadfromdata);
2981
2982         PRVM_ED_LoadFromFile(prog, PRVM_G_STRING(OFS_PARM0));
2983 }
2984
2985 /*
2986 ========================
2987 VM_parseentitydata
2988
2989 parseentitydata(entity ent, string data)
2990 ========================
2991 */
2992 void VM_parseentitydata(prvm_prog_t *prog)
2993 {
2994         prvm_edict_t *ent;
2995         const char *data;
2996
2997         VM_SAFEPARMCOUNT(2, VM_parseentitydata);
2998
2999         // get edict and test it
3000         ent = PRVM_G_EDICT(OFS_PARM0);
3001         if (ent->free)
3002                 prog->error_cmd("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", prog->name, PRVM_NUM_FOR_EDICT(ent));
3003
3004         data = PRVM_G_STRING(OFS_PARM1);
3005
3006         // parse the opening brace
3007         if (!COM_ParseToken_Simple(&data, false, false, true) || com_token[0] != '{' )
3008                 prog->error_cmd("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", prog->name, data );
3009
3010         PRVM_ED_ParseEdict (prog, data, ent);
3011 }
3012
3013 /*
3014 =========
3015 VM_loadfromfile
3016
3017 loadfromfile(string file)
3018 =========
3019 */
3020 void VM_loadfromfile(prvm_prog_t *prog)
3021 {
3022         const char *filename;
3023         char *data;
3024
3025         VM_SAFEPARMCOUNT(1,VM_loadfromfile);
3026
3027         filename = PRVM_G_STRING(OFS_PARM0);
3028         if (FS_CheckNastyPath(filename, false))
3029         {
3030                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3031                 VM_Warning(prog, "VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", prog->name, filename);
3032                 return;
3033         }
3034
3035         // not conform with VM_fopen
3036         data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
3037         if (data == NULL)
3038                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3039
3040         PRVM_ED_LoadFromFile(prog, data);
3041
3042         if(data)
3043                 Mem_Free(data);
3044 }
3045
3046
3047 /*
3048 =========
3049 VM_modulo
3050
3051 float   mod(float val, float m)
3052 =========
3053 */
3054 void VM_modulo(prvm_prog_t *prog)
3055 {
3056         prvm_int_t val, m;
3057         VM_SAFEPARMCOUNT(2, VM_modulo);
3058
3059         val = (prvm_int_t) PRVM_G_FLOAT(OFS_PARM0);
3060         m       = (prvm_int_t) PRVM_G_FLOAT(OFS_PARM1);
3061
3062         PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t) (val % m);
3063 }
3064
3065 static void VM_Search_Init(prvm_prog_t *prog)
3066 {
3067         int i;
3068         for (i = 0;i < PRVM_MAX_OPENSEARCHES;i++)
3069                 prog->opensearches[i] = NULL;
3070 }
3071
3072 static void VM_Search_Reset(prvm_prog_t *prog)
3073 {
3074         int i;
3075         // reset the fssearch list
3076         for(i = 0; i < PRVM_MAX_OPENSEARCHES; i++)
3077         {
3078                 if(prog->opensearches[i])
3079                         FS_FreeSearch(prog->opensearches[i]);
3080                 prog->opensearches[i] = NULL;
3081         }
3082 }
3083
3084 /*
3085 =========
3086 VM_search_begin
3087
3088 float search_begin(string pattern, float caseinsensitive, float quiet[, string packfile])
3089 =========
3090 */
3091 void VM_search_begin(prvm_prog_t *prog)
3092 {
3093         int handle;
3094         const char *packfile = NULL, *pattern;
3095         int caseinsens, quiet;
3096
3097         VM_SAFEPARMCOUNTRANGE(3, 4, VM_search_begin);
3098
3099         pattern = PRVM_G_STRING(OFS_PARM0);
3100
3101         VM_CheckEmptyString(prog, pattern);
3102
3103         caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
3104         quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
3105
3106         // optional packfile parameter (DP_QC_FS_SEARCH_PACKFILE)
3107         if(prog->argc >= 4)
3108                 packfile = PRVM_G_STRING(OFS_PARM3);
3109
3110         for(handle = 0; handle < PRVM_MAX_OPENSEARCHES; handle++)
3111                 if(!prog->opensearches[handle])
3112                         break;
3113
3114         if(handle >= PRVM_MAX_OPENSEARCHES)
3115         {
3116                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3117                 VM_Warning(prog, "VM_search_begin: %s ran out of search handles (%i)\n", prog->name, PRVM_MAX_OPENSEARCHES);
3118                 return;
3119         }
3120
3121         if(!(prog->opensearches[handle] = FS_Search(pattern,caseinsens, quiet, packfile)))
3122                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3123         else
3124         {
3125                 prog->opensearches_origin[handle] = PRVM_AllocationOrigin(prog);
3126                 PRVM_G_FLOAT(OFS_RETURN) = handle;
3127         }
3128 }
3129
3130 /*
3131 =========
3132 VM_search_end
3133
3134 void    search_end(float handle)
3135 =========
3136 */
3137 void VM_search_end(prvm_prog_t *prog)
3138 {
3139         int handle;
3140         VM_SAFEPARMCOUNT(1, VM_search_end);
3141
3142         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3143
3144         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3145         {
3146                 VM_Warning(prog, "VM_search_end: invalid handle %i used in %s\n", handle, prog->name);
3147                 return;
3148         }
3149         if(prog->opensearches[handle] == NULL)
3150         {
3151                 VM_Warning(prog, "VM_search_end: no such handle %i in %s\n", handle, prog->name);
3152                 return;
3153         }
3154
3155         FS_FreeSearch(prog->opensearches[handle]);
3156         prog->opensearches[handle] = NULL;
3157         if(prog->opensearches_origin[handle])
3158                 PRVM_Free((char *)prog->opensearches_origin[handle]);
3159 }
3160
3161 /*
3162 =========
3163 VM_search_getsize
3164
3165 float   search_getsize(float handle)
3166 =========
3167 */
3168 void VM_search_getsize(prvm_prog_t *prog)
3169 {
3170         int handle;
3171         VM_SAFEPARMCOUNT(1, VM_search_getsize);
3172
3173         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3174
3175         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3176         {
3177                 VM_Warning(prog, "VM_search_getsize: invalid handle %i used in %s\n", handle, prog->name);
3178                 return;
3179         }
3180         if(prog->opensearches[handle] == NULL)
3181         {
3182                 VM_Warning(prog, "VM_search_getsize: no such handle %i in %s\n", handle, prog->name);
3183                 return;
3184         }
3185
3186         PRVM_G_FLOAT(OFS_RETURN) = prog->opensearches[handle]->numfilenames;
3187 }
3188
3189 /*
3190 =========
3191 VM_search_getfilename
3192
3193 string  search_getfilename(float handle, float num)
3194 =========
3195 */
3196 void VM_search_getfilename(prvm_prog_t *prog)
3197 {
3198         int handle, filenum;
3199         VM_SAFEPARMCOUNT(2, VM_search_getfilename);
3200
3201         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3202         filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
3203
3204         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3205         {
3206                 VM_Warning(prog, "VM_search_getfilename: invalid handle %i used in %s\n", handle, prog->name);
3207                 return;
3208         }
3209         if(prog->opensearches[handle] == NULL)
3210         {
3211                 VM_Warning(prog, "VM_search_getfilename: no such handle %i in %s\n", handle, prog->name);
3212                 return;
3213         }
3214         if(filenum < 0 || filenum >= prog->opensearches[handle]->numfilenames)
3215         {
3216                 VM_Warning(prog, "VM_search_getfilename: invalid filenum %i in %s\n", filenum, prog->name);
3217                 return;
3218         }
3219
3220         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, prog->opensearches[handle]->filenames[filenum]);
3221 }
3222
3223 /*
3224 =========
3225 VM_chr
3226
3227 string  chr(float ascii)
3228 =========
3229 */
3230 void VM_chr(prvm_prog_t *prog)
3231 {
3232         /*
3233         char tmp[2];
3234         VM_SAFEPARMCOUNT(1, VM_chr);
3235
3236         tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
3237         tmp[1] = 0;
3238
3239         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, tmp);
3240         */
3241         
3242         char tmp[8];
3243         int len;
3244         VM_SAFEPARMCOUNT(1, VM_chr);
3245
3246         len = u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0), tmp, sizeof(tmp));
3247         tmp[len] = 0;
3248         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, tmp);
3249 }
3250
3251 /*
3252 =========
3253 VM_keynumtostring
3254
3255 string keynumtostring(float keynum)
3256 =========
3257 */
3258 void VM_keynumtostring (prvm_prog_t *prog)
3259 {
3260         char tinystr[2];
3261         VM_SAFEPARMCOUNT(1, VM_keynumtostring);
3262
3263         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, Key_KeynumToString((int)PRVM_G_FLOAT(OFS_PARM0), tinystr, sizeof(tinystr)));
3264 }
3265
3266 /*
3267 =========
3268 VM_findkeysforcommand
3269
3270 string  findkeysforcommand(string command, float bindmap)
3271
3272 the returned string is an altstring
3273 =========
3274 */
3275 #define FKFC_NUMKEYS 5
3276 void M_FindKeysForCommand(const char *command, int *keys);
3277 void VM_findkeysforcommand(prvm_prog_t *prog)
3278 {
3279         const char *cmd;
3280         char ret[VM_STRINGTEMP_LENGTH];
3281         int keys[FKFC_NUMKEYS];
3282         int i;
3283         int bindmap;
3284         char vabuf[1024];
3285
3286         VM_SAFEPARMCOUNTRANGE(1, 2, VM_findkeysforcommand);
3287
3288         cmd = PRVM_G_STRING(OFS_PARM0);
3289         if(prog->argc == 2)
3290                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3291         else
3292                 bindmap = 0; // consistent to "bind"
3293
3294         VM_CheckEmptyString(prog, cmd);
3295
3296         Key_FindKeysForCommand(cmd, keys, FKFC_NUMKEYS, bindmap);
3297
3298         ret[0] = 0;
3299         for(i = 0; i < FKFC_NUMKEYS; i++)
3300                 strlcat(ret, va(vabuf, sizeof(vabuf), " \'%i\'", keys[i]), sizeof(ret));
3301
3302         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, ret);
3303 }
3304
3305 /*
3306 =========
3307 VM_stringtokeynum
3308
3309 float stringtokeynum(string key)
3310 =========
3311 */
3312 void VM_stringtokeynum (prvm_prog_t *prog)
3313 {
3314         VM_SAFEPARMCOUNT( 1, VM_stringtokeynum );
3315
3316         PRVM_G_FLOAT(OFS_RETURN) = Key_StringToKeynum(PRVM_G_STRING(OFS_PARM0));
3317 }
3318
3319 /*
3320 =========
3321 VM_getkeybind
3322
3323 string getkeybind(float key, float bindmap)
3324 =========
3325 */
3326 void VM_getkeybind (prvm_prog_t *prog)
3327 {
3328         int bindmap;
3329         VM_SAFEPARMCOUNTRANGE(1, 2, VM_getkeybind);
3330         if(prog->argc == 2)
3331                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3332         else
3333                 bindmap = 0; // consistent to "bind"
3334
3335         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, Key_GetBind((int)PRVM_G_FLOAT(OFS_PARM0), bindmap));
3336 }
3337
3338 /*
3339 =========
3340 VM_setkeybind
3341
3342 float setkeybind(float key, string cmd, float bindmap)
3343 =========
3344 */
3345 void VM_setkeybind (prvm_prog_t *prog)
3346 {
3347         int bindmap;
3348         VM_SAFEPARMCOUNTRANGE(2, 3, VM_setkeybind);
3349         if(prog->argc == 3)
3350                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM2), MAX_BINDMAPS-1);
3351         else
3352                 bindmap = 0; // consistent to "bind"
3353
3354         PRVM_G_FLOAT(OFS_RETURN) = 0;
3355         if(Key_SetBinding((int)PRVM_G_FLOAT(OFS_PARM0), bindmap, PRVM_G_STRING(OFS_PARM1)))
3356                 PRVM_G_FLOAT(OFS_RETURN) = 1;
3357 }
3358
3359 /*
3360 =========
3361 VM_getbindmap
3362
3363 vector getbindmaps()
3364 =========
3365 */
3366 void VM_getbindmaps (prvm_prog_t *prog)
3367 {
3368         int fg, bg;
3369         VM_SAFEPARMCOUNT(0, VM_getbindmaps);
3370         Key_GetBindMap(&fg, &bg);
3371         PRVM_G_VECTOR(OFS_RETURN)[0] = fg;
3372         PRVM_G_VECTOR(OFS_RETURN)[1] = bg;
3373         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
3374 }
3375
3376 /*
3377 =========
3378 VM_setbindmap
3379
3380 float setbindmaps(vector bindmap)
3381 =========
3382 */
3383 void VM_setbindmaps (prvm_prog_t *prog)
3384 {
3385         VM_SAFEPARMCOUNT(1, VM_setbindmaps);
3386         PRVM_G_FLOAT(OFS_RETURN) = 0;
3387         if(PRVM_G_VECTOR(OFS_PARM0)[2] == 0)
3388                 if(Key_SetBindMap((int)PRVM_G_VECTOR(OFS_PARM0)[0], (int)PRVM_G_VECTOR(OFS_PARM0)[1]))
3389                         PRVM_G_FLOAT(OFS_RETURN) = 1;
3390 }
3391
3392 /*
3393 ========================
3394 VM_gecko_create
3395
3396 float[bool] gecko_create( string name )
3397 ========================
3398 */
3399 void VM_gecko_create(prvm_prog_t *prog) {
3400         // REMOVED
3401         PRVM_G_FLOAT( OFS_RETURN ) = 0;
3402 }
3403
3404 /*
3405 ========================
3406 VM_gecko_destroy
3407
3408 void gecko_destroy( string name )
3409 ========================
3410 */
3411 void VM_gecko_destroy(prvm_prog_t *prog) {
3412         // REMOVED
3413 }
3414
3415 /*
3416 ========================
3417 VM_gecko_navigate
3418
3419 void gecko_navigate( string name, string URI )
3420 ========================
3421 */
3422 void VM_gecko_navigate(prvm_prog_t *prog) {
3423         // REMOVED
3424 }
3425
3426 /*
3427 ========================
3428 VM_gecko_keyevent
3429
3430 float[bool] gecko_keyevent( string name, float key, float eventtype ) 
3431 ========================
3432 */
3433 void VM_gecko_keyevent(prvm_prog_t *prog) {
3434         // REMOVED
3435         PRVM_G_FLOAT( OFS_RETURN ) = 0;
3436 }
3437
3438 /*
3439 ========================
3440 VM_gecko_movemouse
3441
3442 void gecko_mousemove( string name, float x, float y )
3443 ========================
3444 */
3445 void VM_gecko_movemouse(prvm_prog_t *prog) {
3446         // REMOVED
3447 }
3448
3449
3450 /*
3451 ========================
3452 VM_gecko_resize
3453
3454 void gecko_resize( string name, float w, float h )
3455 ========================
3456 */
3457 void VM_gecko_resize(prvm_prog_t *prog) {
3458         // REMOVED
3459 }
3460
3461
3462 /*
3463 ========================
3464 VM_gecko_get_texture_extent
3465
3466 vector gecko_get_texture_extent( string name )
3467 ========================
3468 */
3469 void VM_gecko_get_texture_extent(prvm_prog_t *prog) {
3470         // REMOVED
3471         PRVM_G_VECTOR(OFS_RETURN)[0] = 0;
3472         PRVM_G_VECTOR(OFS_RETURN)[1] = 0;
3473 }
3474
3475
3476
3477 /*
3478 ==============
3479 VM_makevectors
3480
3481 Writes new values for v_forward, v_up, and v_right based on angles
3482 void makevectors(vector angle)
3483 ==============
3484 */
3485 void VM_makevectors (prvm_prog_t *prog)
3486 {
3487         vec3_t angles, forward, right, up;
3488         VM_SAFEPARMCOUNT(1, VM_makevectors);
3489         VectorCopy(PRVM_G_VECTOR(OFS_PARM0), angles);
3490         AngleVectors(angles, forward, right, up);
3491         VectorCopy(forward, PRVM_gameglobalvector(v_forward));
3492         VectorCopy(right, PRVM_gameglobalvector(v_right));
3493         VectorCopy(up, PRVM_gameglobalvector(v_up));
3494 }
3495
3496 /*
3497 ==============
3498 VM_vectorvectors
3499
3500 Writes new values for v_forward, v_up, and v_right based on the given forward vector
3501 vectorvectors(vector)
3502 ==============
3503 */
3504 void VM_vectorvectors (prvm_prog_t *prog)
3505 {
3506         vec3_t forward, right, up;
3507         VM_SAFEPARMCOUNT(1, VM_vectorvectors);
3508         VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), forward);
3509         VectorVectors(forward, right, up);
3510         VectorCopy(forward, PRVM_gameglobalvector(v_forward));
3511         VectorCopy(right, PRVM_gameglobalvector(v_right));
3512         VectorCopy(up, PRVM_gameglobalvector(v_up));
3513 }
3514
3515 // float(float number, float quantity) bitshift (EXT_BITSHIFT)
3516 void VM_bitshift (prvm_prog_t *prog)
3517 {
3518         prvm_int_t n1, n2;
3519         VM_SAFEPARMCOUNT(2, VM_bitshift);
3520
3521         n1 = (prvm_int_t)fabs((prvm_vec_t)((prvm_int_t)PRVM_G_FLOAT(OFS_PARM0)));
3522         n2 = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM1);
3523         if(!n1)
3524                 PRVM_G_FLOAT(OFS_RETURN) = n1;
3525         else
3526         if(n2 < 0)
3527                 PRVM_G_FLOAT(OFS_RETURN) = (n1 >> -n2);
3528         else
3529                 PRVM_G_FLOAT(OFS_RETURN) = (n1 << n2);
3530 }
3531
3532 ////////////////////////////////////////
3533 // AltString functions
3534 ////////////////////////////////////////
3535
3536 /*
3537 ========================
3538 VM_altstr_count
3539
3540 float altstr_count(string)
3541 ========================
3542 */
3543 void VM_altstr_count(prvm_prog_t *prog)
3544 {
3545         const char *altstr, *pos;
3546         int     count;
3547
3548         VM_SAFEPARMCOUNT( 1, VM_altstr_count );
3549
3550         altstr = PRVM_G_STRING( OFS_PARM0 );
3551         //VM_CheckEmptyString(prog,  altstr );
3552
3553         for( count = 0, pos = altstr ; *pos ; pos++ ) {
3554                 if( *pos == '\\' ) {
3555                         if( !*++pos ) {
3556                                 break;
3557                         }
3558                 } else if( *pos == '\'' ) {
3559                         count++;
3560                 }
3561         }
3562
3563         PRVM_G_FLOAT( OFS_RETURN ) = (prvm_vec_t) (count / 2);
3564 }
3565
3566 /*
3567 ========================
3568 VM_altstr_prepare
3569
3570 string altstr_prepare(string)
3571 ========================
3572 */
3573 void VM_altstr_prepare(prvm_prog_t *prog)
3574 {
3575         const char *instr, *in;
3576         char outstr[VM_STRINGTEMP_LENGTH];
3577         size_t outpos;
3578
3579         VM_SAFEPARMCOUNT( 1, VM_altstr_prepare );
3580
3581         instr = PRVM_G_STRING( OFS_PARM0 );
3582
3583         for (in = instr, outpos = 0; *in && outpos < sizeof(outstr) - 1; ++in)
3584         {
3585                 if (*in == '\'' && outpos < sizeof(outstr) - 2)
3586                 {
3587                         outstr[outpos++] = '\\';
3588                         outstr[outpos++] = '\'';
3589                 }
3590                 else
3591                         outstr[outpos++] = *in;
3592         }
3593         outstr[outpos] = 0;
3594
3595         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString(prog,  outstr );
3596 }
3597
3598 /*
3599 ========================
3600 VM_altstr_get
3601
3602 string altstr_get(string, float)
3603 ========================
3604 */
3605 void VM_altstr_get(prvm_prog_t *prog)
3606 {
3607         const char *altstr, *pos;
3608         char *out;
3609         int count, size;
3610         char outstr[VM_STRINGTEMP_LENGTH];
3611
3612         VM_SAFEPARMCOUNT( 2, VM_altstr_get );
3613
3614         altstr = PRVM_G_STRING( OFS_PARM0 );
3615
3616         count = (int)PRVM_G_FLOAT( OFS_PARM1 );
3617         count = count * 2 + 1;
3618
3619         for( pos = altstr ; *pos && count ; pos++ )
3620                 if( *pos == '\\' ) {
3621                         if( !*++pos )
3622                                 break;
3623                 } else if( *pos == '\'' )
3624                         count--;
3625
3626         if( !*pos ) {
3627                 PRVM_G_INT( OFS_RETURN ) = 0;
3628                 return;
3629         }
3630
3631         for( out = outstr, size = sizeof(outstr) - 1 ; size && *pos ; size--, pos++, out++ )
3632                 if( *pos == '\\' ) {
3633                         if( !*++pos )
3634                                 break;
3635                         *out = *pos;
3636                         size--;
3637                 } else if( *pos == '\'' )
3638                         break;
3639                 else
3640                         *out = *pos;
3641
3642         *out = 0;
3643         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString(prog,  outstr );
3644 }
3645
3646 /*
3647 ========================
3648 VM_altstr_set
3649
3650 string altstr_set(string altstr, float num, string set)
3651 ========================
3652 */
3653 void VM_altstr_set(prvm_prog_t *prog)
3654 {
3655     int num;
3656         const char *altstr, *str;
3657         const char *in;
3658         char *out;
3659         char outstr[VM_STRINGTEMP_LENGTH];
3660
3661         VM_SAFEPARMCOUNT( 3, VM_altstr_set );
3662
3663         altstr = PRVM_G_STRING( OFS_PARM0 );
3664
3665         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3666
3667         str = PRVM_G_STRING( OFS_PARM2 );
3668
3669         out = outstr;
3670         for( num = num * 2 + 1, in = altstr; *in && num; *out++ = *in++ )
3671                 if( *in == '\\' ) {
3672                         if( !*++in ) {
3673                                 break;
3674                         }
3675                 } else if( *in == '\'' ) {
3676                         num--;
3677                 }
3678
3679         // copy set in
3680         for( ; *str; *out++ = *str++ );
3681         // now jump over the old content
3682         for( ; *in ; in++ )
3683                 if( *in == '\'' || (*in == '\\' && !*++in) )
3684                         break;
3685
3686         strlcpy(out, in, outstr + sizeof(outstr) - out);
3687         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString(prog,  outstr );
3688 }
3689
3690 /*
3691 ========================
3692 VM_altstr_ins
3693 insert after num
3694 string  altstr_ins(string altstr, float num, string set)
3695 ========================
3696 */
3697 void VM_altstr_ins(prvm_prog_t *prog)
3698 {
3699         int num;
3700         const char *set;
3701         const char *in;
3702         char *out;
3703         char outstr[VM_STRINGTEMP_LENGTH];
3704
3705         VM_SAFEPARMCOUNT(3, VM_altstr_ins);
3706
3707         in = PRVM_G_STRING( OFS_PARM0 );
3708         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3709         set = PRVM_G_STRING( OFS_PARM2 );
3710
3711         out = outstr;
3712         for( num = num * 2 + 2 ; *in && num > 0 ; *out++ = *in++ )
3713                 if( *in == '\\' ) {
3714                         if( !*++in ) {
3715                                 break;
3716                         }
3717                 } else if( *in == '\'' ) {
3718                         num--;
3719                 }
3720
3721         *out++ = '\'';
3722         for( ; *set ; *out++ = *set++ );
3723         *out++ = '\'';
3724
3725         strlcpy(out, in, outstr + sizeof(outstr) - out);
3726         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString(prog,  outstr );
3727 }
3728
3729
3730 ////////////////////////////////////////
3731 // BufString functions
3732 ////////////////////////////////////////
3733 //[515]: string buffers support
3734
3735 static size_t stringbuffers_sortlength;
3736
3737 static void BufStr_Expand(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer, int strindex)
3738 {
3739         if (stringbuffer->max_strings <= strindex)
3740         {
3741                 char **oldstrings = stringbuffer->strings;
3742                 stringbuffer->max_strings = max(stringbuffer->max_strings * 2, 128);
3743                 while (stringbuffer->max_strings <= strindex)
3744                         stringbuffer->max_strings *= 2;
3745                 stringbuffer->strings = (char **) Mem_Alloc(prog->progs_mempool, stringbuffer->max_strings * sizeof(stringbuffer->strings[0]));
3746                 if (stringbuffer->num_strings > 0)
3747                         memcpy(stringbuffer->strings, oldstrings, stringbuffer->num_strings * sizeof(stringbuffer->strings[0]));
3748                 if (oldstrings)
3749                         Mem_Free(oldstrings);
3750         }
3751 }
3752
3753 static void BufStr_Shrink(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer)
3754 {
3755         // reduce num_strings if there are empty string slots at the end
3756         while (stringbuffer->num_strings > 0 && stringbuffer->strings[stringbuffer->num_strings - 1] == NULL)
3757                 stringbuffer->num_strings--;
3758
3759         // if empty, free the string pointer array
3760         if (stringbuffer->num_strings == 0)
3761         {
3762                 stringbuffer->max_strings = 0;
3763                 if (stringbuffer->strings)
3764                         Mem_Free(stringbuffer->strings);
3765                 stringbuffer->strings = NULL;
3766         }
3767 }
3768
3769 static int BufStr_SortStringsUP (const void *in1, const void *in2)
3770 {
3771         const char *a, *b;
3772         a = *((const char **) in1);
3773         b = *((const char **) in2);
3774         if(!a || !a[0]) return 1;
3775         if(!b || !b[0]) return -1;
3776         return strncmp(a, b, stringbuffers_sortlength);
3777 }
3778
3779 static int BufStr_SortStringsDOWN (const void *in1, const void *in2)
3780 {
3781         const char *a, *b;
3782         a = *((const char **) in1);
3783         b = *((const char **) in2);
3784         if(!a || !a[0]) return 1;
3785         if(!b || !b[0]) return -1;
3786         return strncmp(b, a, stringbuffers_sortlength);
3787 }
3788
3789 prvm_stringbuffer_t *BufStr_FindCreateReplace (prvm_prog_t *prog, int bufindex, int flags, const char *format)
3790 {
3791         prvm_stringbuffer_t *stringbuffer;
3792         int i;
3793
3794         if (bufindex < 0)
3795                 return NULL;
3796
3797         // find buffer with wanted index
3798         if (bufindex < (int)Mem_ExpandableArray_IndexRange(&prog->stringbuffersarray))
3799         {
3800                 if ( (stringbuffer = (prvm_stringbuffer_t*) Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, bufindex)) )
3801                 {
3802                         if (stringbuffer->flags & STRINGBUFFER_TEMP)
3803                                 stringbuffer->flags = flags; // created but has not been used yet
3804                         return stringbuffer;
3805                 }
3806                 return NULL;
3807         }
3808
3809         // allocate new buffer with wanted index
3810         while(1)
3811         {
3812                 stringbuffer = (prvm_stringbuffer_t *) Mem_ExpandableArray_AllocRecord(&prog->stringbuffersarray);
3813                 stringbuffer->flags = STRINGBUFFER_TEMP;
3814                 for (i = 0;stringbuffer != Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);i++);
3815                 if (i == bufindex)
3816                 {
3817                         stringbuffer->flags = flags; // mark as used
3818                         break;
3819                 }
3820         }
3821         return stringbuffer;
3822 }
3823
3824 void BufStr_Set(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer, int strindex, const char *str)
3825 {
3826         size_t  alloclen;
3827
3828         if (!stringbuffer || strindex < 0)
3829                 return;
3830
3831         BufStr_Expand(prog, stringbuffer, strindex);
3832         stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
3833         if (stringbuffer->strings[strindex])
3834                 Mem_Free(stringbuffer->strings[strindex]);
3835         stringbuffer->strings[strindex] = NULL;
3836
3837         if (str)
3838         {
3839                 // not the NULL string!
3840                 alloclen = strlen(str) + 1;
3841                 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
3842                 memcpy(stringbuffer->strings[strindex], str, alloclen);
3843         }
3844
3845         BufStr_Shrink(prog, stringbuffer);
3846 }
3847
3848 void BufStr_Del(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer)
3849 {
3850         int i;
3851         
3852         if (!stringbuffer)
3853                 return;
3854
3855         for (i = 0;i < stringbuffer->num_strings;i++)
3856                 if (stringbuffer->strings[i])
3857                         Mem_Free(stringbuffer->strings[i]);
3858         if (stringbuffer->strings)
3859                 Mem_Free(stringbuffer->strings);
3860         if(stringbuffer->origin)
3861                 PRVM_Free((char *)stringbuffer->origin);
3862         Mem_ExpandableArray_FreeRecord(&prog->stringbuffersarray, stringbuffer);
3863 }
3864
3865 void BufStr_Flush(prvm_prog_t *prog)
3866 {
3867         prvm_stringbuffer_t *stringbuffer;
3868         int i, numbuffers;
3869
3870         numbuffers = (int)Mem_ExpandableArray_IndexRange(&prog->stringbuffersarray);
3871         for (i = 0; i < numbuffers; i++)
3872                 if ( (stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i)) )
3873                         BufStr_Del(prog, stringbuffer);
3874         Mem_ExpandableArray_NewArray(&prog->stringbuffersarray, prog->progs_mempool, sizeof(prvm_stringbuffer_t), 64);
3875 }
3876
3877 /*
3878 ========================
3879 VM_buf_create
3880 creates new buffer, and returns it's index, returns -1 if failed
3881 float buf_create(prvm_prog_t *prog) = #460;
3882 float newbuf(string format, float flags) = #460;
3883 ========================
3884 */
3885
3886 void VM_buf_create (prvm_prog_t *prog)
3887 {
3888         prvm_stringbuffer_t *stringbuffer;
3889         int i;
3890
3891         VM_SAFEPARMCOUNTRANGE(0, 2, VM_buf_create);
3892
3893         // VorteX: optional parm1 (buffer format) is unfinished, to keep intact with future databuffers extension must be set to "string"
3894         if(prog->argc >= 1 && strcmp(PRVM_G_STRING(OFS_PARM0), "string"))
3895         {
3896                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3897                 return;
3898         }
3899         stringbuffer = (prvm_stringbuffer_t *) Mem_ExpandableArray_AllocRecord(&prog->stringbuffersarray);
3900         for (i = 0;stringbuffer != Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);i++);
3901         stringbuffer->origin = PRVM_AllocationOrigin(prog);
3902         // optional flags parm
3903         if (prog->argc >= 2)
3904                 stringbuffer->flags = (int)PRVM_G_FLOAT(OFS_PARM1) & STRINGBUFFER_QCFLAGS;
3905         PRVM_G_FLOAT(OFS_RETURN) = i;
3906 }
3907
3908
3909
3910 /*
3911 ========================
3912 VM_buf_del
3913 deletes buffer and all strings in it
3914 void buf_del(float bufhandle) = #461;
3915 ========================
3916 */
3917 void VM_buf_del (prvm_prog_t *prog)
3918 {
3919         prvm_stringbuffer_t *stringbuffer;
3920         VM_SAFEPARMCOUNT(1, VM_buf_del);
3921         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
3922         if (stringbuffer)
3923                 BufStr_Del(prog, stringbuffer);
3924         else
3925         {
3926                 VM_Warning(prog, "VM_buf_del: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
3927                 return;
3928         }
3929 }
3930
3931 /*
3932 ========================
3933 VM_buf_getsize
3934 how many strings are stored in buffer
3935 float buf_getsize(float bufhandle) = #462;
3936 ========================
3937 */
3938 void VM_buf_getsize (prvm_prog_t *prog)
3939 {
3940         prvm_stringbuffer_t *stringbuffer;
3941         VM_SAFEPARMCOUNT(1, VM_buf_getsize);
3942
3943         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
3944         if(!stringbuffer)
3945         {
3946                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3947                 VM_Warning(prog, "VM_buf_getsize: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
3948                 return;
3949         }
3950         else
3951                 PRVM_G_FLOAT(OFS_RETURN) = stringbuffer->num_strings;
3952 }
3953
3954 /*
3955 ========================
3956 VM_buf_copy
3957 copy all content from one buffer to another, make sure it exists
3958 void buf_copy(float bufhandle_from, float bufhandle_to) = #463;
3959 ========================
3960 */
3961 void VM_buf_copy (prvm_prog_t *prog)
3962 {
3963         prvm_stringbuffer_t *srcstringbuffer, *dststringbuffer;
3964         int i;
3965         VM_SAFEPARMCOUNT(2, VM_buf_copy);
3966
3967         srcstringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
3968         if(!srcstringbuffer)
3969         {
3970                 VM_Warning(prog, "VM_buf_copy: invalid source buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
3971                 return;
3972         }
3973         i = (int)PRVM_G_FLOAT(OFS_PARM1);
3974         if(i == (int)PRVM_G_FLOAT(OFS_PARM0))
3975         {
3976                 VM_Warning(prog, "VM_buf_copy: source == destination (%i) in %s\n", i, prog->name);
3977                 return;
3978         }
3979         dststringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
3980         if(!dststringbuffer)
3981         {
3982                 VM_Warning(prog, "VM_buf_copy: invalid destination buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
3983                 return;
3984         }
3985
3986         for (i = 0;i < dststringbuffer->num_strings;i++)
3987                 if (dststringbuffer->strings[i])
3988                         Mem_Free(dststringbuffer->strings[i]);
3989         if (dststringbuffer->strings)
3990                 Mem_Free(dststringbuffer->strings);
3991         *dststringbuffer = *srcstringbuffer;
3992         if (dststringbuffer->max_strings)
3993                 dststringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(dststringbuffer->strings[0]) * dststringbuffer->max_strings);
3994
3995         for (i = 0;i < dststringbuffer->num_strings;i++)
3996         {
3997                 if (srcstringbuffer->strings[i])
3998                 {
3999                         size_t stringlen;
4000                         stringlen = strlen(srcstringbuffer->strings[i]) + 1;
4001                         dststringbuffer->strings[i] = (char *)Mem_Alloc(prog->progs_mempool, stringlen);
4002                         memcpy(dststringbuffer->strings[i], srcstringbuffer->strings[i], stringlen);
4003                 }
4004         }
4005 }
4006
4007 /*
4008 ========================
4009 VM_buf_sort
4010 sort buffer by beginnings of strings (cmplength defaults it's length)
4011 "backward == true" means that sorting goes upside-down
4012 void buf_sort(float bufhandle, float cmplength, float backward) = #464;
4013 ========================
4014 */
4015 void VM_buf_sort (prvm_prog_t *prog)
4016 {
4017         prvm_stringbuffer_t *stringbuffer;
4018         VM_SAFEPARMCOUNT(3, VM_buf_sort);
4019
4020         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4021         if(!stringbuffer)
4022         {
4023                 VM_Warning(prog, "VM_buf_sort: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4024                 return;
4025         }
4026         if(stringbuffer->num_strings <= 0)
4027         {
4028                 VM_Warning(prog, "VM_buf_sort: tried to sort empty buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4029                 return;
4030         }
4031         stringbuffers_sortlength = (int)PRVM_G_FLOAT(OFS_PARM1);
4032         if(stringbuffers_sortlength <= 0)
4033                 stringbuffers_sortlength = 0x7FFFFFFF;
4034
4035         if(!PRVM_G_FLOAT(OFS_PARM2))
4036                 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsUP);
4037         else
4038                 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsDOWN);
4039
4040         BufStr_Shrink(prog, stringbuffer);
4041 }
4042
4043 /*
4044 ========================
4045 VM_buf_implode
4046 concantenates all buffer string into one with "glue" separator and returns it as tempstring
4047 string buf_implode(float bufhandle, string glue) = #465;
4048 ========================
4049 */
4050 void VM_buf_implode (prvm_prog_t *prog)
4051 {
4052         prvm_stringbuffer_t *stringbuffer;
4053         char                    k[VM_STRINGTEMP_LENGTH];
4054         const char              *sep;
4055         int                             i;
4056         size_t                  l;
4057         VM_SAFEPARMCOUNT(2, VM_buf_implode);
4058
4059         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4060         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4061         if(!stringbuffer)
4062         {
4063                 VM_Warning(prog, "VM_buf_implode: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4064                 return;
4065         }
4066         if(!stringbuffer->num_strings)
4067                 return;
4068         sep = PRVM_G_STRING(OFS_PARM1);
4069         k[0] = 0;
4070         for(l = i = 0;i < stringbuffer->num_strings;i++)
4071         {
4072                 if(stringbuffer->strings[i])
4073                 {
4074                         l += (i > 0 ? strlen(sep) : 0) + strlen(stringbuffer->strings[i]);
4075                         if (l >= sizeof(k) - 1)
4076                                 break;
4077                         strlcat(k, sep, sizeof(k));
4078                         strlcat(k, stringbuffer->strings[i], sizeof(k));
4079                 }
4080         }
4081         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, k);
4082 }
4083
4084 /*
4085 ========================
4086 VM_bufstr_get
4087 get a string from buffer, returns tempstring, dont str_unzone it!
4088 string bufstr_get(float bufhandle, float string_index) = #465;
4089 ========================
4090 */
4091 void VM_bufstr_get (prvm_prog_t *prog)
4092 {
4093         prvm_stringbuffer_t *stringbuffer;
4094         int                             strindex;
4095         VM_SAFEPARMCOUNT(2, VM_bufstr_get);
4096
4097         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4098         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4099         if(!stringbuffer)
4100         {
4101                 VM_Warning(prog, "VM_bufstr_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4102                 return;
4103         }
4104         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4105         if (strindex < 0)
4106         {
4107                 // VM_Warning(prog, "VM_bufstr_get: invalid string index %i used in %s\n", strindex, prog->name);
4108                 return;
4109         }
4110         if (strindex < stringbuffer->num_strings && stringbuffer->strings[strindex])
4111                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, stringbuffer->strings[strindex]);
4112 }
4113
4114 /*
4115 ========================
4116 VM_bufstr_set
4117 copies a string into selected slot of buffer
4118 void bufstr_set(float bufhandle, float string_index, string str) = #466;
4119 ========================
4120 */
4121 void VM_bufstr_set (prvm_prog_t *prog)
4122 {
4123         int                             strindex;
4124         prvm_stringbuffer_t *stringbuffer;
4125         const char              *news;
4126
4127         VM_SAFEPARMCOUNT(3, VM_bufstr_set);
4128
4129         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4130         if(!stringbuffer)
4131         {
4132                 VM_Warning(prog, "VM_bufstr_set: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4133                 return;
4134         }
4135         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4136         if(strindex < 0 || strindex >= 1000000) // huge number of strings
4137         {
4138                 VM_Warning(prog, "VM_bufstr_set: invalid string index %i used in %s\n", strindex, prog->name);
4139                 return;
4140         }
4141
4142         news = PRVM_G_STRING(OFS_PARM2);
4143         BufStr_Set(prog, stringbuffer, strindex, news);
4144 }
4145
4146 /*
4147 ========================
4148 VM_bufstr_add
4149 adds string to buffer in first free slot and returns its index
4150 "order == true" means that string will be added after last "full" slot
4151 float bufstr_add(float bufhandle, string str, float order) = #467;
4152 ========================
4153 */
4154 void VM_bufstr_add (prvm_prog_t *prog)
4155 {
4156         int                             order, strindex;
4157         prvm_stringbuffer_t *stringbuffer;
4158         const char              *string;
4159         size_t                  alloclen;
4160
4161         VM_SAFEPARMCOUNT(3, VM_bufstr_add);
4162
4163         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4164         PRVM_G_FLOAT(OFS_RETURN) = -1;
4165         if(!stringbuffer)
4166         {
4167                 VM_Warning(prog, "VM_bufstr_add: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4168                 return;
4169         }
4170         if(!PRVM_G_INT(OFS_PARM1)) // NULL string
4171         {
4172                 VM_Warning(prog, "VM_bufstr_add: can not add an empty string to buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4173                 return;
4174         }
4175         string = PRVM_G_STRING(OFS_PARM1);
4176         order = (int)PRVM_G_FLOAT(OFS_PARM2);
4177         if(order)
4178                 strindex = stringbuffer->num_strings;
4179         else
4180                 for (strindex = 0;strindex < stringbuffer->num_strings;strindex++)
4181                         if (stringbuffer->strings[strindex] == NULL)
4182                                 break;
4183
4184         BufStr_Expand(prog, stringbuffer, strindex);
4185
4186         stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4187         alloclen = strlen(string) + 1;
4188         stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4189         memcpy(stringbuffer->strings[strindex], string, alloclen);
4190
4191         PRVM_G_FLOAT(OFS_RETURN) = strindex;
4192 }
4193
4194 /*
4195 ========================
4196 VM_bufstr_free
4197 delete string from buffer
4198 void bufstr_free(float bufhandle, float string_index) = #468;
4199 ========================
4200 */
4201 void VM_bufstr_free (prvm_prog_t *prog)
4202 {
4203         int                             i;
4204         prvm_stringbuffer_t     *stringbuffer;
4205         VM_SAFEPARMCOUNT(2, VM_bufstr_free);
4206
4207         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4208         if(!stringbuffer)
4209         {
4210                 VM_Warning(prog, "VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4211                 return;
4212         }
4213         i = (int)PRVM_G_FLOAT(OFS_PARM1);
4214         if(i < 0)
4215         {
4216                 VM_Warning(prog, "VM_bufstr_free: invalid string index %i used in %s\n", i, prog->name);
4217                 return;
4218         }
4219
4220         if (i < stringbuffer->num_strings)
4221         {
4222                 if(stringbuffer->strings[i])
4223                         Mem_Free(stringbuffer->strings[i]);
4224                 stringbuffer->strings[i] = NULL;
4225         }
4226
4227         BufStr_Shrink(prog, stringbuffer);
4228 }
4229
4230 /*
4231 ========================
4232 VM_buf_loadfile
4233 load a file into string buffer, return 0 or 1
4234 float buf_loadfile(string filename, float bufhandle) = #535;
4235 ========================
4236 */
4237 void VM_buf_loadfile(prvm_prog_t *prog)
4238 {
4239         size_t alloclen;
4240         prvm_stringbuffer_t *stringbuffer;
4241         char string[VM_STRINGTEMP_LENGTH];
4242         int strindex, c, end;
4243         const char *filename;
4244         char vabuf[1024];
4245         qfile_t *file;
4246
4247         VM_SAFEPARMCOUNT(2, VM_buf_loadfile);
4248
4249         // get file
4250         filename = PRVM_G_STRING(OFS_PARM0);
4251         file = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "data/%s", filename), false);
4252         if (file == NULL)
4253                 file = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "%s", filename), false);
4254         if (file == NULL)
4255         {
4256                 if (developer_extra.integer)
4257                         VM_Warning(prog, "VM_buf_loadfile: failed to open file %s in %s\n", filename, prog->name);
4258                 PRVM_G_FLOAT(OFS_RETURN) = 0;
4259                 return;
4260         }
4261
4262         // get string buffer
4263         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM1));
4264         if(!stringbuffer)
4265         {
4266                 VM_Warning(prog, "VM_buf_loadfile: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
4267                 PRVM_G_FLOAT(OFS_RETURN) = 0;
4268                 return;
4269         }
4270
4271         // read file (append to the end of buffer)
4272         strindex = stringbuffer->num_strings;
4273         while(1)
4274         {
4275                 // read line
4276                 end = 0;
4277                 for (;;)
4278                 {
4279                         c = FS_Getc(file);
4280                         if (c == '\r' || c == '\n' || c < 0)
4281                                 break;
4282                         if (end < VM_STRINGTEMP_LENGTH - 1)
4283                                 string[end++] = c;
4284                 }
4285                 string[end] = 0;
4286                 // remove \n following \r
4287                 if (c == '\r')
4288                 {
4289                         c = FS_Getc(file);
4290                         if (c != '\n')
4291                                 FS_UnGetc(file, (unsigned char)c);
4292                 }
4293                 // add and continue
4294                 if (c >= 0 || end)
4295                 {
4296                         BufStr_Expand(prog, stringbuffer, strindex);
4297                         stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4298                         alloclen = strlen(string) + 1;
4299                         stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4300                         memcpy(stringbuffer->strings[strindex], string, alloclen);
4301                         strindex = stringbuffer->num_strings;
4302                 }
4303                 else
4304                         break;
4305         }
4306
4307         // close file
4308         FS_Close(file);
4309         PRVM_G_FLOAT(OFS_RETURN) = 1;
4310 }
4311
4312 /*
4313 ========================
4314 VM_buf_writefile
4315 writes stringbuffer to a file, returns 0 or 1
4316 float buf_writefile(float filehandle, float bufhandle, [, float startpos, float numstrings]) = #468;
4317 ========================
4318 */
4319
4320 void VM_buf_writefile(prvm_prog_t *prog)
4321 {
4322         int filenum, strindex, strnum, strlength;
4323         prvm_stringbuffer_t *stringbuffer;
4324
4325         VM_SAFEPARMCOUNTRANGE(2, 4, VM_buf_writefile);
4326
4327         // get file
4328         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
4329         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
4330         {
4331                 VM_Warning(prog, "VM_buf_writefile: invalid file handle %i used in %s\n", filenum, prog->name);
4332                 return;
4333         }
4334         if (prog->openfiles[filenum] == NULL)
4335         {
4336                 VM_Warning(prog, "VM_buf_writefile: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
4337                 return;
4338         }
4339         
4340         // get string buffer
4341         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM1));
4342         if(!stringbuffer)
4343         {
4344                 VM_Warning(prog, "VM_buf_writefile: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
4345                 PRVM_G_FLOAT(OFS_RETURN) = 0;
4346                 return;
4347         }
4348
4349         // get start and end parms
4350         if (prog->argc > 3)
4351         {
4352                 strindex = (int)PRVM_G_FLOAT(OFS_PARM2);
4353                 strnum = (int)PRVM_G_FLOAT(OFS_PARM3);
4354         }
4355         else if (prog->argc > 2)
4356         {
4357                 strindex = (int)PRVM_G_FLOAT(OFS_PARM2);
4358                 strnum = stringbuffer->num_strings - strindex;
4359         }
4360         else
4361         {
4362                 strindex = 0;
4363                 strnum = stringbuffer->num_strings;
4364         }
4365         if (strindex < 0 || strindex >= stringbuffer->num_strings)
4366         {
4367                 VM_Warning(prog, "VM_buf_writefile: wrong start string index %i used in %s\n", strindex, prog->name);
4368                 PRVM_G_FLOAT(OFS_RETURN) = 0;
4369                 return;
4370         }
4371         if (strnum < 0)
4372         {
4373                 VM_Warning(prog, "VM_buf_writefile: wrong strings count %i used in %s\n", strnum, prog->name);
4374                 PRVM_G_FLOAT(OFS_RETURN) = 0;
4375                 return;
4376         }
4377
4378         // write
4379         while(strindex < stringbuffer->num_strings && strnum)
4380         {
4381                 if (stringbuffer->strings[strindex])
4382                 {
4383                         if ((strlength = (int)strlen(stringbuffer->strings[strindex])))
4384                                 FS_Write(prog->openfiles[filenum], stringbuffer->strings[strindex], strlength);
4385                         FS_Write(prog->openfiles[filenum], "\n", 1);
4386                 }
4387                 strindex++;
4388                 strnum--;
4389         }
4390
4391         PRVM_G_FLOAT(OFS_RETURN) = 1;
4392 }
4393
4394 #define MATCH_AUTO     0
4395 #define MATCH_WHOLE    1
4396 #define MATCH_LEFT     2
4397 #define MATCH_RIGHT    3
4398 #define MATCH_MIDDLE   4
4399 #define MATCH_PATTERN  5
4400
4401 static const char *detect_match_rule(char *pattern, int *matchrule)
4402 {
4403         char *ppos, *qpos;
4404         int patternlength;
4405
4406         patternlength = (int)strlen(pattern);
4407         ppos = strchr(pattern, '*');
4408         qpos = strchr(pattern, '?');
4409         // has ? - pattern
4410         if (qpos) 
4411         {
4412                 *matchrule = MATCH_PATTERN;
4413                 return pattern;
4414         }
4415         // has * - left, mid, right or pattern
4416         if (ppos)
4417         {
4418                 // starts with * - may be right/mid or pattern
4419                 if ((ppos - pattern) == 0)
4420                 {
4421                         ppos = strchr(pattern+1, '*');
4422                         // *something 
4423                         if (!ppos) 
4424                         {
4425                                 *matchrule = MATCH_RIGHT;
4426                                 return pattern+1;
4427                         }
4428                         // *something*
4429                         if ((ppos - pattern) == patternlength)
4430                         {
4431                                 *matchrule = MATCH_MIDDLE;
4432                                 *ppos = 0;
4433                                 return pattern+1;
4434                         }
4435                         // *som*thing
4436                         *matchrule = MATCH_PATTERN;
4437                         return pattern;
4438                 }
4439                 // end with * - left
4440                 if ((ppos - pattern) == patternlength)
4441                 {
4442                         *matchrule = MATCH_LEFT;
4443                         *ppos = 0;
4444                         return pattern;
4445                 }
4446                 // som*thing
4447                 *matchrule = MATCH_PATTERN;
4448                 return pattern;
4449         }
4450         // have no wildcards - whole string
4451         *matchrule = MATCH_WHOLE;
4452         return pattern;
4453 }
4454
4455 // todo: support UTF8
4456 static qbool match_rule(const char *string, int max_string, const char *pattern, int patternlength, int rule)
4457 {