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