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