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