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