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