]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - prvm_cmds.c
argh, sorry for broken copypasta
[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
21 // LordHavoc: changed this to NOT use a return statement, so that it can be used in functions that must return a value
22 void VM_Warning(prvm_prog_t *prog, const char *fmt, ...)
23 {
24         va_list argptr;
25         char msg[MAX_INPUTLINE];
26         static double recursive = -1;
27
28         va_start(argptr,fmt);
29         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
30         va_end(argptr);
31
32         Con_Print(msg);
33
34         // TODO: either add a cvar/cmd to control the state dumping or replace some of the calls with Con_Printf [9/13/2006 Black]
35         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
36         {
37                 recursive = realtime;
38                 PRVM_PrintState(prog);
39                 recursive = -1;
40         }
41 }
42
43
44 //============================================================================
45 // Common
46
47 // TODO DONE: move vm_files and vm_fssearchlist to prvm_prog_t struct
48 // TODO: move vm_files and vm_fssearchlist back [9/13/2006 Black]
49 // TODO: (move vm_files and vm_fssearchlist to prvm_prog_t struct again) [2007-01-23 LordHavoc]
50 // TODO: will this war ever end? [2007-01-23 LordHavoc]
51
52 void VM_CheckEmptyString(prvm_prog_t *prog, const char *s)
53 {
54         if (ISWHITESPACE(s[0]))
55                 prog->error_cmd("%s: Bad string", prog->name);
56 }
57
58 void VM_GenerateFrameGroupBlend(prvm_prog_t *prog, framegroupblend_t *framegroupblend, const prvm_edict_t *ed)
59 {
60         // self.frame is the interpolation target (new frame)
61         // self.frame1time is the animation base time for the interpolation target
62         // self.frame2 is the interpolation start (previous frame)
63         // self.frame2time is the animation base time for the interpolation start
64         // self.lerpfrac is the interpolation strength for self.frame2
65         // self.lerpfrac3 is the interpolation strength for self.frame3
66         // self.lerpfrac4 is the interpolation strength for self.frame4
67         // pitch angle on a player model where the animator set up 5 sets of
68         // animations and the csqc simply lerps between sets)
69         framegroupblend[0].frame = (int) PRVM_gameedictfloat(ed, frame     );
70         framegroupblend[1].frame = (int) PRVM_gameedictfloat(ed, frame2    );
71         framegroupblend[2].frame = (int) PRVM_gameedictfloat(ed, frame3    );
72         framegroupblend[3].frame = (int) PRVM_gameedictfloat(ed, frame4    );
73         framegroupblend[0].start =       PRVM_gameedictfloat(ed, frame1time);
74         framegroupblend[1].start =       PRVM_gameedictfloat(ed, frame2time);
75         framegroupblend[2].start =       PRVM_gameedictfloat(ed, frame3time);
76         framegroupblend[3].start =       PRVM_gameedictfloat(ed, frame4time);
77         framegroupblend[1].lerp  =       PRVM_gameedictfloat(ed, lerpfrac  );
78         framegroupblend[2].lerp  =       PRVM_gameedictfloat(ed, lerpfrac3 );
79         framegroupblend[3].lerp  =       PRVM_gameedictfloat(ed, lerpfrac4 );
80         // assume that the (missing) lerpfrac1 is whatever remains after lerpfrac2+lerpfrac3+lerpfrac4 are summed
81         framegroupblend[0].lerp = 1 - framegroupblend[1].lerp - framegroupblend[2].lerp - framegroupblend[3].lerp;
82 }
83
84 // LordHavoc: quite tempting to break apart this function to reuse the
85 //            duplicated code, but I suspect it is better for performance
86 //            this way
87 void VM_FrameBlendFromFrameGroupBlend(frameblend_t *frameblend, const framegroupblend_t *framegroupblend, const dp_model_t *model)
88 {
89         int sub2, numframes, f, i, k;
90         int isfirstframegroup = true;
91         int nolerp;
92         double sublerp, lerp, d;
93         const animscene_t *scene;
94         const framegroupblend_t *g;
95         frameblend_t *blend = frameblend;
96
97         memset(blend, 0, MAX_FRAMEBLENDS * sizeof(*blend));
98
99         if (!model || !model->surfmesh.isanimated)
100         {
101                 blend[0].lerp = 1;
102                 return;
103         }
104
105         nolerp = (model->type == mod_sprite) ? !r_lerpsprites.integer : !r_lerpmodels.integer;
106         numframes = model->numframes;
107         for (k = 0, g = framegroupblend;k < MAX_FRAMEGROUPBLENDS;k++, g++)
108         {
109                 f = g->frame;
110                 if ((unsigned int)f >= (unsigned int)numframes)
111                 {
112                         if (developer_extra.integer)
113                                 Con_DPrintf("VM_FrameBlendFromFrameGroupBlend: no such frame %d in model %s\n", f, model->name);
114                         f = 0;
115                 }
116                 d = lerp = g->lerp;
117                 if (lerp <= 0)
118                         continue;
119                 if (nolerp)
120                 {
121                         if (isfirstframegroup)
122                         {
123                                 d = lerp = 1;
124                                 isfirstframegroup = false;
125                         }
126                         else
127                                 continue;
128                 }
129                 if (model->animscenes)
130                 {
131                         scene = model->animscenes + f;
132                         f = scene->firstframe;
133                         if (scene->framecount > 1)
134                         {
135                                 // this code path is only used on .zym models and torches
136                                 sublerp = scene->framerate * (cl.time - g->start);
137                                 f = (int) floor(sublerp);
138                                 sublerp -= f;
139                                 sub2 = f + 1;
140                                 if (sublerp < (1.0 / 65536.0f))
141                                         sublerp = 0;
142                                 if (sublerp > (65535.0f / 65536.0f))
143                                         sublerp = 1;
144                                 if (nolerp)
145                                         sublerp = 0;
146                                 if (scene->loop)
147                                 {
148                                         f = (f % scene->framecount);
149                                         sub2 = (sub2 % scene->framecount);
150                                 }
151                                 f = bound(0, f, (scene->framecount - 1)) + scene->firstframe;
152                                 sub2 = bound(0, sub2, (scene->framecount - 1)) + scene->firstframe;
153                                 d = sublerp * lerp;
154                                 // two framelerps produced from one animation
155                                 if (d > 0)
156                                 {
157                                         for (i = 0;i < MAX_FRAMEBLENDS;i++)
158                                         {
159                                                 if (blend[i].lerp <= 0 || blend[i].subframe == sub2)
160                                                 {
161                                                         blend[i].subframe = sub2;
162                                                         blend[i].lerp += d;
163                                                         break;
164                                                 }
165                                         }
166                                 }
167                                 d = (1 - sublerp) * lerp;
168                         }
169                 }
170                 if (d > 0)
171                 {
172                         for (i = 0;i < MAX_FRAMEBLENDS;i++)
173                         {
174                                 if (blend[i].lerp <= 0 || blend[i].subframe == f)
175                                 {
176                                         blend[i].subframe = f;
177                                         blend[i].lerp += d;
178                                         break;
179                                 }
180                         }
181                 }
182         }
183 }
184
185 void VM_UpdateEdictSkeleton(prvm_prog_t *prog, prvm_edict_t *ed, const dp_model_t *edmodel, const frameblend_t *frameblend)
186 {
187         if (ed->priv.server->skeleton.model != edmodel)
188         {
189                 VM_RemoveEdictSkeleton(prog, ed);
190                 ed->priv.server->skeleton.model = edmodel;
191         }
192         if (!ed->priv.server->skeleton.model || !ed->priv.server->skeleton.model->num_bones)
193         {
194                 if(ed->priv.server->skeleton.relativetransforms)
195                         Mem_Free(ed->priv.server->skeleton.relativetransforms);
196                 ed->priv.server->skeleton.relativetransforms = NULL;
197                 return;
198         }
199
200         {
201                 int skeletonindex = -1;
202                 skeleton_t *skeleton;
203                 skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
204                 if (skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones)
205                 {
206                         // custom skeleton controlled by the game (FTE_CSQC_SKELETONOBJECTS)
207                         if (!ed->priv.server->skeleton.relativetransforms)
208                                 ed->priv.server->skeleton.relativetransforms = (matrix4x4_t *)Mem_Alloc(prog->progs_mempool, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
209                         memcpy(ed->priv.server->skeleton.relativetransforms, skeleton->relativetransforms, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
210                 }
211                 else
212                 {
213                         if(ed->priv.server->skeleton.relativetransforms)
214                                 Mem_Free(ed->priv.server->skeleton.relativetransforms);
215                         ed->priv.server->skeleton.relativetransforms = NULL;
216                 }
217         }
218 }
219
220 void VM_RemoveEdictSkeleton(prvm_prog_t *prog, prvm_edict_t *ed)
221 {
222         if (ed->priv.server->skeleton.relativetransforms)
223                 Mem_Free(ed->priv.server->skeleton.relativetransforms);
224         memset(&ed->priv.server->skeleton, 0, sizeof(ed->priv.server->skeleton));
225 }
226
227
228
229
230 //============================================================================
231 //BUILT-IN FUNCTIONS
232
233 void VM_VarString(prvm_prog_t *prog, int first, char *out, int outlength)
234 {
235         int i;
236         const char *s;
237         char *outend;
238
239         outend = out + outlength - 1;
240         for (i = first;i < prog->argc && out < outend;i++)
241         {
242                 s = PRVM_G_STRING((OFS_PARM0+i*3));
243                 while (out < outend && *s)
244                         *out++ = *s++;
245         }
246         *out++ = 0;
247 }
248
249 /*
250 =================
251 VM_checkextension
252
253 returns true if the extension is supported by the server
254
255 checkextension(extensionname)
256 =================
257 */
258
259 // kind of helper function
260 static qboolean checkextension(prvm_prog_t *prog, const char *name)
261 {
262         int len;
263         const char *e, *start;
264         len = (int)strlen(name);
265
266         for (e = prog->extensionstring;*e;e++)
267         {
268                 while (*e == ' ')
269                         e++;
270                 if (!*e)
271                         break;
272                 start = e;
273                 while (*e && *e != ' ')
274                         e++;
275                 if ((e - start) == len && !strncasecmp(start, name, len))
276                 {
277                         // special sheck for ODE
278                         if (!strncasecmp("DP_PHYSICS_ODE", name, 14))
279                         {
280 #ifdef USEODE
281                                 return ode_dll ? true : false;
282 #else
283                                 return false;
284 #endif
285                         }
286
287                         // special sheck for d0_blind_id
288                         if (!strcasecmp("DP_CRYPTO", name))
289                                 return Crypto_Available();
290                         if (!strcasecmp("DP_QC_DIGEST_SHA256", name))
291                                 return Crypto_Available();
292
293                         return true;
294                 }
295         }
296         return false;
297 }
298
299 void VM_checkextension(prvm_prog_t *prog)
300 {
301         VM_SAFEPARMCOUNT(1,VM_checkextension);
302
303         PRVM_G_FLOAT(OFS_RETURN) = checkextension(prog, PRVM_G_STRING(OFS_PARM0));
304 }
305
306 /*
307 =================
308 VM_error
309
310 This is a TERMINAL error, which will kill off the entire prog.
311 Dumps self.
312
313 error(value)
314 =================
315 */
316 void VM_error(prvm_prog_t *prog)
317 {
318         prvm_edict_t    *ed;
319         char string[VM_STRINGTEMP_LENGTH];
320
321         VM_VarString(prog, 0, string, sizeof(string));
322         Con_Printf("======%s ERROR in %s:\n%s\n", prog->name, PRVM_GetString(prog, prog->xfunction->s_name), string);
323         ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
324         PRVM_ED_Print(prog, ed, NULL);
325
326         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);
327 }
328
329 /*
330 =================
331 VM_objerror
332
333 Dumps out self, then an error message.  The program is aborted and self is
334 removed, but the level can continue.
335
336 objerror(value)
337 =================
338 */
339 void VM_objerror(prvm_prog_t *prog)
340 {
341         prvm_edict_t    *ed;
342         char string[VM_STRINGTEMP_LENGTH];
343
344         VM_VarString(prog, 0, string, sizeof(string));
345         Con_Printf("======OBJECT ERROR======\n"); // , prog->name, PRVM_GetString(prog->xfunction->s_name), string); // or include them? FIXME
346         ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
347         PRVM_ED_Print(prog, ed, NULL);
348         PRVM_ED_Free (prog, ed);
349         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);
350 }
351
352 /*
353 =================
354 VM_print
355
356 print to console
357
358 print(...[string])
359 =================
360 */
361 void VM_print(prvm_prog_t *prog)
362 {
363         char string[VM_STRINGTEMP_LENGTH];
364
365         VM_VarString(prog, 0, string, sizeof(string));
366         Con_Print(string);
367 }
368
369 /*
370 =================
371 VM_bprint
372
373 broadcast print to everyone on server
374
375 bprint(...[string])
376 =================
377 */
378 void VM_bprint(prvm_prog_t *prog)
379 {
380         char string[VM_STRINGTEMP_LENGTH];
381
382         if(!sv.active)
383         {
384                 VM_Warning(prog, "VM_bprint: game is not server(%s) !\n", prog->name);
385                 return;
386         }
387
388         VM_VarString(prog, 0, string, sizeof(string));
389         SV_BroadcastPrint(string);
390 }
391
392 /*
393 =================
394 VM_sprint (menu & client but only if server.active == true)
395
396 single print to a specific client
397
398 sprint(float clientnum,...[string])
399 =================
400 */
401 void VM_sprint(prvm_prog_t *prog)
402 {
403         client_t        *client;
404         int                     clientnum;
405         char string[VM_STRINGTEMP_LENGTH];
406
407         VM_SAFEPARMCOUNTRANGE(1, 8, VM_sprint);
408
409         //find client for this entity
410         clientnum = (int)PRVM_G_FLOAT(OFS_PARM0);
411         if (!sv.active  || clientnum < 0 || clientnum >= svs.maxclients || !svs.clients[clientnum].active)
412         {
413                 VM_Warning(prog, "VM_sprint: %s: invalid client or server is not active !\n", prog->name);
414                 return;
415         }
416
417         client = svs.clients + clientnum;
418         if (!client->netconnection)
419                 return;
420
421         VM_VarString(prog, 1, string, sizeof(string));
422         MSG_WriteChar(&client->netconnection->message,svc_print);
423         MSG_WriteString(&client->netconnection->message, string);
424 }
425
426 /*
427 =================
428 VM_centerprint
429
430 single print to the screen
431
432 centerprint(value)
433 =================
434 */
435 void VM_centerprint(prvm_prog_t *prog)
436 {
437         char string[VM_STRINGTEMP_LENGTH];
438
439         VM_SAFEPARMCOUNTRANGE(1, 8, VM_centerprint);
440         VM_VarString(prog, 0, string, sizeof(string));
441         SCR_CenterPrint(string);
442 }
443
444 /*
445 =================
446 VM_normalize
447
448 vector normalize(vector)
449 =================
450 */
451 void VM_normalize(prvm_prog_t *prog)
452 {
453         float   *value1;
454         vec3_t  newvalue;
455         double  f;
456
457         VM_SAFEPARMCOUNT(1,VM_normalize);
458
459         value1 = PRVM_G_VECTOR(OFS_PARM0);
460
461         f = VectorLength2(value1);
462         if (f)
463         {
464                 f = 1.0 / sqrt(f);
465                 VectorScale(value1, f, newvalue);
466         }
467         else
468                 VectorClear(newvalue);
469
470         VectorCopy (newvalue, PRVM_G_VECTOR(OFS_RETURN));
471 }
472
473 /*
474 =================
475 VM_vlen
476
477 scalar vlen(vector)
478 =================
479 */
480 void VM_vlen(prvm_prog_t *prog)
481 {
482         VM_SAFEPARMCOUNT(1,VM_vlen);
483         PRVM_G_FLOAT(OFS_RETURN) = VectorLength(PRVM_G_VECTOR(OFS_PARM0));
484 }
485
486 /*
487 =================
488 VM_vectoyaw
489
490 float vectoyaw(vector)
491 =================
492 */
493 void VM_vectoyaw(prvm_prog_t *prog)
494 {
495         float   *value1;
496         float   yaw;
497
498         VM_SAFEPARMCOUNT(1,VM_vectoyaw);
499
500         value1 = PRVM_G_VECTOR(OFS_PARM0);
501
502         if (value1[1] == 0 && value1[0] == 0)
503                 yaw = 0;
504         else
505         {
506                 yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI);
507                 if (yaw < 0)
508                         yaw += 360;
509         }
510
511         PRVM_G_FLOAT(OFS_RETURN) = yaw;
512 }
513
514
515 /*
516 =================
517 VM_vectoangles
518
519 vector vectoangles(vector[, vector])
520 =================
521 */
522 void VM_vectoangles(prvm_prog_t *prog)
523 {
524         VM_SAFEPARMCOUNTRANGE(1, 2,VM_vectoangles);
525
526         AnglesFromVectors(PRVM_G_VECTOR(OFS_RETURN), PRVM_G_VECTOR(OFS_PARM0), prog->argc >= 2 ? PRVM_G_VECTOR(OFS_PARM1) : NULL, true);
527 }
528
529 /*
530 =================
531 VM_random
532
533 Returns a number from 0<= num < 1
534
535 float random()
536 =================
537 */
538 void VM_random(prvm_prog_t *prog)
539 {
540         VM_SAFEPARMCOUNT(0,VM_random);
541
542         PRVM_G_FLOAT(OFS_RETURN) = lhrandom(0, 1);
543 }
544
545 /*
546 =========
547 VM_localsound
548
549 localsound(string sample)
550 =========
551 */
552 void VM_localsound(prvm_prog_t *prog)
553 {
554         const char *s;
555
556         VM_SAFEPARMCOUNT(1,VM_localsound);
557
558         s = PRVM_G_STRING(OFS_PARM0);
559
560         if(!S_LocalSound (s))
561         {
562                 PRVM_G_FLOAT(OFS_RETURN) = -4;
563                 VM_Warning(prog, "VM_localsound: Failed to play %s for %s !\n", s, prog->name);
564                 return;
565         }
566
567         PRVM_G_FLOAT(OFS_RETURN) = 1;
568 }
569
570 /*
571 =================
572 VM_break
573
574 break()
575 =================
576 */
577 void VM_break(prvm_prog_t *prog)
578 {
579         prog->error_cmd("%s: break statement", prog->name);
580 }
581
582 //============================================================================
583
584 /*
585 =================
586 VM_localcmd
587
588 Sends text over to the client's execution buffer
589
590 [localcmd (string, ...) or]
591 cmd (string, ...)
592 =================
593 */
594 void VM_localcmd(prvm_prog_t *prog)
595 {
596         char string[VM_STRINGTEMP_LENGTH];
597         VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd);
598         VM_VarString(prog, 0, string, sizeof(string));
599         Cbuf_AddText(string);
600 }
601
602 static qboolean PRVM_Cvar_ReadOk(const char *string)
603 {
604         cvar_t *cvar;
605         cvar = Cvar_FindVar(string);
606         return ((cvar) && ((cvar->flags & CVAR_PRIVATE) == 0));
607 }
608
609 /*
610 =================
611 VM_cvar
612
613 float cvar (string)
614 =================
615 */
616 void VM_cvar(prvm_prog_t *prog)
617 {
618         char string[VM_STRINGTEMP_LENGTH];
619         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
620         VM_VarString(prog, 0, string, sizeof(string));
621         VM_CheckEmptyString(prog, string);
622         PRVM_G_FLOAT(OFS_RETURN) = PRVM_Cvar_ReadOk(string) ? Cvar_VariableValue(string) : 0;
623 }
624
625 /*
626 =================
627 VM_cvar
628
629 float cvar_type (string)
630 float CVAR_TYPEFLAG_EXISTS = 1;
631 float CVAR_TYPEFLAG_SAVED = 2;
632 float CVAR_TYPEFLAG_PRIVATE = 4;
633 float CVAR_TYPEFLAG_ENGINE = 8;
634 float CVAR_TYPEFLAG_HASDESCRIPTION = 16;
635 float CVAR_TYPEFLAG_READONLY = 32;
636 =================
637 */
638 void VM_cvar_type(prvm_prog_t *prog)
639 {
640         char string[VM_STRINGTEMP_LENGTH];
641         cvar_t *cvar;
642         int ret;
643
644         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
645         VM_VarString(prog, 0, string, sizeof(string));
646         VM_CheckEmptyString(prog, string);
647         cvar = Cvar_FindVar(string);
648
649
650         if(!cvar)
651         {
652                 PRVM_G_FLOAT(OFS_RETURN) = 0;
653                 return; // CVAR_TYPE_NONE
654         }
655
656         ret = 1; // CVAR_EXISTS
657         if(cvar->flags & CVAR_SAVE)
658                 ret |= 2; // CVAR_TYPE_SAVED
659         if(cvar->flags & CVAR_PRIVATE)
660                 ret |= 4; // CVAR_TYPE_PRIVATE
661         if(!(cvar->flags & CVAR_ALLOCATED))
662                 ret |= 8; // CVAR_TYPE_ENGINE
663         if(cvar->description != cvar_dummy_description)
664                 ret |= 16; // CVAR_TYPE_HASDESCRIPTION
665         if(cvar->flags & CVAR_READONLY)
666                 ret |= 32; // CVAR_TYPE_READONLY
667         
668         PRVM_G_FLOAT(OFS_RETURN) = ret;
669 }
670
671 /*
672 =================
673 VM_cvar_string
674
675 const string    VM_cvar_string (string, ...)
676 =================
677 */
678 void VM_cvar_string(prvm_prog_t *prog)
679 {
680         char string[VM_STRINGTEMP_LENGTH];
681         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_string);
682         VM_VarString(prog, 0, string, sizeof(string));
683         VM_CheckEmptyString(prog, string);
684         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, PRVM_Cvar_ReadOk(string) ? Cvar_VariableString(string) : "");
685 }
686
687
688 /*
689 ========================
690 VM_cvar_defstring
691
692 const string    VM_cvar_defstring (string, ...)
693 ========================
694 */
695 void VM_cvar_defstring(prvm_prog_t *prog)
696 {
697         char string[VM_STRINGTEMP_LENGTH];
698         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_defstring);
699         VM_VarString(prog, 0, string, sizeof(string));
700         VM_CheckEmptyString(prog, string);
701         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, Cvar_VariableDefString(string));
702 }
703
704 /*
705 ========================
706 VM_cvar_defstring
707
708 const string    VM_cvar_description (string, ...)
709 ========================
710 */
711 void VM_cvar_description(prvm_prog_t *prog)
712 {
713         char string[VM_STRINGTEMP_LENGTH];
714         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_description);
715         VM_VarString(prog, 0, string, sizeof(string));
716         VM_CheckEmptyString(prog, string);
717         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, Cvar_VariableDescription(string));
718 }
719 /*
720 =================
721 VM_cvar_set
722
723 void cvar_set (string,string, ...)
724 =================
725 */
726 void VM_cvar_set(prvm_prog_t *prog)
727 {
728         const char *name;
729         char string[VM_STRINGTEMP_LENGTH];
730         VM_SAFEPARMCOUNTRANGE(2,8,VM_cvar_set);
731         VM_VarString(prog, 1, string, sizeof(string));
732         name = PRVM_G_STRING(OFS_PARM0);
733         VM_CheckEmptyString(prog, name);
734         Cvar_Set(name, string);
735 }
736
737 /*
738 =========
739 VM_dprint
740
741 dprint(...[string])
742 =========
743 */
744 void VM_dprint(prvm_prog_t *prog)
745 {
746         char string[VM_STRINGTEMP_LENGTH];
747         VM_SAFEPARMCOUNTRANGE(1, 8, VM_dprint);
748         VM_VarString(prog, 0, string, sizeof(string));
749 #if 1
750         Con_DPrintf("%s", string);
751 #else
752         Con_DPrintf("%s: %s", prog->name, string);
753 #endif
754 }
755
756 /*
757 =========
758 VM_ftos
759
760 string  ftos(float)
761 =========
762 */
763
764 void VM_ftos(prvm_prog_t *prog)
765 {
766         float v;
767         char s[128];
768
769         VM_SAFEPARMCOUNT(1, VM_ftos);
770
771         v = PRVM_G_FLOAT(OFS_PARM0);
772
773         if ((float)((int)v) == v)
774                 dpsnprintf(s, sizeof(s), "%i", (int)v);
775         else
776                 dpsnprintf(s, sizeof(s), "%f", v);
777         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s);
778 }
779
780 /*
781 =========
782 VM_fabs
783
784 float   fabs(float)
785 =========
786 */
787
788 void VM_fabs(prvm_prog_t *prog)
789 {
790         float   v;
791
792         VM_SAFEPARMCOUNT(1,VM_fabs);
793
794         v = PRVM_G_FLOAT(OFS_PARM0);
795         PRVM_G_FLOAT(OFS_RETURN) = fabs(v);
796 }
797
798 /*
799 =========
800 VM_vtos
801
802 string  vtos(vector)
803 =========
804 */
805
806 void VM_vtos(prvm_prog_t *prog)
807 {
808         char s[512];
809
810         VM_SAFEPARMCOUNT(1,VM_vtos);
811
812         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]);
813         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s);
814 }
815
816 /*
817 =========
818 VM_etos
819
820 string  etos(entity)
821 =========
822 */
823
824 void VM_etos(prvm_prog_t *prog)
825 {
826         char s[128];
827
828         VM_SAFEPARMCOUNT(1, VM_etos);
829
830         dpsnprintf (s, sizeof(s), "entity %i", PRVM_G_EDICTNUM(OFS_PARM0));
831         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s);
832 }
833
834 /*
835 =========
836 VM_stof
837
838 float stof(...[string])
839 =========
840 */
841 void VM_stof(prvm_prog_t *prog)
842 {
843         char string[VM_STRINGTEMP_LENGTH];
844         VM_SAFEPARMCOUNTRANGE(1, 8, VM_stof);
845         VM_VarString(prog, 0, string, sizeof(string));
846         PRVM_G_FLOAT(OFS_RETURN) = atof(string);
847 }
848
849 /*
850 ========================
851 VM_itof
852
853 float itof(intt ent)
854 ========================
855 */
856 void VM_itof(prvm_prog_t *prog)
857 {
858         VM_SAFEPARMCOUNT(1, VM_itof);
859         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
860 }
861
862 /*
863 ========================
864 VM_ftoe
865
866 entity ftoe(float num)
867 ========================
868 */
869 void VM_ftoe(prvm_prog_t *prog)
870 {
871         int ent;
872         VM_SAFEPARMCOUNT(1, VM_ftoe);
873
874         ent = (int)PRVM_G_FLOAT(OFS_PARM0);
875         if (ent < 0 || ent >= prog->max_edicts || PRVM_PROG_TO_EDICT(ent)->priv.required->free)
876                 ent = 0; // return world instead of a free or invalid entity
877
878         PRVM_G_INT(OFS_RETURN) = ent;
879 }
880
881 /*
882 ========================
883 VM_etof
884
885 float etof(entity ent)
886 ========================
887 */
888 void VM_etof(prvm_prog_t *prog)
889 {
890         VM_SAFEPARMCOUNT(1, VM_etof);
891         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICTNUM(OFS_PARM0);
892 }
893
894 /*
895 =========
896 VM_strftime
897
898 string strftime(float uselocaltime, string[, string ...])
899 =========
900 */
901 void VM_strftime(prvm_prog_t *prog)
902 {
903         time_t t;
904 #if _MSC_VER >= 1400
905         struct tm tm;
906         int tmresult;
907 #else
908         struct tm *tm;
909 #endif
910         char fmt[VM_STRINGTEMP_LENGTH];
911         char result[VM_STRINGTEMP_LENGTH];
912         VM_SAFEPARMCOUNTRANGE(2, 8, VM_strftime);
913         VM_VarString(prog, 1, fmt, sizeof(fmt));
914         t = time(NULL);
915 #if _MSC_VER >= 1400
916         if (PRVM_G_FLOAT(OFS_PARM0))
917                 tmresult = localtime_s(&tm, &t);
918         else
919                 tmresult = gmtime_s(&tm, &t);
920         if (!tmresult)
921 #else
922         if (PRVM_G_FLOAT(OFS_PARM0))
923                 tm = localtime(&t);
924         else
925                 tm = gmtime(&t);
926         if (!tm)
927 #endif
928         {
929                 PRVM_G_INT(OFS_RETURN) = 0;
930                 return;
931         }
932 #if _MSC_VER >= 1400
933         strftime(result, sizeof(result), fmt, &tm);
934 #else
935         strftime(result, sizeof(result), fmt, tm);
936 #endif
937         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, result);
938 }
939
940 /*
941 =========
942 VM_spawn
943
944 entity spawn()
945 =========
946 */
947
948 void VM_spawn(prvm_prog_t *prog)
949 {
950         prvm_edict_t    *ed;
951         VM_SAFEPARMCOUNT(0, VM_spawn);
952         prog->xfunction->builtinsprofile += 20;
953         ed = PRVM_ED_Alloc(prog);
954         VM_RETURN_EDICT(ed);
955 }
956
957 /*
958 =========
959 VM_remove
960
961 remove(entity e)
962 =========
963 */
964
965 void VM_remove(prvm_prog_t *prog)
966 {
967         prvm_edict_t    *ed;
968         prog->xfunction->builtinsprofile += 20;
969
970         VM_SAFEPARMCOUNT(1, VM_remove);
971
972         ed = PRVM_G_EDICT(OFS_PARM0);
973         if( PRVM_NUM_FOR_EDICT(ed) <= prog->reserved_edicts )
974         {
975                 if (developer.integer > 0)
976                         VM_Warning(prog, "VM_remove: tried to remove the null entity or a reserved entity!\n" );
977         }
978         else if( ed->priv.required->free )
979         {
980                 if (developer.integer > 0)
981                         VM_Warning(prog, "VM_remove: tried to remove an already freed entity!\n" );
982         }
983         else
984                 PRVM_ED_Free (prog, ed);
985 }
986
987 /*
988 =========
989 VM_find
990
991 entity  find(entity start, .string field, string match)
992 =========
993 */
994
995 void VM_find(prvm_prog_t *prog)
996 {
997         int             e;
998         int             f;
999         const char      *s, *t;
1000         prvm_edict_t    *ed;
1001
1002         VM_SAFEPARMCOUNT(3,VM_find);
1003
1004         e = PRVM_G_EDICTNUM(OFS_PARM0);
1005         f = PRVM_G_INT(OFS_PARM1);
1006         s = PRVM_G_STRING(OFS_PARM2);
1007
1008         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1009         // expects it to find all the monsters, so we must be careful to support
1010         // searching for ""
1011
1012         for (e++ ; e < prog->num_edicts ; e++)
1013         {
1014                 prog->xfunction->builtinsprofile++;
1015                 ed = PRVM_EDICT_NUM(e);
1016                 if (ed->priv.required->free)
1017                         continue;
1018                 t = PRVM_E_STRING(ed,f);
1019                 if (!t)
1020                         t = "";
1021                 if (!strcmp(t,s))
1022                 {
1023                         VM_RETURN_EDICT(ed);
1024                         return;
1025                 }
1026         }
1027
1028         VM_RETURN_EDICT(prog->edicts);
1029 }
1030
1031 /*
1032 =========
1033 VM_findfloat
1034
1035   entity        findfloat(entity start, .float field, float match)
1036   entity        findentity(entity start, .entity field, entity match)
1037 =========
1038 */
1039 // LordHavoc: added this for searching float, int, and entity reference fields
1040 void VM_findfloat(prvm_prog_t *prog)
1041 {
1042         int             e;
1043         int             f;
1044         float   s;
1045         prvm_edict_t    *ed;
1046
1047         VM_SAFEPARMCOUNT(3,VM_findfloat);
1048
1049         e = PRVM_G_EDICTNUM(OFS_PARM0);
1050         f = PRVM_G_INT(OFS_PARM1);
1051         s = PRVM_G_FLOAT(OFS_PARM2);
1052
1053         for (e++ ; e < prog->num_edicts ; e++)
1054         {
1055                 prog->xfunction->builtinsprofile++;
1056                 ed = PRVM_EDICT_NUM(e);
1057                 if (ed->priv.required->free)
1058                         continue;
1059                 if (PRVM_E_FLOAT(ed,f) == s)
1060                 {
1061                         VM_RETURN_EDICT(ed);
1062                         return;
1063                 }
1064         }
1065
1066         VM_RETURN_EDICT(prog->edicts);
1067 }
1068
1069 /*
1070 =========
1071 VM_findchain
1072
1073 entity  findchain(.string field, string match)
1074 =========
1075 */
1076 // chained search for strings in entity fields
1077 // entity(.string field, string match) findchain = #402;
1078 void VM_findchain(prvm_prog_t *prog)
1079 {
1080         int             i;
1081         int             f;
1082         const char      *s, *t;
1083         prvm_edict_t    *ent, *chain;
1084         int chainfield;
1085
1086         VM_SAFEPARMCOUNTRANGE(2,3,VM_findchain);
1087
1088         if(prog->argc == 3)
1089                 chainfield = PRVM_G_INT(OFS_PARM2);
1090         else
1091                 chainfield = prog->fieldoffsets.chain;
1092         if (chainfield < 0)
1093                 prog->error_cmd("VM_findchain: %s doesnt have the specified chain field !", prog->name);
1094
1095         chain = prog->edicts;
1096
1097         f = PRVM_G_INT(OFS_PARM0);
1098         s = PRVM_G_STRING(OFS_PARM1);
1099
1100         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1101         // expects it to find all the monsters, so we must be careful to support
1102         // searching for ""
1103
1104         ent = PRVM_NEXT_EDICT(prog->edicts);
1105         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1106         {
1107                 prog->xfunction->builtinsprofile++;
1108                 if (ent->priv.required->free)
1109                         continue;
1110                 t = PRVM_E_STRING(ent,f);
1111                 if (!t)
1112                         t = "";
1113                 if (strcmp(t,s))
1114                         continue;
1115
1116                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_NUM_FOR_EDICT(chain);
1117                 chain = ent;
1118         }
1119
1120         VM_RETURN_EDICT(chain);
1121 }
1122
1123 /*
1124 =========
1125 VM_findchainfloat
1126
1127 entity  findchainfloat(.string field, float match)
1128 entity  findchainentity(.string field, entity match)
1129 =========
1130 */
1131 // LordHavoc: chained search for float, int, and entity reference fields
1132 // entity(.string field, float match) findchainfloat = #403;
1133 void VM_findchainfloat(prvm_prog_t *prog)
1134 {
1135         int             i;
1136         int             f;
1137         float   s;
1138         prvm_edict_t    *ent, *chain;
1139         int chainfield;
1140
1141         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainfloat);
1142
1143         if(prog->argc == 3)
1144                 chainfield = PRVM_G_INT(OFS_PARM2);
1145         else
1146                 chainfield = prog->fieldoffsets.chain;
1147         if (chainfield < 0)
1148                 prog->error_cmd("VM_findchain: %s doesnt have the specified chain field !", prog->name);
1149
1150         chain = (prvm_edict_t *)prog->edicts;
1151
1152         f = PRVM_G_INT(OFS_PARM0);
1153         s = PRVM_G_FLOAT(OFS_PARM1);
1154
1155         ent = PRVM_NEXT_EDICT(prog->edicts);
1156         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1157         {
1158                 prog->xfunction->builtinsprofile++;
1159                 if (ent->priv.required->free)
1160                         continue;
1161                 if (PRVM_E_FLOAT(ent,f) != s)
1162                         continue;
1163
1164                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1165                 chain = ent;
1166         }
1167
1168         VM_RETURN_EDICT(chain);
1169 }
1170
1171 /*
1172 ========================
1173 VM_findflags
1174
1175 entity  findflags(entity start, .float field, float match)
1176 ========================
1177 */
1178 // LordHavoc: search for flags in float fields
1179 void VM_findflags(prvm_prog_t *prog)
1180 {
1181         int             e;
1182         int             f;
1183         int             s;
1184         prvm_edict_t    *ed;
1185
1186         VM_SAFEPARMCOUNT(3, VM_findflags);
1187
1188
1189         e = PRVM_G_EDICTNUM(OFS_PARM0);
1190         f = PRVM_G_INT(OFS_PARM1);
1191         s = (int)PRVM_G_FLOAT(OFS_PARM2);
1192
1193         for (e++ ; e < prog->num_edicts ; e++)
1194         {
1195                 prog->xfunction->builtinsprofile++;
1196                 ed = PRVM_EDICT_NUM(e);
1197                 if (ed->priv.required->free)
1198                         continue;
1199                 if (!PRVM_E_FLOAT(ed,f))
1200                         continue;
1201                 if ((int)PRVM_E_FLOAT(ed,f) & s)
1202                 {
1203                         VM_RETURN_EDICT(ed);
1204                         return;
1205                 }
1206         }
1207
1208         VM_RETURN_EDICT(prog->edicts);
1209 }
1210
1211 /*
1212 ========================
1213 VM_findchainflags
1214
1215 entity  findchainflags(.float field, float match)
1216 ========================
1217 */
1218 // LordHavoc: chained search for flags in float fields
1219 void VM_findchainflags(prvm_prog_t *prog)
1220 {
1221         int             i;
1222         int             f;
1223         int             s;
1224         prvm_edict_t    *ent, *chain;
1225         int chainfield;
1226
1227         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainflags);
1228
1229         if(prog->argc == 3)
1230                 chainfield = PRVM_G_INT(OFS_PARM2);
1231         else
1232                 chainfield = prog->fieldoffsets.chain;
1233         if (chainfield < 0)
1234                 prog->error_cmd("VM_findchain: %s doesnt have the specified chain field !", prog->name);
1235
1236         chain = (prvm_edict_t *)prog->edicts;
1237
1238         f = PRVM_G_INT(OFS_PARM0);
1239         s = (int)PRVM_G_FLOAT(OFS_PARM1);
1240
1241         ent = PRVM_NEXT_EDICT(prog->edicts);
1242         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1243         {
1244                 prog->xfunction->builtinsprofile++;
1245                 if (ent->priv.required->free)
1246                         continue;
1247                 if (!PRVM_E_FLOAT(ent,f))
1248                         continue;
1249                 if (!((int)PRVM_E_FLOAT(ent,f) & s))
1250                         continue;
1251
1252                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1253                 chain = ent;
1254         }
1255
1256         VM_RETURN_EDICT(chain);
1257 }
1258
1259 /*
1260 =========
1261 VM_precache_sound
1262
1263 string  precache_sound (string sample)
1264 =========
1265 */
1266 void VM_precache_sound(prvm_prog_t *prog)
1267 {
1268         const char *s;
1269
1270         VM_SAFEPARMCOUNT(1, VM_precache_sound);
1271
1272         s = PRVM_G_STRING(OFS_PARM0);
1273         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1274         //VM_CheckEmptyString(prog, s);
1275
1276         if(snd_initialized.integer && !S_PrecacheSound(s, true, true))
1277         {
1278                 VM_Warning(prog, "VM_precache_sound: Failed to load %s for %s\n", s, prog->name);
1279                 return;
1280         }
1281 }
1282
1283 /*
1284 =================
1285 VM_precache_file
1286
1287 returns the same string as output
1288
1289 does nothing, only used by qcc to build .pak archives
1290 =================
1291 */
1292 void VM_precache_file(prvm_prog_t *prog)
1293 {
1294         VM_SAFEPARMCOUNT(1,VM_precache_file);
1295         // precache_file is only used to copy files with qcc, it does nothing
1296         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1297 }
1298
1299 /*
1300 =========
1301 VM_coredump
1302
1303 coredump()
1304 =========
1305 */
1306 void VM_coredump(prvm_prog_t *prog)
1307 {
1308         VM_SAFEPARMCOUNT(0,VM_coredump);
1309
1310         Cbuf_AddText("prvm_edicts ");
1311         Cbuf_AddText(prog->name);
1312         Cbuf_AddText("\n");
1313 }
1314
1315 /*
1316 =========
1317 VM_stackdump
1318
1319 stackdump()
1320 =========
1321 */
1322 void VM_stackdump(prvm_prog_t *prog)
1323 {
1324         VM_SAFEPARMCOUNT(0, VM_stackdump);
1325
1326         PRVM_StackTrace(prog);
1327 }
1328
1329 /*
1330 =========
1331 VM_crash
1332
1333 crash()
1334 =========
1335 */
1336
1337 void VM_crash(prvm_prog_t *prog)
1338 {
1339         VM_SAFEPARMCOUNT(0, VM_crash);
1340
1341         prog->error_cmd("Crash called by %s",prog->name);
1342 }
1343
1344 /*
1345 =========
1346 VM_traceon
1347
1348 traceon()
1349 =========
1350 */
1351 void VM_traceon(prvm_prog_t *prog)
1352 {
1353         VM_SAFEPARMCOUNT(0,VM_traceon);
1354
1355         prog->trace = true;
1356 }
1357
1358 /*
1359 =========
1360 VM_traceoff
1361
1362 traceoff()
1363 =========
1364 */
1365 void VM_traceoff(prvm_prog_t *prog)
1366 {
1367         VM_SAFEPARMCOUNT(0,VM_traceoff);
1368
1369         prog->trace = false;
1370 }
1371
1372 /*
1373 =========
1374 VM_eprint
1375
1376 eprint(entity e)
1377 =========
1378 */
1379 void VM_eprint(prvm_prog_t *prog)
1380 {
1381         VM_SAFEPARMCOUNT(1,VM_eprint);
1382
1383         PRVM_ED_PrintNum (prog, PRVM_G_EDICTNUM(OFS_PARM0), NULL);
1384 }
1385
1386 /*
1387 =========
1388 VM_rint
1389
1390 float   rint(float)
1391 =========
1392 */
1393 void VM_rint(prvm_prog_t *prog)
1394 {
1395         float f;
1396         VM_SAFEPARMCOUNT(1,VM_rint);
1397
1398         f = PRVM_G_FLOAT(OFS_PARM0);
1399         if (f > 0)
1400                 PRVM_G_FLOAT(OFS_RETURN) = floor(f + 0.5);
1401         else
1402                 PRVM_G_FLOAT(OFS_RETURN) = ceil(f - 0.5);
1403 }
1404
1405 /*
1406 =========
1407 VM_floor
1408
1409 float   floor(float)
1410 =========
1411 */
1412 void VM_floor(prvm_prog_t *prog)
1413 {
1414         VM_SAFEPARMCOUNT(1,VM_floor);
1415
1416         PRVM_G_FLOAT(OFS_RETURN) = floor(PRVM_G_FLOAT(OFS_PARM0));
1417 }
1418
1419 /*
1420 =========
1421 VM_ceil
1422
1423 float   ceil(float)
1424 =========
1425 */
1426 void VM_ceil(prvm_prog_t *prog)
1427 {
1428         VM_SAFEPARMCOUNT(1,VM_ceil);
1429
1430         PRVM_G_FLOAT(OFS_RETURN) = ceil(PRVM_G_FLOAT(OFS_PARM0));
1431 }
1432
1433
1434 /*
1435 =============
1436 VM_nextent
1437
1438 entity  nextent(entity)
1439 =============
1440 */
1441 void VM_nextent(prvm_prog_t *prog)
1442 {
1443         int             i;
1444         prvm_edict_t    *ent;
1445
1446         VM_SAFEPARMCOUNT(1, VM_nextent);
1447
1448         i = PRVM_G_EDICTNUM(OFS_PARM0);
1449         while (1)
1450         {
1451                 prog->xfunction->builtinsprofile++;
1452                 i++;
1453                 if (i == prog->num_edicts)
1454                 {
1455                         VM_RETURN_EDICT(prog->edicts);
1456                         return;
1457                 }
1458                 ent = PRVM_EDICT_NUM(i);
1459                 if (!ent->priv.required->free)
1460                 {
1461                         VM_RETURN_EDICT(ent);
1462                         return;
1463                 }
1464         }
1465 }
1466
1467 //=============================================================================
1468
1469 /*
1470 ==============
1471 VM_changelevel
1472 server and menu
1473
1474 changelevel(string map)
1475 ==============
1476 */
1477 void VM_changelevel(prvm_prog_t *prog)
1478 {
1479         char vabuf[1024];
1480         VM_SAFEPARMCOUNT(1, VM_changelevel);
1481
1482         if(!sv.active)
1483         {
1484                 VM_Warning(prog, "VM_changelevel: game is not server (%s)\n", prog->name);
1485                 return;
1486         }
1487
1488 // make sure we don't issue two changelevels
1489         if (svs.changelevel_issued)
1490                 return;
1491         svs.changelevel_issued = true;
1492
1493         Cbuf_AddText(va(vabuf, sizeof(vabuf), "changelevel %s\n",PRVM_G_STRING(OFS_PARM0)));
1494 }
1495
1496 /*
1497 =========
1498 VM_sin
1499
1500 float   sin(float)
1501 =========
1502 */
1503 void VM_sin(prvm_prog_t *prog)
1504 {
1505         VM_SAFEPARMCOUNT(1,VM_sin);
1506         PRVM_G_FLOAT(OFS_RETURN) = sin(PRVM_G_FLOAT(OFS_PARM0));
1507 }
1508
1509 /*
1510 =========
1511 VM_cos
1512 float   cos(float)
1513 =========
1514 */
1515 void VM_cos(prvm_prog_t *prog)
1516 {
1517         VM_SAFEPARMCOUNT(1,VM_cos);
1518         PRVM_G_FLOAT(OFS_RETURN) = cos(PRVM_G_FLOAT(OFS_PARM0));
1519 }
1520
1521 /*
1522 =========
1523 VM_sqrt
1524
1525 float   sqrt(float)
1526 =========
1527 */
1528 void VM_sqrt(prvm_prog_t *prog)
1529 {
1530         VM_SAFEPARMCOUNT(1,VM_sqrt);
1531         PRVM_G_FLOAT(OFS_RETURN) = sqrt(PRVM_G_FLOAT(OFS_PARM0));
1532 }
1533
1534 /*
1535 =========
1536 VM_asin
1537
1538 float   asin(float)
1539 =========
1540 */
1541 void VM_asin(prvm_prog_t *prog)
1542 {
1543         VM_SAFEPARMCOUNT(1,VM_asin);
1544         PRVM_G_FLOAT(OFS_RETURN) = asin(PRVM_G_FLOAT(OFS_PARM0));
1545 }
1546
1547 /*
1548 =========
1549 VM_acos
1550 float   acos(float)
1551 =========
1552 */
1553 void VM_acos(prvm_prog_t *prog)
1554 {
1555         VM_SAFEPARMCOUNT(1,VM_acos);
1556         PRVM_G_FLOAT(OFS_RETURN) = acos(PRVM_G_FLOAT(OFS_PARM0));
1557 }
1558
1559 /*
1560 =========
1561 VM_atan
1562 float   atan(float)
1563 =========
1564 */
1565 void VM_atan(prvm_prog_t *prog)
1566 {
1567         VM_SAFEPARMCOUNT(1,VM_atan);
1568         PRVM_G_FLOAT(OFS_RETURN) = atan(PRVM_G_FLOAT(OFS_PARM0));
1569 }
1570
1571 /*
1572 =========
1573 VM_atan2
1574 float   atan2(float,float)
1575 =========
1576 */
1577 void VM_atan2(prvm_prog_t *prog)
1578 {
1579         VM_SAFEPARMCOUNT(2,VM_atan2);
1580         PRVM_G_FLOAT(OFS_RETURN) = atan2(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1581 }
1582
1583 /*
1584 =========
1585 VM_tan
1586 float   tan(float)
1587 =========
1588 */
1589 void VM_tan(prvm_prog_t *prog)
1590 {
1591         VM_SAFEPARMCOUNT(1,VM_tan);
1592         PRVM_G_FLOAT(OFS_RETURN) = tan(PRVM_G_FLOAT(OFS_PARM0));
1593 }
1594
1595 /*
1596 =================
1597 VM_randomvec
1598
1599 Returns a vector of length < 1 and > 0
1600
1601 vector randomvec()
1602 =================
1603 */
1604 void VM_randomvec(prvm_prog_t *prog)
1605 {
1606         vec3_t temp;
1607         VM_SAFEPARMCOUNT(0, VM_randomvec);
1608         VectorRandom(temp);
1609         VectorCopy(temp, PRVM_G_VECTOR(OFS_RETURN));
1610 }
1611
1612 //=============================================================================
1613
1614 /*
1615 =========
1616 VM_registercvar
1617
1618 float   registercvar (string name, string value[, float flags])
1619 =========
1620 */
1621 void VM_registercvar(prvm_prog_t *prog)
1622 {
1623         const char *name, *value;
1624         int     flags;
1625
1626         VM_SAFEPARMCOUNTRANGE(2, 3, VM_registercvar);
1627
1628         name = PRVM_G_STRING(OFS_PARM0);
1629         value = PRVM_G_STRING(OFS_PARM1);
1630         flags = prog->argc >= 3 ? (int)PRVM_G_FLOAT(OFS_PARM2) : 0;
1631         PRVM_G_FLOAT(OFS_RETURN) = 0;
1632
1633         if(flags > CVAR_MAXFLAGSVAL)
1634                 return;
1635
1636 // first check to see if it has already been defined
1637         if (Cvar_FindVar (name))
1638                 return;
1639
1640 // check for overlap with a command
1641         if (Cmd_Exists (name))
1642         {
1643                 VM_Warning(prog, "VM_registercvar: %s is a command\n", name);
1644                 return;
1645         }
1646
1647         Cvar_Get(name, value, flags, NULL);
1648
1649         PRVM_G_FLOAT(OFS_RETURN) = 1; // success
1650 }
1651
1652
1653 /*
1654 =================
1655 VM_min
1656
1657 returns the minimum of two supplied floats
1658
1659 float min(float a, float b, ...[float])
1660 =================
1661 */
1662 void VM_min(prvm_prog_t *prog)
1663 {
1664         VM_SAFEPARMCOUNTRANGE(2, 8, VM_min);
1665         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1666         if (prog->argc >= 3)
1667         {
1668                 int i;
1669                 float f = PRVM_G_FLOAT(OFS_PARM0);
1670                 for (i = 1;i < prog->argc;i++)
1671                         if (f > PRVM_G_FLOAT((OFS_PARM0+i*3)))
1672                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1673                 PRVM_G_FLOAT(OFS_RETURN) = f;
1674         }
1675         else
1676                 PRVM_G_FLOAT(OFS_RETURN) = min(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1677 }
1678
1679 /*
1680 =================
1681 VM_max
1682
1683 returns the maximum of two supplied floats
1684
1685 float   max(float a, float b, ...[float])
1686 =================
1687 */
1688 void VM_max(prvm_prog_t *prog)
1689 {
1690         VM_SAFEPARMCOUNTRANGE(2, 8, VM_max);
1691         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1692         if (prog->argc >= 3)
1693         {
1694                 int i;
1695                 float f = PRVM_G_FLOAT(OFS_PARM0);
1696                 for (i = 1;i < prog->argc;i++)
1697                         if (f < PRVM_G_FLOAT((OFS_PARM0+i*3)))
1698                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1699                 PRVM_G_FLOAT(OFS_RETURN) = f;
1700         }
1701         else
1702                 PRVM_G_FLOAT(OFS_RETURN) = max(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1703 }
1704
1705 /*
1706 =================
1707 VM_bound
1708
1709 returns number bounded by supplied range
1710
1711 float   bound(float min, float value, float max)
1712 =================
1713 */
1714 void VM_bound(prvm_prog_t *prog)
1715 {
1716         VM_SAFEPARMCOUNT(3,VM_bound);
1717         PRVM_G_FLOAT(OFS_RETURN) = bound(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1), PRVM_G_FLOAT(OFS_PARM2));
1718 }
1719
1720 /*
1721 =================
1722 VM_pow
1723
1724 returns a raised to power b
1725
1726 float   pow(float a, float b)
1727 =================
1728 */
1729 void VM_pow(prvm_prog_t *prog)
1730 {
1731         VM_SAFEPARMCOUNT(2,VM_pow);
1732         PRVM_G_FLOAT(OFS_RETURN) = pow(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1733 }
1734
1735 void VM_log(prvm_prog_t *prog)
1736 {
1737         VM_SAFEPARMCOUNT(1,VM_log);
1738         PRVM_G_FLOAT(OFS_RETURN) = log(PRVM_G_FLOAT(OFS_PARM0));
1739 }
1740
1741 void VM_Files_Init(prvm_prog_t *prog)
1742 {
1743         int i;
1744         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1745                 prog->openfiles[i] = NULL;
1746 }
1747
1748 void VM_Files_CloseAll(prvm_prog_t *prog)
1749 {
1750         int i;
1751         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1752         {
1753                 if (prog->openfiles[i])
1754                         FS_Close(prog->openfiles[i]);
1755                 prog->openfiles[i] = NULL;
1756         }
1757 }
1758
1759 static qfile_t *VM_GetFileHandle(prvm_prog_t *prog, int index)
1760 {
1761         if (index < 0 || index >= PRVM_MAX_OPENFILES)
1762         {
1763                 Con_Printf("VM_GetFileHandle: invalid file handle %i used in %s\n", index, prog->name);
1764                 return NULL;
1765         }
1766         if (prog->openfiles[index] == NULL)
1767         {
1768                 Con_Printf("VM_GetFileHandle: no such file handle %i (or file has been closed) in %s\n", index, prog->name);
1769                 return NULL;
1770         }
1771         return prog->openfiles[index];
1772 }
1773
1774 /*
1775 =========
1776 VM_fopen
1777
1778 float   fopen(string filename, float mode)
1779 =========
1780 */
1781 // float(string filename, float mode) fopen = #110;
1782 // opens a file inside quake/gamedir/data/ (mode is FILE_READ, FILE_APPEND, or FILE_WRITE),
1783 // returns fhandle >= 0 if successful, or fhandle < 0 if unable to open file for any reason
1784 void VM_fopen(prvm_prog_t *prog)
1785 {
1786         int filenum, mode;
1787         const char *modestring, *filename;
1788         char vabuf[1024];
1789
1790         VM_SAFEPARMCOUNT(2,VM_fopen);
1791
1792         for (filenum = 0;filenum < PRVM_MAX_OPENFILES;filenum++)
1793                 if (prog->openfiles[filenum] == NULL)
1794                         break;
1795         if (filenum >= PRVM_MAX_OPENFILES)
1796         {
1797                 PRVM_G_FLOAT(OFS_RETURN) = -2;
1798                 VM_Warning(prog, "VM_fopen: %s ran out of file handles (%i)\n", prog->name, PRVM_MAX_OPENFILES);
1799                 return;
1800         }
1801         filename = PRVM_G_STRING(OFS_PARM0);
1802         mode = (int)PRVM_G_FLOAT(OFS_PARM1);
1803         switch(mode)
1804         {
1805         case 0: // FILE_READ
1806                 modestring = "rb";
1807                 prog->openfiles[filenum] = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "data/%s", filename), false);
1808                 if (prog->openfiles[filenum] == NULL)
1809                         prog->openfiles[filenum] = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "%s", filename), false);
1810                 break;
1811         case 1: // FILE_APPEND
1812                 modestring = "a";
1813                 prog->openfiles[filenum] = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "data/%s", filename), modestring, false);
1814                 break;
1815         case 2: // FILE_WRITE
1816                 modestring = "w";
1817                 prog->openfiles[filenum] = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "data/%s", filename), modestring, false);
1818                 break;
1819         default:
1820                 PRVM_G_FLOAT(OFS_RETURN) = -3;
1821                 VM_Warning(prog, "VM_fopen: %s: no such mode %i (valid: 0 = read, 1 = append, 2 = write)\n", prog->name, mode);
1822                 return;
1823         }
1824
1825         if (prog->openfiles[filenum] == NULL)
1826         {
1827                 PRVM_G_FLOAT(OFS_RETURN) = -1;
1828                 if (developer_extra.integer)
1829                         VM_Warning(prog, "VM_fopen: %s: %s mode %s failed\n", prog->name, filename, modestring);
1830         }
1831         else
1832         {
1833                 PRVM_G_FLOAT(OFS_RETURN) = filenum;
1834                 if (developer_extra.integer)
1835                         Con_DPrintf("VM_fopen: %s: %s mode %s opened as #%i\n", prog->name, filename, modestring, filenum);
1836                 prog->openfiles_origin[filenum] = PRVM_AllocationOrigin(prog);
1837         }
1838 }
1839
1840 /*
1841 =========
1842 VM_fclose
1843
1844 fclose(float fhandle)
1845 =========
1846 */
1847 //void(float fhandle) fclose = #111; // closes a file
1848 void VM_fclose(prvm_prog_t *prog)
1849 {
1850         int filenum;
1851
1852         VM_SAFEPARMCOUNT(1,VM_fclose);
1853
1854         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1855         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1856         {
1857                 VM_Warning(prog, "VM_fclose: invalid file handle %i used in %s\n", filenum, prog->name);
1858                 return;
1859         }
1860         if (prog->openfiles[filenum] == NULL)
1861         {
1862                 VM_Warning(prog, "VM_fclose: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
1863                 return;
1864         }
1865         FS_Close(prog->openfiles[filenum]);
1866         prog->openfiles[filenum] = NULL;
1867         if(prog->openfiles_origin[filenum])
1868                 PRVM_Free((char *)prog->openfiles_origin[filenum]);
1869         if (developer_extra.integer)
1870                 Con_DPrintf("VM_fclose: %s: #%i closed\n", prog->name, filenum);
1871 }
1872
1873 /*
1874 =========
1875 VM_fgets
1876
1877 string  fgets(float fhandle)
1878 =========
1879 */
1880 //string(float fhandle) fgets = #112; // reads a line of text from the file and returns as a tempstring
1881 void VM_fgets(prvm_prog_t *prog)
1882 {
1883         int c, end;
1884         char string[VM_STRINGTEMP_LENGTH];
1885         int filenum;
1886
1887         VM_SAFEPARMCOUNT(1,VM_fgets);
1888
1889         // set the return value regardless of any possible errors
1890         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
1891
1892         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1893         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1894         {
1895                 VM_Warning(prog, "VM_fgets: invalid file handle %i used in %s\n", filenum, prog->name);
1896                 return;
1897         }
1898         if (prog->openfiles[filenum] == NULL)
1899         {
1900                 VM_Warning(prog, "VM_fgets: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
1901                 return;
1902         }
1903         end = 0;
1904         for (;;)
1905         {
1906                 c = FS_Getc(prog->openfiles[filenum]);
1907                 if (c == '\r' || c == '\n' || c < 0)
1908                         break;
1909                 if (end < VM_STRINGTEMP_LENGTH - 1)
1910                         string[end++] = c;
1911         }
1912         string[end] = 0;
1913         // remove \n following \r
1914         if (c == '\r')
1915         {
1916                 c = FS_Getc(prog->openfiles[filenum]);
1917                 if (c != '\n')
1918                         FS_UnGetc(prog->openfiles[filenum], (unsigned char)c);
1919         }
1920         if (developer_extra.integer)
1921                 Con_DPrintf("fgets: %s: %s\n", prog->name, string);
1922         if (c >= 0 || end)
1923                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
1924 }
1925
1926 /*
1927 =========
1928 VM_fputs
1929
1930 fputs(float fhandle, string s)
1931 =========
1932 */
1933 //void(float fhandle, string s) fputs = #113; // writes a line of text to the end of the file
1934 void VM_fputs(prvm_prog_t *prog)
1935 {
1936         int stringlength;
1937         char string[VM_STRINGTEMP_LENGTH];
1938         int filenum;
1939
1940         VM_SAFEPARMCOUNT(2,VM_fputs);
1941
1942         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1943         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1944         {
1945                 VM_Warning(prog, "VM_fputs: invalid file handle %i used in %s\n", filenum, prog->name);
1946                 return;
1947         }
1948         if (prog->openfiles[filenum] == NULL)
1949         {
1950                 VM_Warning(prog, "VM_fputs: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
1951                 return;
1952         }
1953         VM_VarString(prog, 1, string, sizeof(string));
1954         if ((stringlength = (int)strlen(string)))
1955                 FS_Write(prog->openfiles[filenum], string, stringlength);
1956         if (developer_extra.integer)
1957                 Con_DPrintf("fputs: %s: %s\n", prog->name, string);
1958 }
1959
1960 /*
1961 =========
1962 VM_writetofile
1963
1964         writetofile(float fhandle, entity ent)
1965 =========
1966 */
1967 void VM_writetofile(prvm_prog_t *prog)
1968 {
1969         prvm_edict_t * ent;
1970         qfile_t *file;
1971
1972         VM_SAFEPARMCOUNT(2, VM_writetofile);
1973
1974         file = VM_GetFileHandle(prog, (int)PRVM_G_FLOAT(OFS_PARM0));
1975         if( !file )
1976         {
1977                 VM_Warning(prog, "VM_writetofile: invalid or closed file handle\n");
1978                 return;
1979         }
1980
1981         ent = PRVM_G_EDICT(OFS_PARM1);
1982         if(ent->priv.required->free)
1983         {
1984                 VM_Warning(prog, "VM_writetofile: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
1985                 return;
1986         }
1987
1988         PRVM_ED_Write (prog, file, ent);
1989 }
1990
1991 // KrimZon - DP_QC_ENTITYDATA
1992 /*
1993 =========
1994 VM_numentityfields
1995
1996 float() numentityfields
1997 Return the number of entity fields - NOT offsets
1998 =========
1999 */
2000 void VM_numentityfields(prvm_prog_t *prog)
2001 {
2002         PRVM_G_FLOAT(OFS_RETURN) = prog->numfielddefs;
2003 }
2004
2005 // KrimZon - DP_QC_ENTITYDATA
2006 /*
2007 =========
2008 VM_entityfieldname
2009
2010 string(float fieldnum) entityfieldname
2011 Return name of the specified field as a string, or empty if the field is invalid (warning)
2012 =========
2013 */
2014 void VM_entityfieldname(prvm_prog_t *prog)
2015 {
2016         ddef_t *d;
2017         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2018         
2019         if (i < 0 || i >= prog->numfielddefs)
2020         {
2021         VM_Warning(prog, "VM_entityfieldname: %s: field index out of bounds\n", prog->name);
2022         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
2023                 return;
2024         }
2025         
2026         d = &prog->fielddefs[i];
2027         PRVM_G_INT(OFS_RETURN) = d->s_name; // presuming that s_name points to a string already
2028 }
2029
2030 // KrimZon - DP_QC_ENTITYDATA
2031 /*
2032 =========
2033 VM_entityfieldtype
2034
2035 float(float fieldnum) entityfieldtype
2036 =========
2037 */
2038 void VM_entityfieldtype(prvm_prog_t *prog)
2039 {
2040         ddef_t *d;
2041         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2042         
2043         if (i < 0 || i >= prog->numfielddefs)
2044         {
2045                 VM_Warning(prog, "VM_entityfieldtype: %s: field index out of bounds\n", prog->name);
2046                 PRVM_G_FLOAT(OFS_RETURN) = -1.0;
2047                 return;
2048         }
2049         
2050         d = &prog->fielddefs[i];
2051         PRVM_G_FLOAT(OFS_RETURN) = (float)d->type;
2052 }
2053
2054 // KrimZon - DP_QC_ENTITYDATA
2055 /*
2056 =========
2057 VM_getentityfieldstring
2058
2059 string(float fieldnum, entity ent) getentityfieldstring
2060 =========
2061 */
2062 void VM_getentityfieldstring(prvm_prog_t *prog)
2063 {
2064         // put the data into a string
2065         ddef_t *d;
2066         int type, j;
2067         int *v;
2068         prvm_edict_t * ent;
2069         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2070         char valuebuf[MAX_INPUTLINE];
2071         
2072         if (i < 0 || i >= prog->numfielddefs)
2073         {
2074         VM_Warning(prog, "VM_entityfielddata: %s: field index out of bounds\n", prog->name);
2075                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
2076                 return;
2077         }
2078         
2079         d = &prog->fielddefs[i];
2080         
2081         // get the entity
2082         ent = PRVM_G_EDICT(OFS_PARM1);
2083         if(ent->priv.required->free)
2084         {
2085                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
2086                 VM_Warning(prog, "VM_entityfielddata: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2087                 return;
2088         }
2089         v = (int *)((char *)ent->fields.vp + d->ofs*4);
2090         
2091         // if it's 0 or blank, return an empty string
2092         type = d->type & ~DEF_SAVEGLOBAL;
2093         for (j=0 ; j<prvm_type_size[type] ; j++)
2094                 if (v[j])
2095                         break;
2096         if (j == prvm_type_size[type])
2097         {
2098                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
2099                 return;
2100         }
2101                 
2102         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, PRVM_UglyValueString(prog, (etype_t)d->type, (prvm_eval_t *)v, valuebuf, sizeof(valuebuf)));
2103 }
2104
2105 // KrimZon - DP_QC_ENTITYDATA
2106 /*
2107 =========
2108 VM_putentityfieldstring
2109
2110 float(float fieldnum, entity ent, string s) putentityfieldstring
2111 =========
2112 */
2113 void VM_putentityfieldstring(prvm_prog_t *prog)
2114 {
2115         ddef_t *d;
2116         prvm_edict_t * ent;
2117         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2118
2119         if (i < 0 || i >= prog->numfielddefs)
2120         {
2121         VM_Warning(prog, "VM_entityfielddata: %s: field index out of bounds\n", prog->name);
2122                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2123                 return;
2124         }
2125
2126         d = &prog->fielddefs[i];
2127
2128         // get the entity
2129         ent = PRVM_G_EDICT(OFS_PARM1);
2130         if(ent->priv.required->free)
2131         {
2132                 VM_Warning(prog, "VM_entityfielddata: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2133                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2134                 return;
2135         }
2136
2137         // parse the string into the value
2138         PRVM_G_FLOAT(OFS_RETURN) = ( PRVM_ED_ParseEpair(prog, ent, d, PRVM_G_STRING(OFS_PARM2), false) ) ? 1.0f : 0.0f;
2139 }
2140
2141 /*
2142 =========
2143 VM_strlen
2144
2145 float   strlen(string s)
2146 =========
2147 */
2148 //float(string s) strlen = #114; // returns how many characters are in a string
2149 void VM_strlen(prvm_prog_t *prog)
2150 {
2151         VM_SAFEPARMCOUNT(1,VM_strlen);
2152
2153         //PRVM_G_FLOAT(OFS_RETURN) = strlen(PRVM_G_STRING(OFS_PARM0));
2154         PRVM_G_FLOAT(OFS_RETURN) = u8_strlen(PRVM_G_STRING(OFS_PARM0));
2155 }
2156
2157 // DRESK - Decolorized String
2158 /*
2159 =========
2160 VM_strdecolorize
2161
2162 string  strdecolorize(string s)
2163 =========
2164 */
2165 // string (string s) strdecolorize = #472; // returns the passed in string with color codes stripped
2166 void VM_strdecolorize(prvm_prog_t *prog)
2167 {
2168         char szNewString[VM_STRINGTEMP_LENGTH];
2169         const char *szString;
2170
2171         // Prepare Strings
2172         VM_SAFEPARMCOUNT(1,VM_strdecolorize);
2173         szString = PRVM_G_STRING(OFS_PARM0);
2174         COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), TRUE);
2175         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString);
2176 }
2177
2178 // DRESK - String Length (not counting color codes)
2179 /*
2180 =========
2181 VM_strlennocol
2182
2183 float   strlennocol(string s)
2184 =========
2185 */
2186 // float(string s) strlennocol = #471; // returns how many characters are in a string not including color codes
2187 // For example, ^2Dresk returns a length of 5
2188 void VM_strlennocol(prvm_prog_t *prog)
2189 {
2190         const char *szString;
2191         int nCnt;
2192
2193         VM_SAFEPARMCOUNT(1,VM_strlennocol);
2194
2195         szString = PRVM_G_STRING(OFS_PARM0);
2196
2197         //nCnt = COM_StringLengthNoColors(szString, 0, NULL);
2198         nCnt = u8_COM_StringLengthNoColors(szString, 0, NULL);
2199
2200         PRVM_G_FLOAT(OFS_RETURN) = nCnt;
2201 }
2202
2203 // DRESK - String to Uppercase and Lowercase
2204 /*
2205 =========
2206 VM_strtolower
2207
2208 string  strtolower(string s)
2209 =========
2210 */
2211 // string (string s) strtolower = #480; // returns passed in string in lowercase form
2212 void VM_strtolower(prvm_prog_t *prog)
2213 {
2214         char szNewString[VM_STRINGTEMP_LENGTH];
2215         const char *szString;
2216
2217         // Prepare Strings
2218         VM_SAFEPARMCOUNT(1,VM_strtolower);
2219         szString = PRVM_G_STRING(OFS_PARM0);
2220
2221         COM_ToLowerString(szString, szNewString, sizeof(szNewString) );
2222
2223         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString);
2224 }
2225
2226 /*
2227 =========
2228 VM_strtoupper
2229
2230 string  strtoupper(string s)
2231 =========
2232 */
2233 // string (string s) strtoupper = #481; // returns passed in string in uppercase form
2234 void VM_strtoupper(prvm_prog_t *prog)
2235 {
2236         char szNewString[VM_STRINGTEMP_LENGTH];
2237         const char *szString;
2238
2239         // Prepare Strings
2240         VM_SAFEPARMCOUNT(1,VM_strtoupper);
2241         szString = PRVM_G_STRING(OFS_PARM0);
2242
2243         COM_ToUpperString(szString, szNewString, sizeof(szNewString) );
2244
2245         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString);
2246 }
2247
2248 /*
2249 =========
2250 VM_strcat
2251
2252 string strcat(string,string,...[string])
2253 =========
2254 */
2255 //string(string s1, string s2) strcat = #115;
2256 // concatenates two strings (for example "abc", "def" would return "abcdef")
2257 // and returns as a tempstring
2258 void VM_strcat(prvm_prog_t *prog)
2259 {
2260         char s[VM_STRINGTEMP_LENGTH];
2261         VM_SAFEPARMCOUNTRANGE(1, 8, VM_strcat);
2262
2263         VM_VarString(prog, 0, s, sizeof(s));
2264         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s);
2265 }
2266
2267 /*
2268 =========
2269 VM_substring
2270
2271 string  substring(string s, float start, float length)
2272 =========
2273 */
2274 // string(string s, float start, float length) substring = #116;
2275 // returns a section of a string as a tempstring
2276 void VM_substring(prvm_prog_t *prog)
2277 {
2278         int start, length;
2279         int u_slength = 0, u_start;
2280         size_t u_length;
2281         const char *s;
2282         char string[VM_STRINGTEMP_LENGTH];
2283
2284         VM_SAFEPARMCOUNT(3,VM_substring);
2285
2286         /*
2287         s = PRVM_G_STRING(OFS_PARM0);
2288         start = (int)PRVM_G_FLOAT(OFS_PARM1);
2289         length = (int)PRVM_G_FLOAT(OFS_PARM2);
2290         slength = strlen(s);
2291
2292         if (start < 0) // FTE_STRINGS feature
2293                 start += slength;
2294         start = bound(0, start, slength);
2295
2296         if (length < 0) // FTE_STRINGS feature
2297                 length += slength - start + 1;
2298         maxlen = min((int)sizeof(string) - 1, slength - start);
2299         length = bound(0, length, maxlen);
2300
2301         memcpy(string, s + start, length);
2302         string[length] = 0;
2303         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2304         */
2305         
2306         s = PRVM_G_STRING(OFS_PARM0);
2307         start = (int)PRVM_G_FLOAT(OFS_PARM1);
2308         length = (int)PRVM_G_FLOAT(OFS_PARM2);
2309
2310         if (start < 0) // FTE_STRINGS feature
2311         {
2312                 u_slength = u8_strlen(s);
2313                 start += u_slength;
2314                 start = bound(0, start, u_slength);
2315         }
2316
2317         if (length < 0) // FTE_STRINGS feature
2318         {
2319                 if (!u_slength) // it's not calculated when it's not needed above
2320                         u_slength = u8_strlen(s);
2321                 length += u_slength - start + 1;
2322         }
2323                 
2324         // positive start, positive length
2325         u_start = u8_byteofs(s, start, NULL);
2326         if (u_start < 0)
2327         {
2328                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
2329                 return;
2330         }
2331         u_length = u8_bytelen(s + u_start, length);
2332         if (u_length >= sizeof(string)-1)
2333                 u_length = sizeof(string)-1;
2334         
2335         memcpy(string, s + u_start, u_length);
2336         string[u_length] = 0;
2337         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2338 }
2339
2340 /*
2341 =========
2342 VM_strreplace
2343
2344 string(string search, string replace, string subject) strreplace = #484;
2345 =========
2346 */
2347 // replaces all occurrences of search with replace in the string subject, and returns the result
2348 void VM_strreplace(prvm_prog_t *prog)
2349 {
2350         int i, j, si;
2351         const char *search, *replace, *subject;
2352         char string[VM_STRINGTEMP_LENGTH];
2353         int search_len, replace_len, subject_len;
2354
2355         VM_SAFEPARMCOUNT(3,VM_strreplace);
2356
2357         search = PRVM_G_STRING(OFS_PARM0);
2358         replace = PRVM_G_STRING(OFS_PARM1);
2359         subject = PRVM_G_STRING(OFS_PARM2);
2360
2361         search_len = (int)strlen(search);
2362         replace_len = (int)strlen(replace);
2363         subject_len = (int)strlen(subject);
2364
2365         si = 0;
2366         for (i = 0; i <= subject_len - search_len; i++)
2367         {
2368                 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2369                         if (subject[i+j] != search[j])
2370                                 break;
2371                 if (j == search_len)
2372                 {
2373                         // NOTE: if search_len == 0, we always hit THIS case, and never the other
2374                         // found it at offset 'i'
2375                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2376                                 string[si++] = replace[j];
2377                         if(search_len > 0)
2378                         {
2379                                 i += search_len - 1;
2380                         }
2381                         else
2382                         {
2383                                 // the above would subtract 1 from i... so we
2384                                 // don't do that, but instead output the next
2385                                 // char
2386                                 if (si < (int)sizeof(string) - 1)
2387                                         string[si++] = subject[i];
2388                         }
2389                 }
2390                 else
2391                 {
2392                         // in THIS case, we know search_len > 0, thus i < subject_len
2393                         // not found
2394                         if (si < (int)sizeof(string) - 1)
2395                                 string[si++] = subject[i];
2396                 }
2397         }
2398         // remaining chars (these cannot match)
2399         for (; i < subject_len; i++)
2400                 if (si < (int)sizeof(string) - 1)
2401                         string[si++] = subject[i];
2402         string[si] = '\0';
2403
2404         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2405 }
2406
2407 /*
2408 =========
2409 VM_strireplace
2410
2411 string(string search, string replace, string subject) strireplace = #485;
2412 =========
2413 */
2414 // case-insensitive version of strreplace
2415 void VM_strireplace(prvm_prog_t *prog)
2416 {
2417         int i, j, si;
2418         const char *search, *replace, *subject;
2419         char string[VM_STRINGTEMP_LENGTH];
2420         int search_len, replace_len, subject_len;
2421
2422         VM_SAFEPARMCOUNT(3,VM_strreplace);
2423
2424         search = PRVM_G_STRING(OFS_PARM0);
2425         replace = PRVM_G_STRING(OFS_PARM1);
2426         subject = PRVM_G_STRING(OFS_PARM2);
2427
2428         search_len = (int)strlen(search);
2429         replace_len = (int)strlen(replace);
2430         subject_len = (int)strlen(subject);
2431
2432         si = 0;
2433         for (i = 0; i <= subject_len - search_len; i++)
2434         {
2435                 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2436                         if (tolower(subject[i+j]) != tolower(search[j]))
2437                                 break;
2438                 if (j == search_len)
2439                 {
2440                         // NOTE: if search_len == 0, we always hit THIS case, and never the other
2441                         // found it at offset 'i'
2442                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2443                                 string[si++] = replace[j];
2444                         if(search_len > 0)
2445                         {
2446                                 i += search_len - 1;
2447                         }
2448                         else
2449                         {
2450                                 // the above would subtract 1 from i... so we
2451                                 // don't do that, but instead output the next
2452                                 // char
2453                                 if (si < (int)sizeof(string) - 1)
2454                                         string[si++] = subject[i];
2455                         }
2456                 }
2457                 else
2458                 {
2459                         // in THIS case, we know search_len > 0, thus i < subject_len
2460                         // not found
2461                         if (si < (int)sizeof(string) - 1)
2462                                 string[si++] = subject[i];
2463                 }
2464         }
2465         // remaining chars (these cannot match)
2466         for (; i < subject_len; i++)
2467                 if (si < (int)sizeof(string) - 1)
2468                         string[si++] = subject[i];
2469         string[si] = '\0';
2470
2471         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2472 }
2473
2474 /*
2475 =========
2476 VM_stov
2477
2478 vector  stov(string s)
2479 =========
2480 */
2481 //vector(string s) stov = #117; // returns vector value from a string
2482 void VM_stov(prvm_prog_t *prog)
2483 {
2484         char string[VM_STRINGTEMP_LENGTH];
2485
2486         VM_SAFEPARMCOUNT(1,VM_stov);
2487
2488         VM_VarString(prog, 0, string, sizeof(string));
2489         Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
2490 }
2491
2492 /*
2493 =========
2494 VM_strzone
2495
2496 string  strzone(string s)
2497 =========
2498 */
2499 //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)
2500 void VM_strzone(prvm_prog_t *prog)
2501 {
2502         char *out;
2503         char string[VM_STRINGTEMP_LENGTH];
2504         size_t alloclen;
2505
2506         VM_SAFEPARMCOUNT(1,VM_strzone);
2507
2508         VM_VarString(prog, 0, string, sizeof(string));
2509         alloclen = strlen(string) + 1;
2510         PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(prog, alloclen, &out);
2511         memcpy(out, string, alloclen);
2512 }
2513
2514 /*
2515 =========
2516 VM_strunzone
2517
2518 strunzone(string s)
2519 =========
2520 */
2521 //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!!!)
2522 void VM_strunzone(prvm_prog_t *prog)
2523 {
2524         VM_SAFEPARMCOUNT(1,VM_strunzone);
2525         PRVM_FreeString(prog, PRVM_G_INT(OFS_PARM0));
2526 }
2527
2528 /*
2529 =========
2530 VM_command (used by client and menu)
2531
2532 clientcommand(float client, string s) (for client and menu)
2533 =========
2534 */
2535 //void(entity e, string s) clientcommand = #440; // executes a command string as if it came from the specified client
2536 //this function originally written by KrimZon, made shorter by LordHavoc
2537 void VM_clcommand (prvm_prog_t *prog)
2538 {
2539         client_t *temp_client;
2540         int i;
2541
2542         VM_SAFEPARMCOUNT(2,VM_clcommand);
2543
2544         i = (int)PRVM_G_FLOAT(OFS_PARM0);
2545         if (!sv.active  || i < 0 || i >= svs.maxclients || !svs.clients[i].active)
2546         {
2547                 VM_Warning(prog, "VM_clientcommand: %s: invalid client/server is not active !\n", prog->name);
2548                 return;
2549         }
2550
2551         temp_client = host_client;
2552         host_client = svs.clients + i;
2553         Cmd_ExecuteString (PRVM_G_STRING(OFS_PARM1), src_client, true);
2554         host_client = temp_client;
2555 }
2556
2557
2558 /*
2559 =========
2560 VM_tokenize
2561
2562 float tokenize(string s)
2563 =========
2564 */
2565 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
2566 //this function originally written by KrimZon, made shorter by LordHavoc
2567 //20040203: rewritten by LordHavoc (no longer uses allocations)
2568 static int num_tokens = 0;
2569 static int tokens[VM_STRINGTEMP_LENGTH / 2];
2570 static int tokens_startpos[VM_STRINGTEMP_LENGTH / 2];
2571 static int tokens_endpos[VM_STRINGTEMP_LENGTH / 2];
2572 static char tokenize_string[VM_STRINGTEMP_LENGTH];
2573 void VM_tokenize (prvm_prog_t *prog)
2574 {
2575         const char *p;
2576
2577         VM_SAFEPARMCOUNT(1,VM_tokenize);
2578
2579         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2580         p = tokenize_string;
2581
2582         num_tokens = 0;
2583         for(;;)
2584         {
2585                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2586                         break;
2587
2588                 // skip whitespace here to find token start pos
2589                 while(*p && ISWHITESPACE(*p))
2590                         ++p;
2591
2592                 tokens_startpos[num_tokens] = p - tokenize_string;
2593                 if(!COM_ParseToken_VM_Tokenize(&p, false))
2594                         break;
2595                 tokens_endpos[num_tokens] = p - tokenize_string;
2596                 tokens[num_tokens] = PRVM_SetTempString(prog, com_token);
2597                 ++num_tokens;
2598         }
2599
2600         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2601 }
2602
2603 //float(string s) tokenize = #514; // takes apart a string into individal words (access them with argv), returns how many
2604 void VM_tokenize_console (prvm_prog_t *prog)
2605 {
2606         const char *p;
2607
2608         VM_SAFEPARMCOUNT(1,VM_tokenize);
2609
2610         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2611         p = tokenize_string;
2612
2613         num_tokens = 0;
2614         for(;;)
2615         {
2616                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2617                         break;
2618
2619                 // skip whitespace here to find token start pos
2620                 while(*p && ISWHITESPACE(*p))
2621                         ++p;
2622
2623                 tokens_startpos[num_tokens] = p - tokenize_string;
2624                 if(!COM_ParseToken_Console(&p))
2625                         break;
2626                 tokens_endpos[num_tokens] = p - tokenize_string;
2627                 tokens[num_tokens] = PRVM_SetTempString(prog, com_token);
2628                 ++num_tokens;
2629         }
2630
2631         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2632 }
2633
2634 /*
2635 =========
2636 VM_tokenizebyseparator
2637
2638 float tokenizebyseparator(string s, string separator1, ...)
2639 =========
2640 */
2641 //float(string s, string separator1, ...) tokenizebyseparator = #479; // takes apart a string into individal words (access them with argv), returns how many
2642 //this function returns the token preceding each instance of a separator (of
2643 //which there can be multiple), and the text following the last separator
2644 //useful for parsing certain kinds of data like IP addresses
2645 //example:
2646 //numnumbers = tokenizebyseparator("10.1.2.3", ".");
2647 //returns 4 and the tokens "10" "1" "2" "3".
2648 void VM_tokenizebyseparator (prvm_prog_t *prog)
2649 {
2650         int j, k;
2651         int numseparators;
2652         int separatorlen[7];
2653         const char *separators[7];
2654         const char *p, *p0;
2655         const char *token;
2656         char tokentext[MAX_INPUTLINE];
2657
2658         VM_SAFEPARMCOUNTRANGE(2, 8,VM_tokenizebyseparator);
2659
2660         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2661         p = tokenize_string;
2662
2663         numseparators = 0;
2664         for (j = 1;j < prog->argc;j++)
2665         {
2666                 // skip any blank separator strings
2667                 const char *s = PRVM_G_STRING(OFS_PARM0+j*3);
2668                 if (!s[0])
2669                         continue;
2670                 separators[numseparators] = s;
2671                 separatorlen[numseparators] = strlen(s);
2672                 numseparators++;
2673         }
2674
2675         num_tokens = 0;
2676         j = 0;
2677
2678         while (num_tokens < (int)(sizeof(tokens)/sizeof(tokens[0])))
2679         {
2680                 token = tokentext + j;
2681                 tokens_startpos[num_tokens] = p - tokenize_string;
2682                 p0 = p;
2683                 while (*p)
2684                 {
2685                         for (k = 0;k < numseparators;k++)
2686                         {
2687                                 if (!strncmp(p, separators[k], separatorlen[k]))
2688                                 {
2689                                         p += separatorlen[k];
2690                                         break;
2691                                 }
2692                         }
2693                         if (k < numseparators)
2694                                 break;
2695                         if (j < (int)sizeof(tokentext)-1)
2696                                 tokentext[j++] = *p;
2697                         p++;
2698                         p0 = p;
2699                 }
2700                 tokens_endpos[num_tokens] = p0 - tokenize_string;
2701                 if (j >= (int)sizeof(tokentext))
2702                         break;
2703                 tokentext[j++] = 0;
2704                 tokens[num_tokens++] = PRVM_SetTempString(prog, token);
2705                 if (!*p)
2706                         break;
2707         }
2708
2709         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2710 }
2711
2712 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
2713 //this function originally written by KrimZon, made shorter by LordHavoc
2714 void VM_argv (prvm_prog_t *prog)
2715 {
2716         int token_num;
2717
2718         VM_SAFEPARMCOUNT(1,VM_argv);
2719
2720         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2721
2722         if(token_num < 0)
2723                 token_num += num_tokens;
2724
2725         if (token_num >= 0 && token_num < num_tokens)
2726                 PRVM_G_INT(OFS_RETURN) = tokens[token_num];
2727         else
2728                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2729 }
2730
2731 //float(float n) argv_start_index = #515; // returns the start index of a token
2732 void VM_argv_start_index (prvm_prog_t *prog)
2733 {
2734         int token_num;
2735
2736         VM_SAFEPARMCOUNT(1,VM_argv);
2737
2738         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2739
2740         if(token_num < 0)
2741                 token_num += num_tokens;
2742
2743         if (token_num >= 0 && token_num < num_tokens)
2744                 PRVM_G_FLOAT(OFS_RETURN) = tokens_startpos[token_num];
2745         else
2746                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2747 }
2748
2749 //float(float n) argv_end_index = #516; // returns the end index of a token
2750 void VM_argv_end_index (prvm_prog_t *prog)
2751 {
2752         int token_num;
2753
2754         VM_SAFEPARMCOUNT(1,VM_argv);
2755
2756         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2757
2758         if(token_num < 0)
2759                 token_num += num_tokens;
2760
2761         if (token_num >= 0 && token_num < num_tokens)
2762                 PRVM_G_FLOAT(OFS_RETURN) = tokens_endpos[token_num];
2763         else
2764                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2765 }
2766
2767 /*
2768 =========
2769 VM_isserver
2770
2771 float   isserver()
2772 =========
2773 */
2774 void VM_isserver(prvm_prog_t *prog)
2775 {
2776         VM_SAFEPARMCOUNT(0,VM_serverstate);
2777
2778         PRVM_G_FLOAT(OFS_RETURN) = sv.active && (svs.maxclients > 1 || cls.state == ca_dedicated);
2779 }
2780
2781 /*
2782 =========
2783 VM_clientcount
2784
2785 float   clientcount()
2786 =========
2787 */
2788 void VM_clientcount(prvm_prog_t *prog)
2789 {
2790         VM_SAFEPARMCOUNT(0,VM_clientcount);
2791
2792         PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
2793 }
2794
2795 /*
2796 =========
2797 VM_clientstate
2798
2799 float   clientstate()
2800 =========
2801 */
2802 void VM_clientstate(prvm_prog_t *prog)
2803 {
2804         VM_SAFEPARMCOUNT(0,VM_clientstate);
2805
2806
2807         switch( cls.state ) {
2808                 case ca_uninitialized:
2809                 case ca_dedicated:
2810                         PRVM_G_FLOAT(OFS_RETURN) = 0;
2811                         break;
2812                 case ca_disconnected:
2813                         PRVM_G_FLOAT(OFS_RETURN) = 1;
2814                         break;
2815                 case ca_connected:
2816                         PRVM_G_FLOAT(OFS_RETURN) = 2;
2817                         break;
2818                 default:
2819                         // should never be reached!
2820                         break;
2821         }
2822 }
2823
2824 /*
2825 =========
2826 VM_getostype
2827
2828 float   getostype(prvm_prog_t *prog)
2829 =========
2830 */ // not used at the moment -> not included in the common list
2831 void VM_getostype(prvm_prog_t *prog)
2832 {
2833         VM_SAFEPARMCOUNT(0,VM_getostype);
2834
2835         /*
2836         OS_WINDOWS
2837         OS_LINUX
2838         OS_MAC - not supported
2839         */
2840
2841 #ifdef WIN32
2842         PRVM_G_FLOAT(OFS_RETURN) = 0;
2843 #elif defined(MACOSX)
2844         PRVM_G_FLOAT(OFS_RETURN) = 2;
2845 #else
2846         PRVM_G_FLOAT(OFS_RETURN) = 1;
2847 #endif
2848 }
2849
2850 /*
2851 =========
2852 VM_gettime
2853
2854 float   gettime(prvm_prog_t *prog)
2855 =========
2856 */
2857 float CDAudio_GetPosition(void);
2858 void VM_gettime(prvm_prog_t *prog)
2859 {
2860         int timer_index;
2861
2862         VM_SAFEPARMCOUNTRANGE(0,1,VM_gettime);
2863
2864         if(prog->argc == 0)
2865         {
2866                 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2867         }
2868         else
2869         {
2870                 timer_index = (int) PRVM_G_FLOAT(OFS_PARM0);
2871                 switch(timer_index)
2872                 {
2873                         case 0: // GETTIME_FRAMESTART
2874                                 PRVM_G_FLOAT(OFS_RETURN) = realtime;
2875                                 break;
2876                         case 1: // GETTIME_REALTIME
2877                                 PRVM_G_FLOAT(OFS_RETURN) = Sys_DirtyTime();
2878                                 break;
2879                         case 2: // GETTIME_HIRES
2880                                 PRVM_G_FLOAT(OFS_RETURN) = (Sys_DirtyTime() - host_dirtytime);
2881                                 break;
2882                         case 3: // GETTIME_UPTIME
2883                                 PRVM_G_FLOAT(OFS_RETURN) = realtime;
2884                                 break;
2885                         case 4: // GETTIME_CDTRACK
2886                                 PRVM_G_FLOAT(OFS_RETURN) = CDAudio_GetPosition();
2887                                 break;
2888                         default:
2889                                 VM_Warning(prog, "VM_gettime: %s: unsupported timer specified, returning realtime\n", prog->name);
2890                                 PRVM_G_FLOAT(OFS_RETURN) = realtime;
2891                                 break;
2892                 }
2893         }
2894 }
2895
2896 /*
2897 =========
2898 VM_getsoundtime
2899
2900 float   getsoundtime(prvm_prog_t *prog)
2901 =========
2902 */
2903
2904 void VM_getsoundtime (prvm_prog_t *prog)
2905 {
2906         int entnum, entchannel;
2907         VM_SAFEPARMCOUNT(2,VM_getsoundtime);
2908
2909         if (prog == SVVM_prog)
2910                 entnum = PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
2911         else if (prog == CLVM_prog)
2912                 entnum = MAX_EDICTS + PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
2913         else
2914         {
2915                 VM_Warning(prog, "VM_getsoundtime: %s: not supported on this progs\n", prog->name);
2916                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2917                 return;
2918         }
2919         entchannel = (int)PRVM_G_FLOAT(OFS_PARM1);
2920         entchannel = CHAN_USER2ENGINE(entchannel);
2921         if (!IS_CHAN(entchannel))
2922                 VM_Warning(prog, "VM_getsoundtime: %s: bad channel %i\n", prog->name, entchannel);
2923         PRVM_G_FLOAT(OFS_RETURN) = (float)S_GetEntChannelPosition(entnum, entchannel);
2924 }
2925
2926 /*
2927 =========
2928 VM_GetSoundLen
2929
2930 string  soundlength (string sample)
2931 =========
2932 */
2933 void VM_soundlength (prvm_prog_t *prog)
2934 {
2935         const char *s;
2936
2937         VM_SAFEPARMCOUNT(1, VM_soundlength);
2938
2939         s = PRVM_G_STRING(OFS_PARM0);
2940         PRVM_G_FLOAT(OFS_RETURN) = S_SoundLength(s);
2941 }
2942
2943 /*
2944 =========
2945 VM_loadfromdata
2946
2947 loadfromdata(string data)
2948 =========
2949 */
2950 void VM_loadfromdata(prvm_prog_t *prog)
2951 {
2952         VM_SAFEPARMCOUNT(1,VM_loadentsfromfile);
2953
2954         PRVM_ED_LoadFromFile(prog, PRVM_G_STRING(OFS_PARM0));
2955 }
2956
2957 /*
2958 ========================
2959 VM_parseentitydata
2960
2961 parseentitydata(entity ent, string data)
2962 ========================
2963 */
2964 void VM_parseentitydata(prvm_prog_t *prog)
2965 {
2966         prvm_edict_t *ent;
2967         const char *data;
2968
2969         VM_SAFEPARMCOUNT(2, VM_parseentitydata);
2970
2971         // get edict and test it
2972         ent = PRVM_G_EDICT(OFS_PARM0);
2973         if (ent->priv.required->free)
2974                 prog->error_cmd("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", prog->name, PRVM_NUM_FOR_EDICT(ent));
2975
2976         data = PRVM_G_STRING(OFS_PARM1);
2977
2978         // parse the opening brace
2979         if (!COM_ParseToken_Simple(&data, false, false, true) || com_token[0] != '{' )
2980                 prog->error_cmd("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", prog->name, data );
2981
2982         PRVM_ED_ParseEdict (prog, data, ent);
2983 }
2984
2985 /*
2986 =========
2987 VM_loadfromfile
2988
2989 loadfromfile(string file)
2990 =========
2991 */
2992 void VM_loadfromfile(prvm_prog_t *prog)
2993 {
2994         const char *filename;
2995         char *data;
2996
2997         VM_SAFEPARMCOUNT(1,VM_loadfromfile);
2998
2999         filename = PRVM_G_STRING(OFS_PARM0);
3000         if (FS_CheckNastyPath(filename, false))
3001         {
3002                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3003                 VM_Warning(prog, "VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", prog->name, filename);
3004                 return;
3005         }
3006
3007         // not conform with VM_fopen
3008         data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
3009         if (data == NULL)
3010                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3011
3012         PRVM_ED_LoadFromFile(prog, data);
3013
3014         if(data)
3015                 Mem_Free(data);
3016 }
3017
3018
3019 /*
3020 =========
3021 VM_modulo
3022
3023 float   mod(float val, float m)
3024 =========
3025 */
3026 void VM_modulo(prvm_prog_t *prog)
3027 {
3028         int val, m;
3029         VM_SAFEPARMCOUNT(2,VM_module);
3030
3031         val = (int) PRVM_G_FLOAT(OFS_PARM0);
3032         m       = (int) PRVM_G_FLOAT(OFS_PARM1);
3033
3034         PRVM_G_FLOAT(OFS_RETURN) = (float) (val % m);
3035 }
3036
3037 static void VM_Search_Init(prvm_prog_t *prog)
3038 {
3039         int i;
3040         for (i = 0;i < PRVM_MAX_OPENSEARCHES;i++)
3041                 prog->opensearches[i] = NULL;
3042 }
3043
3044 static void VM_Search_Reset(prvm_prog_t *prog)
3045 {
3046         int i;
3047         // reset the fssearch list
3048         for(i = 0; i < PRVM_MAX_OPENSEARCHES; i++)
3049         {
3050                 if(prog->opensearches[i])
3051                         FS_FreeSearch(prog->opensearches[i]);
3052                 prog->opensearches[i] = NULL;
3053         }
3054 }
3055
3056 /*
3057 =========
3058 VM_search_begin
3059
3060 float search_begin(string pattern, float caseinsensitive, float quiet)
3061 =========
3062 */
3063 void VM_search_begin(prvm_prog_t *prog)
3064 {
3065         int handle;
3066         const char *pattern;
3067         int caseinsens, quiet;
3068
3069         VM_SAFEPARMCOUNT(3, VM_search_begin);
3070
3071         pattern = PRVM_G_STRING(OFS_PARM0);
3072
3073         VM_CheckEmptyString(prog, pattern);
3074
3075         caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
3076         quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
3077
3078         for(handle = 0; handle < PRVM_MAX_OPENSEARCHES; handle++)
3079                 if(!prog->opensearches[handle])
3080                         break;
3081
3082         if(handle >= PRVM_MAX_OPENSEARCHES)
3083         {
3084                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3085                 VM_Warning(prog, "VM_search_begin: %s ran out of search handles (%i)\n", prog->name, PRVM_MAX_OPENSEARCHES);
3086                 return;
3087         }
3088
3089         if(!(prog->opensearches[handle] = FS_Search(pattern,caseinsens, quiet)))
3090                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3091         else
3092         {
3093                 prog->opensearches_origin[handle] = PRVM_AllocationOrigin(prog);
3094                 PRVM_G_FLOAT(OFS_RETURN) = handle;
3095         }
3096 }
3097
3098 /*
3099 =========
3100 VM_search_end
3101
3102 void    search_end(float handle)
3103 =========
3104 */
3105 void VM_search_end(prvm_prog_t *prog)
3106 {
3107         int handle;
3108         VM_SAFEPARMCOUNT(1, VM_search_end);
3109
3110         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3111
3112         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3113         {
3114                 VM_Warning(prog, "VM_search_end: invalid handle %i used in %s\n", handle, prog->name);
3115                 return;
3116         }
3117         if(prog->opensearches[handle] == NULL)
3118         {
3119                 VM_Warning(prog, "VM_search_end: no such handle %i in %s\n", handle, prog->name);
3120                 return;
3121         }
3122
3123         FS_FreeSearch(prog->opensearches[handle]);
3124         prog->opensearches[handle] = NULL;
3125         if(prog->opensearches_origin[handle])
3126                 PRVM_Free((char *)prog->opensearches_origin[handle]);
3127 }
3128
3129 /*
3130 =========
3131 VM_search_getsize
3132
3133 float   search_getsize(float handle)
3134 =========
3135 */
3136 void VM_search_getsize(prvm_prog_t *prog)
3137 {
3138         int handle;
3139         VM_SAFEPARMCOUNT(1, VM_M_search_getsize);
3140
3141         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3142
3143         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3144         {
3145                 VM_Warning(prog, "VM_search_getsize: invalid handle %i used in %s\n", handle, prog->name);
3146                 return;
3147         }
3148         if(prog->opensearches[handle] == NULL)
3149         {
3150                 VM_Warning(prog, "VM_search_getsize: no such handle %i in %s\n", handle, prog->name);
3151                 return;
3152         }
3153
3154         PRVM_G_FLOAT(OFS_RETURN) = prog->opensearches[handle]->numfilenames;
3155 }
3156
3157 /*
3158 =========
3159 VM_search_getfilename
3160
3161 string  search_getfilename(float handle, float num)
3162 =========
3163 */
3164 void VM_search_getfilename(prvm_prog_t *prog)
3165 {
3166         int handle, filenum;
3167         VM_SAFEPARMCOUNT(2, VM_search_getfilename);
3168
3169         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3170         filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
3171
3172         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3173         {
3174                 VM_Warning(prog, "VM_search_getfilename: invalid handle %i used in %s\n", handle, prog->name);
3175                 return;
3176         }
3177         if(prog->opensearches[handle] == NULL)
3178         {
3179                 VM_Warning(prog, "VM_search_getfilename: no such handle %i in %s\n", handle, prog->name);
3180                 return;
3181         }
3182         if(filenum < 0 || filenum >= prog->opensearches[handle]->numfilenames)
3183         {
3184                 VM_Warning(prog, "VM_search_getfilename: invalid filenum %i in %s\n", filenum, prog->name);
3185                 return;
3186         }
3187
3188         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, prog->opensearches[handle]->filenames[filenum]);
3189 }
3190
3191 /*
3192 =========
3193 VM_chr
3194
3195 string  chr(float ascii)
3196 =========
3197 */
3198 void VM_chr(prvm_prog_t *prog)
3199 {
3200         /*
3201         char tmp[2];
3202         VM_SAFEPARMCOUNT(1, VM_chr);
3203
3204         tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
3205         tmp[1] = 0;
3206
3207         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, tmp);
3208         */
3209         
3210         char tmp[8];
3211         int len;
3212         VM_SAFEPARMCOUNT(1, VM_chr);
3213
3214         len = u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0), tmp, sizeof(tmp));
3215         tmp[len] = 0;
3216         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, tmp);
3217 }
3218
3219 //=============================================================================
3220 // Draw builtins (client & menu)
3221
3222 /*
3223 =========
3224 VM_iscachedpic
3225
3226 float   iscachedpic(string pic)
3227 =========
3228 */
3229 void VM_iscachedpic(prvm_prog_t *prog)
3230 {
3231         VM_SAFEPARMCOUNT(1,VM_iscachedpic);
3232
3233         // drawq hasnt such a function, thus always return true
3234         PRVM_G_FLOAT(OFS_RETURN) = false;
3235 }
3236
3237 /*
3238 =========
3239 VM_precache_pic
3240
3241 string  precache_pic(string pic)
3242 =========
3243 */
3244 void VM_precache_pic(prvm_prog_t *prog)
3245 {
3246         const char      *s;
3247
3248         VM_SAFEPARMCOUNT(1, VM_precache_pic);
3249
3250         s = PRVM_G_STRING(OFS_PARM0);
3251         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
3252         VM_CheckEmptyString(prog, s);
3253
3254         // AK Draw_CachePic is supposed to always return a valid pointer
3255         if( Draw_CachePic_Flags(s, 0)->tex == r_texture_notexture )
3256                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
3257 }
3258
3259 /*
3260 =========
3261 VM_freepic
3262
3263 freepic(string s)
3264 =========
3265 */
3266 void VM_freepic(prvm_prog_t *prog)
3267 {
3268         const char *s;
3269
3270         VM_SAFEPARMCOUNT(1,VM_freepic);
3271
3272         s = PRVM_G_STRING(OFS_PARM0);
3273         VM_CheckEmptyString(prog, s);
3274
3275         Draw_FreePic(s);
3276 }
3277
3278 static void getdrawfontscale(prvm_prog_t *prog, float *sx, float *sy)
3279 {
3280         vec3_t v;
3281         *sx = *sy = 1;
3282         VectorCopy(PRVM_drawglobalvector(drawfontscale), v);
3283         if(VectorLength2(v) > 0)
3284         {
3285                 *sx = v[0];
3286                 *sy = v[1];
3287         }
3288 }
3289
3290 static dp_font_t *getdrawfont(prvm_prog_t *prog)
3291 {
3292         int f = (int) PRVM_drawglobalfloat(drawfont);
3293         if(f < 0 || f >= dp_fonts.maxsize)
3294                 return FONT_DEFAULT;
3295         return &dp_fonts.f[f];
3296 }
3297
3298 /*
3299 =========
3300 VM_drawcharacter
3301
3302 float   drawcharacter(vector position, float character, vector scale, vector rgb, float alpha, float flag)
3303 =========
3304 */
3305 void VM_drawcharacter(prvm_prog_t *prog)
3306 {
3307         float *pos,*scale,*rgb;
3308         char   character;
3309         int flag;
3310         float sx, sy;
3311         VM_SAFEPARMCOUNT(6,VM_drawcharacter);
3312
3313         character = (char) PRVM_G_FLOAT(OFS_PARM1);
3314         if(character == 0)
3315         {
3316                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3317                 VM_Warning(prog, "VM_drawcharacter: %s passed null character !\n",prog->name);
3318                 return;
3319         }
3320
3321         pos = PRVM_G_VECTOR(OFS_PARM0);
3322         scale = PRVM_G_VECTOR(OFS_PARM2);
3323         rgb = PRVM_G_VECTOR(OFS_PARM3);
3324         flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3325
3326         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3327         {
3328                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3329                 VM_Warning(prog, "VM_drawcharacter: %s: wrong DRAWFLAG %i !\n",prog->name,flag);
3330                 return;
3331         }
3332
3333         if(pos[2] || scale[2])
3334                 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")));
3335
3336         if(!scale[0] || !scale[1])
3337         {
3338                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3339                 VM_Warning(prog, "VM_drawcharacter: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3340                 return;
3341         }
3342
3343         getdrawfontscale(prog, &sx, &sy);
3344         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));
3345         PRVM_G_FLOAT(OFS_RETURN) = 1;
3346 }
3347
3348 /*
3349 =========
3350 VM_drawstring
3351
3352 float   drawstring(vector position, string text, vector scale, vector rgb, float alpha[, float flag])
3353 =========
3354 */
3355 void VM_drawstring(prvm_prog_t *prog)
3356 {
3357         float *pos,*scale,*rgb;
3358         const char  *string;
3359         int flag = 0;
3360         float sx, sy;
3361         VM_SAFEPARMCOUNTRANGE(5,6,VM_drawstring);
3362
3363         string = PRVM_G_STRING(OFS_PARM1);
3364         pos = PRVM_G_VECTOR(OFS_PARM0);
3365         scale = PRVM_G_VECTOR(OFS_PARM2);
3366         rgb = PRVM_G_VECTOR(OFS_PARM3);
3367         if (prog->argc >= 6)
3368                 flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3369
3370         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3371         {
3372                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3373                 VM_Warning(prog, "VM_drawstring: %s: wrong DRAWFLAG %i !\n",prog->name,flag);
3374                 return;
3375         }
3376
3377         if(!scale[0] || !scale[1])
3378         {
3379                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3380                 VM_Warning(prog, "VM_drawstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3381                 return;
3382         }
3383
3384         if(pos[2] || scale[2])
3385                 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")));
3386
3387         getdrawfontscale(prog, &sx, &sy);
3388         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));
3389         //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);
3390         PRVM_G_FLOAT(OFS_RETURN) = 1;
3391 }
3392
3393 /*
3394 =========
3395 VM_drawcolorcodedstring
3396
3397 float   drawcolorcodedstring(vector position, string text, vector scale, float alpha, float flag)
3398 /
3399 float   drawcolorcodedstring(vector position, string text, vector scale, vector rgb, float alpha, float flag)
3400 =========
3401 */
3402 void VM_drawcolorcodedstring(prvm_prog_t *prog)
3403 {
3404         float *pos, *scale;
3405         const char  *string;
3406         int flag;
3407         vec3_t rgb;
3408         float sx, sy, alpha;
3409
3410         VM_SAFEPARMCOUNTRANGE(5,6,VM_drawcolorcodedstring);
3411
3412         if (prog->argc == 6) // full 6 parms, like normal drawstring
3413         {
3414                 pos = PRVM_G_VECTOR(OFS_PARM0);
3415                 string = PRVM_G_STRING(OFS_PARM1);
3416                 scale = PRVM_G_VECTOR(OFS_PARM2);
3417                 VectorCopy(PRVM_G_VECTOR(OFS_PARM3), rgb); 
3418                 alpha = PRVM_G_FLOAT(OFS_PARM4);
3419                 flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3420         }
3421         else
3422         {
3423                 pos = PRVM_G_VECTOR(OFS_PARM0);
3424                 string = PRVM_G_STRING(OFS_PARM1);
3425                 scale = PRVM_G_VECTOR(OFS_PARM2);
3426                 rgb[0] = 1.0;
3427                 rgb[1] = 1.0;
3428                 rgb[2] = 1.0;
3429                 alpha = PRVM_G_FLOAT(OFS_PARM3);
3430                 flag = (int)PRVM_G_FLOAT(OFS_PARM4);
3431         }
3432
3433         if(flag < DRAWFLAG_NORMAL || flag >= DRAWFLAG_NUMFLAGS)
3434         {
3435                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3436                 VM_Warning(prog, "VM_drawcolorcodedstring: %s: wrong DRAWFLAG %i !\n",prog->name,flag);
3437                 return;
3438         }
3439
3440         if(!scale[0] || !scale[1])
3441         {
3442                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3443                 VM_Warning(prog, "VM_drawcolorcodedstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3444                 return;
3445         }
3446
3447         if(pos[2] || scale[2])
3448                 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")));
3449
3450         getdrawfontscale(prog, &sx, &sy);
3451         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));
3452         if (prog->argc == 6) // also return vector of last color
3453                 VectorCopy(DrawQ_Color, PRVM_G_VECTOR(OFS_RETURN));
3454         else
3455                 PRVM_G_FLOAT(OFS_RETURN) = 1;
3456 }
3457 /*
3458 =========
3459 VM_stringwidth
3460
3461 float   stringwidth(string text, float allowColorCodes, float size)
3462 =========
3463 */
3464 void VM_stringwidth(prvm_prog_t *prog)
3465 {
3466         const char  *string;
3467         float *szv;
3468         float mult; // sz is intended font size so we can later add freetype support, mult is font size multiplier in pixels per character cell
3469         int colors;
3470         float sx, sy;
3471         size_t maxlen = 0;
3472         VM_SAFEPARMCOUNTRANGE(2,3,VM_drawstring);
3473
3474         getdrawfontscale(prog, &sx, &sy);
3475         if(prog->argc == 3)
3476         {
3477                 szv = PRVM_G_VECTOR(OFS_PARM2);
3478                 mult = 1;
3479         }
3480         else
3481         {
3482                 // we want the width for 8x8 font size, divided by 8
3483                 static float defsize[] = {8, 8};
3484                 szv = defsize;
3485                 mult = 0.125;
3486                 // to make sure snapping is turned off, ALWAYS use a nontrivial scale in this case
3487                 if(sx >= 0.9 && sx <= 1.1)
3488                 {
3489                         mult *= 2;
3490                         sx /= 2;
3491                         sy /= 2;
3492                 }
3493         }
3494
3495         string = PRVM_G_STRING(OFS_PARM0);
3496         colors = (int)PRVM_G_FLOAT(OFS_PARM1);
3497
3498         PRVM_G_FLOAT(OFS_RETURN) = DrawQ_TextWidth_UntilWidth_TrackColors_Scale(string, &maxlen, szv[0], szv[1], sx, sy, NULL, !colors, getdrawfont(prog), 1000000000) * mult;
3499 /*
3500         if(prog->argc == 3)
3501         {
3502                 mult = sz = PRVM_G_FLOAT(OFS_PARM2);
3503         }
3504         else
3505         {
3506                 sz = 8;
3507                 mult = 1;
3508         }
3509
3510         string = PRVM_G_STRING(OFS_PARM0);
3511         colors = (int)PRVM_G_FLOAT(OFS_PARM1);
3512
3513         PRVM_G_FLOAT(OFS_RETURN) = DrawQ_TextWidth(string, 0, !colors, getdrawfont()) * mult; // 1x1 characters, don't actually draw
3514 */
3515 }
3516
3517 /*
3518 =========
3519 VM_findfont
3520
3521 float findfont(string s)
3522 =========
3523 */
3524
3525 static float getdrawfontnum(const char *fontname)
3526 {
3527         int i;
3528
3529         for(i = 0; i < dp_fonts.maxsize; ++i)
3530                 if(!strcmp(dp_fonts.f[i].title, fontname))
3531                         return i;
3532         return -1;
3533 }
3534
3535 void VM_findfont(prvm_prog_t *prog)
3536 {
3537         VM_SAFEPARMCOUNT(1,VM_findfont);
3538         PRVM_G_FLOAT(OFS_RETURN) = getdrawfontnum(PRVM_G_STRING(OFS_PARM0));
3539 }
3540
3541 /*
3542 =========
3543 VM_loadfont
3544
3545 float loadfont(string fontname, string fontmaps, string sizes, float slot)
3546 =========
3547 */
3548
3549 void VM_loadfont(prvm_prog_t *prog)
3550 {
3551         const char *fontname, *filelist, *sizes, *c, *cm;
3552         char mainfont[MAX_QPATH];
3553         int i, numsizes;
3554         float sz, scale, voffset;
3555         dp_font_t *f;
3556
3557         VM_SAFEPARMCOUNTRANGE(3,6,VM_loadfont);
3558
3559         fontname = PRVM_G_STRING(OFS_PARM0);
3560         if (!fontname[0])
3561                 fontname = "default";
3562
3563         filelist = PRVM_G_STRING(OFS_PARM1);
3564         if (!filelist[0])
3565                 filelist = "gfx/conchars";
3566
3567         sizes = PRVM_G_STRING(OFS_PARM2);
3568         if (!sizes[0])
3569                 sizes = "10";
3570
3571         // find a font
3572         f = NULL;
3573         if (prog->argc >= 4)
3574         {
3575                 i = PRVM_G_FLOAT(OFS_PARM3);
3576                 if (i >= 0 && i < dp_fonts.maxsize)
3577                 {
3578                         f = &dp_fonts.f[i];
3579                         strlcpy(f->title, fontname, sizeof(f->title)); // replace name
3580                 }
3581         }
3582         if (!f)
3583                 f = FindFont(fontname, true);
3584         if (!f)
3585         {
3586                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3587                 return; // something go wrong
3588         }
3589
3590         memset(f->fallbacks, 0, sizeof(f->fallbacks));
3591         memset(f->fallback_faces, 0, sizeof(f->fallback_faces));
3592
3593         // first font is handled "normally"
3594         c = strchr(filelist, ':');
3595         cm = strchr(filelist, ',');
3596         if(c && (!cm || c < cm))
3597                 f->req_face = atoi(c+1);
3598         else
3599         {
3600                 f->req_face = 0;
3601                 c = cm;
3602         }
3603         if(!c || (c - filelist) > MAX_QPATH)
3604                 strlcpy(mainfont, filelist, sizeof(mainfont));
3605         else
3606         {
3607                 memcpy(mainfont, filelist, c - filelist);
3608                 mainfont[c - filelist] = 0;
3609         }
3610
3611         // handle fallbacks
3612         for(i = 0; i < MAX_FONT_FALLBACKS; ++i)
3613         {
3614                 c = strchr(filelist, ',');
3615                 if(!c)
3616                         break;
3617                 filelist = c + 1;
3618                 if(!*filelist)
3619                         break;
3620                 c = strchr(filelist, ':');
3621                 cm = strchr(filelist, ',');
3622                 if(c && (!cm || c < cm))
3623                         f->fallback_faces[i] = atoi(c+1);
3624                 else
3625                 {
3626                         f->fallback_faces[i] = 0; // f->req_face; could make it stick to the default-font's face index
3627                         c = cm;
3628                 }
3629                 if(!c || (c-filelist) > MAX_QPATH)
3630                 {
3631                         strlcpy(f->fallbacks[i], filelist, sizeof(mainfont));
3632                 }
3633                 else
3634                 {
3635                         memcpy(f->fallbacks[i], filelist, c - filelist);
3636                         f->fallbacks[i][c - filelist] = 0;
3637                 }
3638         }
3639
3640         // handle sizes
3641         for(i = 0; i < MAX_FONT_SIZES; ++i)
3642                 f->req_sizes[i] = -1;
3643         for (numsizes = 0,c = sizes;;)
3644         {
3645                 if (!COM_ParseToken_VM_Tokenize(&c, 0))
3646                         break;
3647                 sz = atof(com_token);
3648                 // detect crap size
3649                 if (sz < 0.001f || sz > 1000.0f)
3650                 {
3651                         VM_Warning(prog, "VM_loadfont: crap size %s", com_token);
3652                         continue;
3653                 }
3654                 // check overflow
3655                 if (numsizes == MAX_FONT_SIZES)
3656                 {
3657                         VM_Warning(prog, "VM_loadfont: MAX_FONT_SIZES = %i exceeded", MAX_FONT_SIZES);
3658                         break;
3659                 }
3660                 f->req_sizes[numsizes] = sz;
3661                 numsizes++;
3662         }
3663
3664         // additional scale/hoffset parms
3665         scale = 1;
3666         voffset = 0;
3667         if (prog->argc >= 5)
3668         {
3669                 scale = PRVM_G_FLOAT(OFS_PARM4);
3670                 if (scale <= 0)
3671                         scale = 1;
3672         }
3673         if (prog->argc >= 6)
3674                 voffset = PRVM_G_FLOAT(OFS_PARM5);
3675
3676         // load
3677         LoadFont(true, mainfont, f, scale, voffset);
3678
3679         // return index of loaded font
3680         PRVM_G_FLOAT(OFS_RETURN) = (f - dp_fonts.f);
3681 }
3682
3683 /*
3684 =========
3685 VM_drawpic
3686
3687 float   drawpic(vector position, string pic, vector size, vector rgb, float alpha, float flag)
3688 =========
3689 */
3690 void VM_drawpic(prvm_prog_t *prog)
3691 {
3692         const char *picname;
3693         float *size, *pos, *rgb;
3694         int flag = 0;
3695
3696         VM_SAFEPARMCOUNTRANGE(5,6,VM_drawpic);
3697
3698         picname = PRVM_G_STRING(OFS_PARM1);
3699         VM_CheckEmptyString(prog, picname);
3700
3701         // is pic cached ? no function yet for that
3702         if(!1)
3703         {
3704                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3705                 VM_Warning(prog, "VM_drawpic: %s: %s not cached !\n", prog->name, picname);
3706                 return;
3707         }
3708
3709         pos = PRVM_G_VECTOR(OFS_PARM0);
3710         size = PRVM_G_VECTOR(OFS_PARM2);
3711         rgb = PRVM_G_VECTOR(OFS_PARM3);
3712         if (prog->argc >= 6)
3713                 flag = (int) PRVM_G_FLOAT(OFS_PARM5);
3714
3715         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3716         {
3717                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3718                 VM_Warning(prog, "VM_drawpic: %s: wrong DRAWFLAG %i !\n",prog->name,flag);
3719                 return;
3720         }
3721
3722         if(pos[2] || size[2])
3723                 VM_Warning(prog, "VM_drawpic: z value%s from %s discarded\n",(pos[2] && size[2]) ? "s" : " ",((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
3724
3725         DrawQ_Pic(pos[0], pos[1], Draw_CachePic_Flags (picname, CACHEPICFLAG_NOTPERSISTENT), size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag);
3726         PRVM_G_FLOAT(OFS_RETURN) = 1;
3727 }
3728 /*
3729 =========
3730 VM_drawrotpic
3731
3732 float   drawrotpic(vector position, string pic, vector size, vector org, float angle, vector rgb, float alpha, float flag)
3733 =========
3734 */
3735 void VM_drawrotpic(prvm_prog_t *prog)
3736 {
3737         const char *picname;
3738         float *size, *pos, *org, *rgb;
3739         int flag;
3740
3741         VM_SAFEPARMCOUNT(8,VM_drawrotpic);
3742
3743         picname = PRVM_G_STRING(OFS_PARM1);
3744         VM_CheckEmptyString(prog, picname);
3745
3746         // is pic cached ? no function yet for that
3747         if(!1)
3748         {
3749                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3750                 VM_Warning(prog, "VM_drawrotpic: %s: %s not cached !\n", prog->name, picname);
3751                 return;
3752         }
3753
3754         pos = PRVM_G_VECTOR(OFS_PARM0);
3755         size = PRVM_G_VECTOR(OFS_PARM2);
3756         org = PRVM_G_VECTOR(OFS_PARM3);
3757         rgb = PRVM_G_VECTOR(OFS_PARM5);
3758         flag = (int) PRVM_G_FLOAT(OFS_PARM7);
3759
3760         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3761         {
3762                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3763                 VM_Warning(prog, "VM_drawrotpic: %s: wrong DRAWFLAG %i !\n",prog->name,flag);
3764                 return;
3765         }
3766
3767         if(pos[2] || size[2] || org[2])
3768                 VM_Warning(prog, "VM_drawrotpic: z value from pos/size/org discarded\n");
3769
3770         DrawQ_RotPic(pos[0], pos[1], Draw_CachePic_Flags(picname, CACHEPICFLAG_NOTPERSISTENT), size[0], size[1], org[0], org[1], PRVM_G_FLOAT(OFS_PARM4), rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM6), flag);
3771         PRVM_G_FLOAT(OFS_RETURN) = 1;
3772 }
3773 /*
3774 =========
3775 VM_drawsubpic
3776
3777 float   drawsubpic(vector position, vector size, string pic, vector srcPos, vector srcSize, vector rgb, float alpha, float flag)
3778
3779 =========
3780 */
3781 void VM_drawsubpic(prvm_prog_t *prog)
3782 {
3783         const char *picname;
3784         float *size, *pos, *rgb, *srcPos, *srcSize, alpha;
3785         int flag;
3786
3787         VM_SAFEPARMCOUNT(8,VM_drawsubpic);
3788
3789         picname = PRVM_G_STRING(OFS_PARM2);
3790         VM_CheckEmptyString(prog, picname);
3791
3792         // is pic cached ? no function yet for that
3793         if(!1)
3794         {
3795                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3796                 VM_Warning(prog, "VM_drawsubpic: %s: %s not cached !\n", prog->name, picname);
3797                 return;
3798         }
3799
3800         pos = PRVM_G_VECTOR(OFS_PARM0);
3801         size = PRVM_G_VECTOR(OFS_PARM1);
3802         srcPos = PRVM_G_VECTOR(OFS_PARM3);
3803         srcSize = PRVM_G_VECTOR(OFS_PARM4);
3804         rgb = PRVM_G_VECTOR(OFS_PARM5);
3805         alpha = PRVM_G_FLOAT(OFS_PARM6);
3806         flag = (int) PRVM_G_FLOAT(OFS_PARM7);
3807
3808         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3809         {
3810                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3811                 VM_Warning(prog, "VM_drawsubpic: %s: wrong DRAWFLAG %i !\n",prog->name,flag);
3812                 return;
3813         }
3814
3815         if(pos[2] || size[2])
3816                 VM_Warning(prog, "VM_drawsubpic: z value%s from %s discarded\n",(pos[2] && size[2]) ? "s" : " ",((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
3817
3818         DrawQ_SuperPic(pos[0], pos[1], Draw_CachePic_Flags (picname, CACHEPICFLAG_NOTPERSISTENT),
3819                 size[0], size[1],
3820                 srcPos[0],              srcPos[1],              rgb[0], rgb[1], rgb[2], alpha,
3821                 srcPos[0] + srcSize[0], srcPos[1],              rgb[0], rgb[1], rgb[2], alpha,
3822                 srcPos[0],              srcPos[1] + srcSize[1], rgb[0], rgb[1], rgb[2], alpha,
3823                 srcPos[0] + srcSize[0], srcPos[1] + srcSize[1], rgb[0], rgb[1], rgb[2], alpha,
3824                 flag);
3825         PRVM_G_FLOAT(OFS_RETURN) = 1;
3826 }
3827
3828 /*
3829 =========
3830 VM_drawfill
3831
3832 float drawfill(vector position, vector size, vector rgb, float alpha, float flag)
3833 =========
3834 */
3835 void VM_drawfill(prvm_prog_t *prog)
3836 {
3837         float *size, *pos, *rgb;
3838         int flag;
3839
3840         VM_SAFEPARMCOUNT(5,VM_drawfill);
3841
3842
3843         pos = PRVM_G_VECTOR(OFS_PARM0);
3844         size = PRVM_G_VECTOR(OFS_PARM1);
3845         rgb = PRVM_G_VECTOR(OFS_PARM2);
3846         flag = (int) PRVM_G_FLOAT(OFS_PARM4);
3847
3848         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3849         {
3850                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3851                 VM_Warning(prog, "VM_drawfill: %s: wrong DRAWFLAG %i !\n",prog->name,flag);
3852                 return;
3853         }
3854
3855         if(pos[2] || size[2])
3856                 VM_Warning(prog, "VM_drawfill: z value%s from %s discarded\n",(pos[2] && size[2]) ? "s" : " ",((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
3857
3858         DrawQ_Fill(pos[0], pos[1], size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM3), flag);
3859         PRVM_G_FLOAT(OFS_RETURN) = 1;
3860 }
3861
3862 /*
3863 =========
3864 VM_drawsetcliparea
3865
3866 drawsetcliparea(float x, float y, float width, float height)
3867 =========
3868 */
3869 void VM_drawsetcliparea(prvm_prog_t *prog)
3870 {
3871         float x,y,w,h;
3872         VM_SAFEPARMCOUNT(4,VM_drawsetcliparea);
3873
3874         x = bound(0, PRVM_G_FLOAT(OFS_PARM0), vid_conwidth.integer);
3875         y = bound(0, PRVM_G_FLOAT(OFS_PARM1), vid_conheight.integer);
3876         w = bound(0, PRVM_G_FLOAT(OFS_PARM2) + PRVM_G_FLOAT(OFS_PARM0) - x, (vid_conwidth.integer  - x));
3877         h = bound(0, PRVM_G_FLOAT(OFS_PARM3) + PRVM_G_FLOAT(OFS_PARM1) - y, (vid_conheight.integer - y));
3878
3879         DrawQ_SetClipArea(x, y, w, h);
3880 }
3881
3882 /*
3883 =========
3884 VM_drawresetcliparea
3885
3886 drawresetcliparea()
3887 =========
3888 */
3889 void VM_drawresetcliparea(prvm_prog_t *prog)
3890 {
3891         VM_SAFEPARMCOUNT(0,VM_drawresetcliparea);
3892
3893         DrawQ_ResetClipArea();
3894 }
3895
3896 /*
3897 =========
3898 VM_getimagesize
3899
3900 vector  getimagesize(string pic)
3901 =========
3902 */
3903 void VM_getimagesize(prvm_prog_t *prog)
3904 {
3905         const char *p;
3906         cachepic_t *pic;
3907
3908         VM_SAFEPARMCOUNT(1,VM_getimagesize);
3909
3910         p = PRVM_G_STRING(OFS_PARM0);
3911         VM_CheckEmptyString(prog, p);
3912
3913         pic = Draw_CachePic_Flags (p, CACHEPICFLAG_NOTPERSISTENT);
3914         if( pic->tex == r_texture_notexture )
3915         {
3916                 PRVM_G_VECTOR(OFS_RETURN)[0] = 0;
3917                 PRVM_G_VECTOR(OFS_RETURN)[1] = 0;
3918         }
3919         else
3920         {
3921                 PRVM_G_VECTOR(OFS_RETURN)[0] = pic->width;
3922                 PRVM_G_VECTOR(OFS_RETURN)[1] = pic->height;
3923         }
3924         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
3925 }
3926
3927 /*
3928 =========
3929 VM_keynumtostring
3930
3931 string keynumtostring(float keynum)
3932 =========
3933 */
3934 void VM_keynumtostring (prvm_prog_t *prog)
3935 {
3936         char tinystr[2];
3937         VM_SAFEPARMCOUNT(1, VM_keynumtostring);
3938
3939         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, Key_KeynumToString((int)PRVM_G_FLOAT(OFS_PARM0), tinystr, sizeof(tinystr)));
3940 }
3941
3942 /*
3943 =========
3944 VM_findkeysforcommand
3945
3946 string  findkeysforcommand(string command, float bindmap)
3947
3948 the returned string is an altstring
3949 =========
3950 */
3951 #define FKFC_NUMKEYS 5
3952 void M_FindKeysForCommand(const char *command, int *keys);
3953 void VM_findkeysforcommand(prvm_prog_t *prog)
3954 {
3955         const char *cmd;
3956         char ret[VM_STRINGTEMP_LENGTH];
3957         int keys[FKFC_NUMKEYS];
3958         int i;
3959         int bindmap;
3960         char vabuf[1024];
3961
3962         VM_SAFEPARMCOUNTRANGE(1, 2, VM_findkeysforcommand);
3963
3964         cmd = PRVM_G_STRING(OFS_PARM0);
3965         if(prog->argc == 2)
3966                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3967         else
3968                 bindmap = 0; // consistent to "bind"
3969
3970         VM_CheckEmptyString(prog, cmd);
3971
3972         Key_FindKeysForCommand(cmd, keys, FKFC_NUMKEYS, bindmap);
3973
3974         ret[0] = 0;
3975         for(i = 0; i < FKFC_NUMKEYS; i++)
3976                 strlcat(ret, va(vabuf, sizeof(vabuf), " \'%i\'", keys[i]), sizeof(ret));
3977
3978         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, ret);
3979 }
3980
3981 /*
3982 =========
3983 VM_stringtokeynum
3984
3985 float stringtokeynum(string key)
3986 =========
3987 */
3988 void VM_stringtokeynum (prvm_prog_t *prog)
3989 {
3990         VM_SAFEPARMCOUNT( 1, VM_keynumtostring );
3991
3992         PRVM_G_FLOAT(OFS_RETURN) = Key_StringToKeynum(PRVM_G_STRING(OFS_PARM0));
3993 }
3994
3995 /*
3996 =========
3997 VM_getkeybind
3998
3999 string getkeybind(float key, float bindmap)
4000 =========
4001 */
4002 void VM_getkeybind (prvm_prog_t *prog)
4003 {
4004         int bindmap;
4005         VM_SAFEPARMCOUNTRANGE(1, 2, VM_CL_getkeybind);
4006         if(prog->argc == 2)
4007                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
4008         else
4009                 bindmap = 0; // consistent to "bind"
4010
4011         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, Key_GetBind((int)PRVM_G_FLOAT(OFS_PARM0), bindmap));
4012 }
4013
4014 /*
4015 =========
4016 VM_setkeybind
4017
4018 float setkeybind(float key, string cmd, float bindmap)
4019 =========
4020 */
4021 void VM_setkeybind (prvm_prog_t *prog)
4022 {
4023         int bindmap;
4024         VM_SAFEPARMCOUNTRANGE(2, 3, VM_CL_setkeybind);
4025         if(prog->argc == 3)
4026                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM2), MAX_BINDMAPS-1);
4027         else
4028                 bindmap = 0; // consistent to "bind"
4029
4030         PRVM_G_FLOAT(OFS_RETURN) = 0;
4031         if(Key_SetBinding((int)PRVM_G_FLOAT(OFS_PARM0), bindmap, PRVM_G_STRING(OFS_PARM1)))
4032                 PRVM_G_FLOAT(OFS_RETURN) = 1;
4033 }
4034
4035 /*
4036 =========
4037 VM_getbindmap
4038
4039 vector getbindmaps()
4040 =========
4041 */
4042 void VM_getbindmaps (prvm_prog_t *prog)
4043 {
4044         int fg, bg;
4045         VM_SAFEPARMCOUNT(0, VM_CL_getbindmap);
4046         Key_GetBindMap(&fg, &bg);
4047         PRVM_G_VECTOR(OFS_RETURN)[0] = fg;
4048         PRVM_G_VECTOR(OFS_RETURN)[1] = bg;
4049         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
4050 }
4051
4052 /*
4053 =========
4054 VM_setbindmap
4055
4056 float setbindmaps(vector bindmap)
4057 =========
4058 */
4059 void VM_setbindmaps (prvm_prog_t *prog)
4060 {
4061         VM_SAFEPARMCOUNT(1, VM_CL_setbindmap);
4062         PRVM_G_FLOAT(OFS_RETURN) = 0;
4063         if(PRVM_G_VECTOR(OFS_PARM0)[2] == 0)
4064                 if(Key_SetBindMap((int)PRVM_G_VECTOR(OFS_PARM0)[0], (int)PRVM_G_VECTOR(OFS_PARM0)[1]))
4065                         PRVM_G_FLOAT(OFS_RETURN) = 1;
4066 }
4067
4068 // CL_Video interface functions
4069
4070 /*
4071 ========================
4072 VM_cin_open
4073
4074 float cin_open(string file, string name)
4075 ========================
4076 */
4077 void VM_cin_open(prvm_prog_t *prog)
4078 {
4079         const char *file;
4080         const char *name;
4081
4082         VM_SAFEPARMCOUNT( 2, VM_cin_open );
4083
4084         file = PRVM_G_STRING( OFS_PARM0 );
4085         name = PRVM_G_STRING( OFS_PARM1 );
4086
4087         VM_CheckEmptyString(prog,  file );
4088     VM_CheckEmptyString(prog,  name );
4089
4090         if( CL_OpenVideo( file, name, MENUOWNER, "" ) )
4091                 PRVM_G_FLOAT( OFS_RETURN ) = 1;
4092         else
4093                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4094 }
4095
4096 /*
4097 ========================
4098 VM_cin_close
4099
4100 void cin_close(string name)
4101 ========================
4102 */
4103 void VM_cin_close(prvm_prog_t *prog)
4104 {
4105         const char *name;
4106
4107         VM_SAFEPARMCOUNT( 1, VM_cin_close );
4108
4109         name = PRVM_G_STRING( OFS_PARM0 );
4110         VM_CheckEmptyString(prog,  name );
4111
4112         CL_CloseVideo( CL_GetVideoByName( name ) );
4113 }
4114
4115 /*
4116 ========================
4117 VM_cin_setstate
4118 void cin_setstate(string name, float type)
4119 ========================
4120 */
4121 void VM_cin_setstate(prvm_prog_t *prog)
4122 {
4123         const char *name;
4124         clvideostate_t  state;
4125         clvideo_t               *video;
4126
4127         VM_SAFEPARMCOUNT( 2, VM_cin_netstate );
4128
4129         name = PRVM_G_STRING( OFS_PARM0 );
4130         VM_CheckEmptyString(prog,  name );
4131
4132         state = (clvideostate_t)((int)PRVM_G_FLOAT( OFS_PARM1 ));
4133
4134         video = CL_GetVideoByName( name );
4135         if( video && state > CLVIDEO_UNUSED && state < CLVIDEO_STATECOUNT )
4136                 CL_SetVideoState( video, state );
4137 }
4138
4139 /*
4140 ========================
4141 VM_cin_getstate
4142
4143 float cin_getstate(string name)
4144 ========================
4145 */
4146 void VM_cin_getstate(prvm_prog_t *prog)
4147 {
4148         const char *name;
4149         clvideo_t               *video;
4150
4151         VM_SAFEPARMCOUNT( 1, VM_cin_getstate );
4152
4153         name = PRVM_G_STRING( OFS_PARM0 );
4154         VM_CheckEmptyString(prog,  name );
4155
4156         video = CL_GetVideoByName( name );
4157         if( video )
4158                 PRVM_G_FLOAT( OFS_RETURN ) = (int)video->state;
4159         else
4160                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4161 }
4162
4163 /*
4164 ========================
4165 VM_cin_restart
4166
4167 void cin_restart(string name)
4168 ========================
4169 */
4170 void VM_cin_restart(prvm_prog_t *prog)
4171 {
4172         const char *name;
4173         clvideo_t               *video;
4174
4175         VM_SAFEPARMCOUNT( 1, VM_cin_restart );
4176
4177         name = PRVM_G_STRING( OFS_PARM0 );
4178         VM_CheckEmptyString(prog,  name );
4179
4180         video = CL_GetVideoByName( name );
4181         if( video )
4182                 CL_RestartVideo( video );
4183 }
4184
4185 /*
4186 ========================
4187 VM_gecko_create
4188
4189 float[bool] gecko_create( string name )
4190 ========================
4191 */
4192 void VM_gecko_create(prvm_prog_t *prog) {
4193         // REMOVED
4194         PRVM_G_FLOAT( OFS_RETURN ) = 0;
4195 }
4196
4197 /*
4198 ========================
4199 VM_gecko_destroy
4200
4201 void gecko_destroy( string name )
4202 ========================
4203 */
4204 void VM_gecko_destroy(prvm_prog_t *prog) {
4205         // REMOVED
4206 }
4207
4208 /*
4209 ========================
4210 VM_gecko_navigate
4211
4212 void gecko_navigate( string name, string URI )
4213 ========================
4214 */
4215 void VM_gecko_navigate(prvm_prog_t *prog) {
4216         // REMOVED
4217 }
4218
4219 /*
4220 ========================
4221 VM_gecko_keyevent
4222
4223 float[bool] gecko_keyevent( string name, float key, float eventtype ) 
4224 ========================
4225 */
4226 void VM_gecko_keyevent(prvm_prog_t *prog) {
4227         // REMOVED
4228         PRVM_G_FLOAT( OFS_RETURN ) = 0;
4229 }
4230
4231 /*
4232 ========================
4233 VM_gecko_movemouse
4234
4235 void gecko_mousemove( string name, float x, float y )
4236 ========================
4237 */
4238 void VM_gecko_movemouse(prvm_prog_t *prog) {
4239         // REMOVED
4240 }
4241
4242
4243 /*
4244 ========================
4245 VM_gecko_resize
4246
4247 void gecko_resize( string name, float w, float h )
4248 ========================
4249 */
4250 void VM_gecko_resize(prvm_prog_t *prog) {
4251         // REMOVED
4252 }
4253
4254
4255 /*
4256 ========================
4257 VM_gecko_get_texture_extent
4258
4259 vector gecko_get_texture_extent( string name )
4260 ========================
4261 */
4262 void VM_gecko_get_texture_extent(prvm_prog_t *prog) {
4263         // REMOVED
4264         PRVM_G_VECTOR(OFS_RETURN)[0] = 0;
4265         PRVM_G_VECTOR(OFS_RETURN)[1] = 0;
4266 }
4267
4268
4269
4270 /*
4271 ==============
4272 VM_makevectors
4273
4274 Writes new values for v_forward, v_up, and v_right based on angles
4275 void makevectors(vector angle)
4276 ==============
4277 */
4278 void VM_makevectors (prvm_prog_t *prog)
4279 {
4280         VM_SAFEPARMCOUNT(1, VM_makevectors);
4281         AngleVectors(PRVM_G_VECTOR(OFS_PARM0), PRVM_gameglobalvector(v_forward), PRVM_gameglobalvector(v_right), PRVM_gameglobalvector(v_up));
4282 }
4283
4284 /*
4285 ==============
4286 VM_vectorvectors
4287
4288 Writes new values for v_forward, v_up, and v_right based on the given forward vector
4289 vectorvectors(vector)
4290 ==============
4291 */
4292 void VM_vectorvectors (prvm_prog_t *prog)
4293 {
4294         VM_SAFEPARMCOUNT(1, VM_vectorvectors);
4295         VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), PRVM_gameglobalvector(v_forward));
4296         VectorVectors(PRVM_gameglobalvector(v_forward), PRVM_gameglobalvector(v_right), PRVM_gameglobalvector(v_up));
4297 }
4298
4299 /*
4300 ========================
4301 VM_drawline
4302
4303 void drawline(float width, vector pos1, vector pos2, vector rgb, float alpha, float flags)
4304 ========================
4305 */
4306 void VM_drawline (prvm_prog_t *prog)
4307 {
4308         float   *c1, *c2, *rgb;
4309         float   alpha, width;
4310         unsigned char   flags;
4311
4312         VM_SAFEPARMCOUNT(6, VM_drawline);
4313         width   = PRVM_G_FLOAT(OFS_PARM0);
4314         c1              = PRVM_G_VECTOR(OFS_PARM1);
4315         c2              = PRVM_G_VECTOR(OFS_PARM2);
4316         rgb             = PRVM_G_VECTOR(OFS_PARM3);
4317         alpha   = PRVM_G_FLOAT(OFS_PARM4);
4318         flags   = (int)PRVM_G_FLOAT(OFS_PARM5);
4319         DrawQ_Line(width, c1[0], c1[1], c2[0], c2[1], rgb[0], rgb[1], rgb[2], alpha, flags);
4320 }
4321
4322 // float(float number, float quantity) bitshift (EXT_BITSHIFT)
4323 void VM_bitshift (prvm_prog_t *prog)
4324 {
4325         int n1, n2;
4326         VM_SAFEPARMCOUNT(2, VM_bitshift);
4327
4328         n1 = (int)fabs((float)((int)PRVM_G_FLOAT(OFS_PARM0)));
4329         n2 = (int)PRVM_G_FLOAT(OFS_PARM1);
4330         if(!n1)
4331                 PRVM_G_FLOAT(OFS_RETURN) = n1;
4332         else
4333         if(n2 < 0)
4334                 PRVM_G_FLOAT(OFS_RETURN) = (n1 >> -n2);
4335         else
4336                 PRVM_G_FLOAT(OFS_RETURN) = (n1 << n2);
4337 }
4338
4339 ////////////////////////////////////////
4340 // AltString functions
4341 ////////////////////////////////////////
4342
4343 /*
4344 ========================
4345 VM_altstr_count
4346
4347 float altstr_count(string)
4348 ========================
4349 */
4350 void VM_altstr_count(prvm_prog_t *prog)
4351 {
4352         const char *altstr, *pos;
4353         int     count;
4354
4355         VM_SAFEPARMCOUNT( 1, VM_altstr_count );
4356
4357         altstr = PRVM_G_STRING( OFS_PARM0 );
4358         //VM_CheckEmptyString(prog,  altstr );
4359
4360         for( count = 0, pos = altstr ; *pos ; pos++ ) {
4361                 if( *pos == '\\' ) {
4362                         if( !*++pos ) {
4363                                 break;
4364                         }
4365                 } else if( *pos == '\'' ) {
4366                         count++;
4367                 }
4368         }
4369
4370         PRVM_G_FLOAT( OFS_RETURN ) = (float) (count / 2);
4371 }
4372
4373 /*
4374 ========================
4375 VM_altstr_prepare
4376
4377 string altstr_prepare(string)
4378 ========================
4379 */
4380 void VM_altstr_prepare(prvm_prog_t *prog)
4381 {
4382         char *out;
4383         const char *instr, *in;
4384         int size;
4385         char outstr[VM_STRINGTEMP_LENGTH];
4386
4387         VM_SAFEPARMCOUNT( 1, VM_altstr_prepare );
4388
4389         instr = PRVM_G_STRING( OFS_PARM0 );
4390
4391         for( out = outstr, in = instr, size = sizeof(outstr) - 1 ; size && *in ; size--, in++, out++ )
4392                 if( *in == '\'' ) {
4393                         *out++ = '\\';
4394                         *out = '\'';
4395                         size--;
4396                 } else
4397                         *out = *in;
4398         *out = 0;
4399
4400         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString(prog,  outstr );
4401 }
4402
4403 /*
4404 ========================
4405 VM_altstr_get
4406
4407 string altstr_get(string, float)
4408 ========================
4409 */
4410 void VM_altstr_get(prvm_prog_t *prog)
4411 {
4412         const char *altstr, *pos;
4413         char *out;
4414         int count, size;
4415         char outstr[VM_STRINGTEMP_LENGTH];
4416
4417         VM_SAFEPARMCOUNT( 2, VM_altstr_get );
4418
4419         altstr = PRVM_G_STRING( OFS_PARM0 );
4420
4421         count = (int)PRVM_G_FLOAT( OFS_PARM1 );
4422         count = count * 2 + 1;
4423
4424         for( pos = altstr ; *pos && count ; pos++ )
4425                 if( *pos == '\\' ) {
4426                         if( !*++pos )
4427                                 break;
4428                 } else if( *pos == '\'' )
4429                         count--;
4430
4431         if( !*pos ) {
4432                 PRVM_G_INT( OFS_RETURN ) = 0;
4433                 return;
4434         }
4435
4436         for( out = outstr, size = sizeof(outstr) - 1 ; size && *pos ; size--, pos++, out++ )
4437                 if( *pos == '\\' ) {
4438                         if( !*++pos )
4439                                 break;
4440                         *out = *pos;
4441                         size--;
4442                 } else if( *pos == '\'' )
4443                         break;
4444                 else
4445                         *out = *pos;
4446
4447         *out = 0;
4448         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString(prog,  outstr );
4449 }
4450
4451 /*
4452 ========================
4453 VM_altstr_set
4454
4455 string altstr_set(string altstr, float num, string set)
4456 ========================
4457 */
4458 void VM_altstr_set(prvm_prog_t *prog)
4459 {
4460     int num;
4461         const char *altstr, *str;
4462         const char *in;
4463         char *out;
4464         char outstr[VM_STRINGTEMP_LENGTH];
4465
4466         VM_SAFEPARMCOUNT( 3, VM_altstr_set );
4467
4468         altstr = PRVM_G_STRING( OFS_PARM0 );
4469
4470         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
4471
4472         str = PRVM_G_STRING( OFS_PARM2 );
4473
4474         out = outstr;
4475         for( num = num * 2 + 1, in = altstr; *in && num; *out++ = *in++ )
4476                 if( *in == '\\' ) {
4477                         if( !*++in ) {
4478                                 break;
4479                         }
4480                 } else if( *in == '\'' ) {
4481                         num--;
4482                 }
4483
4484         // copy set in
4485         for( ; *str; *out++ = *str++ );
4486         // now jump over the old content
4487         for( ; *in ; in++ )
4488                 if( *in == '\'' || (*in == '\\' && !*++in) )
4489                         break;
4490
4491         strlcpy(out, in, outstr + sizeof(outstr) - out);
4492         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString(prog,  outstr );
4493 }
4494
4495 /*
4496 ========================
4497 VM_altstr_ins
4498 insert after num
4499 string  altstr_ins(string altstr, float num, string set)
4500 ========================
4501 */
4502 void VM_altstr_ins(prvm_prog_t *prog)
4503 {
4504         int num;
4505         const char *set;
4506         const char *in;
4507         char *out;
4508         char outstr[VM_STRINGTEMP_LENGTH];
4509
4510         VM_SAFEPARMCOUNT(3, VM_altstr_ins);
4511
4512         in = PRVM_G_STRING( OFS_PARM0 );
4513         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
4514         set = PRVM_G_STRING( OFS_PARM2 );
4515
4516         out = outstr;
4517         for( num = num * 2 + 2 ; *in && num > 0 ; *out++ = *in++ )
4518                 if( *in == '\\' ) {
4519                         if( !*++in ) {
4520                                 break;
4521                         }
4522                 } else if( *in == '\'' ) {
4523                         num--;
4524                 }
4525
4526         *out++ = '\'';
4527         for( ; *set ; *out++ = *set++ );
4528         *out++ = '\'';
4529
4530         strlcpy(out, in, outstr + sizeof(outstr) - out);
4531         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString(prog,  outstr );
4532 }
4533
4534
4535 ////////////////////////////////////////
4536 // BufString functions
4537 ////////////////////////////////////////
4538 //[515]: string buffers support
4539
4540 static size_t stringbuffers_sortlength;
4541
4542 static void BufStr_Expand(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer, int strindex)
4543 {
4544         if (stringbuffer->max_strings <= strindex)
4545         {
4546                 char **oldstrings = stringbuffer->strings;
4547                 stringbuffer->max_strings = max(stringbuffer->max_strings * 2, 128);
4548                 while (stringbuffer->max_strings <= strindex)
4549                         stringbuffer->max_strings *= 2;
4550                 stringbuffer->strings = (char **) Mem_Alloc(prog->progs_mempool, stringbuffer->max_strings * sizeof(stringbuffer->strings[0]));
4551                 if (stringbuffer->num_strings > 0)
4552                         memcpy(stringbuffer->strings, oldstrings, stringbuffer->num_strings * sizeof(stringbuffer->strings[0]));
4553                 if (oldstrings)
4554                         Mem_Free(oldstrings);
4555         }
4556 }
4557
4558 static void BufStr_Shrink(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer)
4559 {
4560         // reduce num_strings if there are empty string slots at the end
4561         while (stringbuffer->num_strings > 0 && stringbuffer->strings[stringbuffer->num_strings - 1] == NULL)
4562                 stringbuffer->num_strings--;
4563
4564         // if empty, free the string pointer array
4565         if (stringbuffer->num_strings == 0)
4566         {
4567                 stringbuffer->max_strings = 0;
4568                 if (stringbuffer->strings)
4569                         Mem_Free(stringbuffer->strings);
4570                 stringbuffer->strings = NULL;
4571         }
4572 }
4573
4574 static int BufStr_SortStringsUP (const void *in1, const void *in2)
4575 {
4576         const char *a, *b;
4577         a = *((const char **) in1);
4578         b = *((const char **) in2);
4579         if(!a || !a[0]) return 1;
4580         if(!b || !b[0]) return -1;
4581         return strncmp(a, b, stringbuffers_sortlength);
4582 }
4583
4584 static int BufStr_SortStringsDOWN (const void *in1, const void *in2)
4585 {
4586         const char *a, *b;
4587         a = *((const char **) in1);
4588         b = *((const char **) in2);
4589         if(!a || !a[0]) return 1;
4590         if(!b || !b[0]) return -1;
4591         return strncmp(b, a, stringbuffers_sortlength);
4592 }
4593
4594 /*
4595 ========================
4596 VM_buf_create
4597 creates new buffer, and returns it's index, returns -1 if failed
4598 float buf_create(prvm_prog_t *prog) = #460;
4599 float newbuf(string format, float flags) = #460;
4600 ========================
4601 */
4602
4603 void VM_buf_create (prvm_prog_t *prog)
4604 {
4605         prvm_stringbuffer_t *stringbuffer;
4606         int i;
4607         
4608         VM_SAFEPARMCOUNTRANGE(0, 2, VM_buf_create);
4609
4610         // VorteX: optional parm1 (buffer format) is unfinished, to keep intact with future databuffers extension must be set to "string"
4611         if(prog->argc >= 1 && strcmp(PRVM_G_STRING(OFS_PARM0), "string"))
4612         {
4613                 PRVM_G_FLOAT(OFS_RETURN) = -1;
4614                 return;
4615         }
4616         stringbuffer = (prvm_stringbuffer_t *) Mem_ExpandableArray_AllocRecord(&prog->stringbuffersarray);
4617         for (i = 0;stringbuffer != Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);i++);
4618         stringbuffer->origin = PRVM_AllocationOrigin(prog);
4619         // optional flags parm
4620         if (prog->argc >= 2)
4621                 stringbuffer->flags = (int)PRVM_G_FLOAT(OFS_PARM1) & 0xFF;
4622         PRVM_G_FLOAT(OFS_RETURN) = i;
4623 }
4624
4625
4626
4627 /*
4628 ========================
4629 VM_buf_del
4630 deletes buffer and all strings in it
4631 void buf_del(float bufhandle) = #461;
4632 ========================
4633 */
4634 void VM_buf_del (prvm_prog_t *prog)
4635 {
4636         prvm_stringbuffer_t *stringbuffer;
4637         VM_SAFEPARMCOUNT(1, VM_buf_del);
4638         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4639         if (stringbuffer)
4640         {
4641                 int i;
4642                 for (i = 0;i < stringbuffer->num_strings;i++)
4643                         if (stringbuffer->strings[i])
4644                                 Mem_Free(stringbuffer->strings[i]);
4645                 if (stringbuffer->strings)
4646                         Mem_Free(stringbuffer->strings);
4647                 if(stringbuffer->origin)
4648                         PRVM_Free((char *)stringbuffer->origin);
4649                 Mem_ExpandableArray_FreeRecord(&prog->stringbuffersarray, stringbuffer);
4650         }
4651         else
4652         {
4653                 VM_Warning(prog, "VM_buf_del: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4654                 return;
4655         }
4656 }
4657
4658 /*
4659 ========================
4660 VM_buf_getsize
4661 how many strings are stored in buffer
4662 float buf_getsize(float bufhandle) = #462;
4663 ========================
4664 */
4665 void VM_buf_getsize (prvm_prog_t *prog)
4666 {
4667         prvm_stringbuffer_t *stringbuffer;
4668         VM_SAFEPARMCOUNT(1, VM_buf_getsize);
4669
4670         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4671         if(!stringbuffer)
4672         {
4673                 PRVM_G_FLOAT(OFS_RETURN) = -1;
4674                 VM_Warning(prog, "VM_buf_getsize: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4675                 return;
4676         }
4677         else
4678                 PRVM_G_FLOAT(OFS_RETURN) = stringbuffer->num_strings;
4679 }
4680
4681 /*
4682 ========================
4683 VM_buf_copy
4684 copy all content from one buffer to another, make sure it exists
4685 void buf_copy(float bufhandle_from, float bufhandle_to) = #463;
4686 ========================
4687 */
4688 void VM_buf_copy (prvm_prog_t *prog)
4689 {
4690         prvm_stringbuffer_t *srcstringbuffer, *dststringbuffer;
4691         int i;
4692         VM_SAFEPARMCOUNT(2, VM_buf_copy);
4693
4694         srcstringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4695         if(!srcstringbuffer)
4696         {
4697                 VM_Warning(prog, "VM_buf_copy: invalid source buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4698                 return;
4699         }
4700         i = (int)PRVM_G_FLOAT(OFS_PARM1);
4701         if(i == (int)PRVM_G_FLOAT(OFS_PARM0))
4702         {
4703                 VM_Warning(prog, "VM_buf_copy: source == destination (%i) in %s\n", i, prog->name);
4704                 return;
4705         }
4706         dststringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4707         if(!dststringbuffer)
4708         {
4709                 VM_Warning(prog, "VM_buf_copy: invalid destination buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
4710                 return;
4711         }
4712
4713         for (i = 0;i < dststringbuffer->num_strings;i++)
4714                 if (dststringbuffer->strings[i])
4715                         Mem_Free(dststringbuffer->strings[i]);
4716         if (dststringbuffer->strings)
4717                 Mem_Free(dststringbuffer->strings);
4718         *dststringbuffer = *srcstringbuffer;
4719         if (dststringbuffer->max_strings)
4720                 dststringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(dststringbuffer->strings[0]) * dststringbuffer->max_strings);
4721
4722         for (i = 0;i < dststringbuffer->num_strings;i++)
4723         {
4724                 if (srcstringbuffer->strings[i])
4725                 {
4726                         size_t stringlen;
4727                         stringlen = strlen(srcstringbuffer->strings[i]) + 1;
4728                         dststringbuffer->strings[i] = (char *)Mem_Alloc(prog->progs_mempool, stringlen);
4729                         memcpy(dststringbuffer->strings[i], srcstringbuffer->strings[i], stringlen);
4730                 }
4731         }
4732 }
4733
4734 /*
4735 ========================
4736 VM_buf_sort
4737 sort buffer by beginnings of strings (cmplength defaults it's length)
4738 "backward == TRUE" means that sorting goes upside-down
4739 void buf_sort(float bufhandle, float cmplength, float backward) = #464;
4740 ========================
4741 */
4742 void VM_buf_sort (prvm_prog_t *prog)
4743 {
4744         prvm_stringbuffer_t *stringbuffer;
4745         VM_SAFEPARMCOUNT(3, VM_buf_sort);
4746
4747         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4748         if(!stringbuffer)
4749         {
4750                 VM_Warning(prog, "VM_buf_sort: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4751                 return;
4752         }
4753         if(stringbuffer->num_strings <= 0)
4754         {
4755                 VM_Warning(prog, "VM_buf_sort: tried to sort empty buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4756                 return;
4757         }
4758         stringbuffers_sortlength = (int)PRVM_G_FLOAT(OFS_PARM1);
4759         if(stringbuffers_sortlength <= 0)
4760                 stringbuffers_sortlength = 0x7FFFFFFF;
4761
4762         if(!PRVM_G_FLOAT(OFS_PARM2))
4763                 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsUP);
4764         else
4765                 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsDOWN);
4766
4767         BufStr_Shrink(prog, stringbuffer);
4768 }
4769
4770 /*
4771 ========================
4772 VM_buf_implode
4773 concantenates all buffer string into one with "glue" separator and returns it as tempstring
4774 string buf_implode(float bufhandle, string glue) = #465;
4775 ========================
4776 */
4777 void VM_buf_implode (prvm_prog_t *prog)
4778 {
4779         prvm_stringbuffer_t *stringbuffer;
4780         char                    k[VM_STRINGTEMP_LENGTH];
4781         const char              *sep;
4782         int                             i;
4783         size_t                  l;
4784         VM_SAFEPARMCOUNT(2, VM_buf_implode);
4785
4786         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4787         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4788         if(!stringbuffer)
4789         {
4790                 VM_Warning(prog, "VM_buf_implode: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4791                 return;
4792         }
4793         if(!stringbuffer->num_strings)
4794                 return;
4795         sep = PRVM_G_STRING(OFS_PARM1);
4796         k[0] = 0;
4797         for(l = i = 0;i < stringbuffer->num_strings;i++)
4798         {
4799                 if(stringbuffer->strings[i])
4800                 {
4801                         l += (i > 0 ? strlen(sep) : 0) + strlen(stringbuffer->strings[i]);
4802                         if (l >= sizeof(k) - 1)
4803                                 break;
4804                         strlcat(k, sep, sizeof(k));
4805                         strlcat(k, stringbuffer->strings[i], sizeof(k));
4806                 }
4807         }
4808         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, k);
4809 }
4810
4811 /*
4812 ========================
4813 VM_bufstr_get
4814 get a string from buffer, returns tempstring, dont str_unzone it!
4815 string bufstr_get(float bufhandle, float string_index) = #465;
4816 ========================
4817 */
4818 void VM_bufstr_get (prvm_prog_t *prog)
4819 {
4820         prvm_stringbuffer_t *stringbuffer;
4821         int                             strindex;
4822         VM_SAFEPARMCOUNT(2, VM_bufstr_get);
4823
4824         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4825         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4826         if(!stringbuffer)
4827         {
4828                 VM_Warning(prog, "VM_bufstr_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4829                 return;
4830         }
4831         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4832         if (strindex < 0)
4833         {
4834                 // VM_Warning(prog, "VM_bufstr_get: invalid string index %i used in %s\n", strindex, prog->name);
4835                 return;
4836         }
4837         if (strindex < stringbuffer->num_strings && stringbuffer->strings[strindex])
4838                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, stringbuffer->strings[strindex]);
4839 }
4840
4841 /*
4842 ========================
4843 VM_bufstr_set
4844 copies a string into selected slot of buffer
4845 void bufstr_set(float bufhandle, float string_index, string str) = #466;
4846 ========================
4847 */
4848 void VM_bufstr_set (prvm_prog_t *prog)
4849 {
4850         size_t alloclen;
4851         int                             strindex;
4852         prvm_stringbuffer_t *stringbuffer;
4853         const char              *news;
4854
4855         VM_SAFEPARMCOUNT(3, VM_bufstr_set);
4856
4857         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4858         if(!stringbuffer)
4859         {
4860                 VM_Warning(prog, "VM_bufstr_set: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4861                 return;
4862         }
4863         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4864         if(strindex < 0 || strindex >= 1000000) // huge number of strings
4865         {
4866                 VM_Warning(prog, "VM_bufstr_set: invalid string index %i used in %s\n", strindex, prog->name);
4867                 return;
4868         }
4869
4870         BufStr_Expand(prog, stringbuffer, strindex);
4871         stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4872
4873         if(stringbuffer->strings[strindex])
4874                 Mem_Free(stringbuffer->strings[strindex]);
4875         stringbuffer->strings[strindex] = NULL;
4876
4877         if(PRVM_G_INT(OFS_PARM2))
4878         {
4879                 // not the NULL string!
4880                 news = PRVM_G_STRING(OFS_PARM2);
4881                 alloclen = strlen(news) + 1;
4882                 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4883                 memcpy(stringbuffer->strings[strindex], news, alloclen);
4884         }
4885
4886         BufStr_Shrink(prog, stringbuffer);
4887 }
4888
4889 /*
4890 ========================
4891 VM_bufstr_add
4892 adds string to buffer in first free slot and returns its index
4893 "order == TRUE" means that string will be added after last "full" slot
4894 float bufstr_add(float bufhandle, string str, float order) = #467;
4895 ========================
4896 */
4897 void VM_bufstr_add (prvm_prog_t *prog)
4898 {
4899         int                             order, strindex;
4900         prvm_stringbuffer_t *stringbuffer;
4901         const char              *string;
4902         size_t                  alloclen;
4903
4904         VM_SAFEPARMCOUNT(3, VM_bufstr_add);
4905
4906         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4907         PRVM_G_FLOAT(OFS_RETURN) = -1;
4908         if(!stringbuffer)
4909         {
4910                 VM_Warning(prog, "VM_bufstr_add: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4911                 return;
4912         }
4913         if(!PRVM_G_INT(OFS_PARM1)) // NULL string
4914         {
4915                 VM_Warning(prog, "VM_bufstr_add: can not add an empty string to buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4916                 return;
4917         }
4918         string = PRVM_G_STRING(OFS_PARM1);
4919         order = (int)PRVM_G_FLOAT(OFS_PARM2);
4920         if(order)
4921                 strindex = stringbuffer->num_strings;
4922         else
4923                 for (strindex = 0;strindex < stringbuffer->num_strings;strindex++)
4924                         if (stringbuffer->strings[strindex] == NULL)
4925                                 break;
4926
4927         BufStr_Expand(prog, stringbuffer, strindex);
4928
4929         stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4930         alloclen = strlen(string) + 1;
4931         stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4932         memcpy(stringbuffer->strings[strindex], string, alloclen);
4933
4934         PRVM_G_FLOAT(OFS_RETURN) = strindex;
4935 }
4936
4937 /*
4938 ========================
4939 VM_bufstr_free
4940 delete string from buffer
4941 void bufstr_free(float bufhandle, float string_index) = #468;
4942 ========================
4943 */
4944 void VM_bufstr_free (prvm_prog_t *prog)
4945 {
4946         int                             i;
4947         prvm_stringbuffer_t     *stringbuffer;
4948         VM_SAFEPARMCOUNT(2, VM_bufstr_free);
4949
4950         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4951         if(!stringbuffer)
4952         {
4953                 VM_Warning(prog, "VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4954                 return;
4955         }
4956         i = (int)PRVM_G_FLOAT(OFS_PARM1);
4957         if(i < 0)
4958         {
4959                 VM_Warning(prog, "VM_bufstr_free: invalid string index %i used in %s\n", i, prog->name);
4960                 return;
4961         }
4962
4963         if (i < stringbuffer->num_strings)
4964         {
4965                 if(stringbuffer->strings[i])
4966                         Mem_Free(stringbuffer->strings[i]);
4967                 stringbuffer->strings[i] = NULL;
4968         }
4969
4970         BufStr_Shrink(prog, stringbuffer);
4971 }
4972
4973
4974
4975
4976
4977
4978
4979 void VM_buf_cvarlist(prvm_prog_t *prog)
4980 {
4981         cvar_t *cvar;
4982         const char *partial, *antipartial;
4983         size_t len, antilen;
4984         size_t alloclen;
4985         qboolean ispattern, antiispattern;
4986         int n;
4987         prvm_stringbuffer_t     *stringbuffer;
4988         VM_SAFEPARMCOUNTRANGE(2, 3, VM_buf_cvarlist);
4989
4990         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4991         if(!stringbuffer)
4992         {
4993                 VM_Warning(prog, "VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4994                 return;
4995         }
4996
4997         partial = PRVM_G_STRING(OFS_PARM1);
4998         if(!partial)
4999                 len = 0;
5000         else
5001                 len = strlen(partial);
5002
5003         if(prog->argc == 3)
5004                 antipartial = PRVM_G_STRING(OFS_PARM2);
5005         else
5006                 antipartial = NULL;
5007         if(!antipartial)
5008                 antilen = 0;
5009         else
5010                 antilen = strlen(antipartial);
5011         
5012         for (n = 0;n < stringbuffer->num_strings;n++)
5013                 if (stringbuffer->strings[n])
5014                         Mem_Free(stringbuffer->strings[n]);
5015         if (stringbuffer->strings)
5016                 Mem_Free(stringbuffer->strings);
5017         stringbuffer->strings = NULL;
5018
5019         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
5020         antiispattern = antipartial && (strchr(antipartial, '*') || strchr(antipartial, '?'));
5021
5022         n = 0;
5023         for(cvar = cvar_vars; cvar; cvar = cvar->next)
5024         {
5025                 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
5026                         continue;
5027
5028                 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
5029                         continue;
5030
5031                 ++n;
5032         }
5033
5034         stringbuffer->max_strings = stringbuffer->num_strings = n;
5035         if (stringbuffer->max_strings)
5036                 stringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(stringbuffer->strings[0]) * stringbuffer->max_strings);
5037         
5038         n = 0;
5039         for(cvar = cvar_vars; cvar; cvar = cvar->next)
5040         {
5041                 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
5042                         continue;
5043
5044                 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
5045                         continue;
5046
5047                 alloclen = strlen(cvar->name) + 1;
5048                 stringbuffer->strings[n] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
5049                 memcpy(stringbuffer->strings[n], cvar->name, alloclen);
5050
5051                 ++n;
5052         }
5053 }
5054
5055
5056
5057
5058 //=============
5059
5060 /*
5061 ==============
5062 VM_changeyaw
5063
5064 This was a major timewaster in progs, so it was converted to C
5065 ==============
5066 */
5067 void VM_changeyaw (prvm_prog_t *prog)
5068 {
5069         prvm_edict_t            *ent;
5070         float           ideal, current, move, speed;
5071
5072         // this is called (VERY HACKISHLY) by VM_SV_MoveToGoal, so it can not use any
5073         // parameters because they are the parameters to VM_SV_MoveToGoal, not this
5074         //VM_SAFEPARMCOUNT(0, VM_changeyaw);
5075
5076         ent = PRVM_PROG_TO_EDICT(PRVM_gameglobaledict(self));
5077         if (ent == prog->edicts)
5078         {
5079                 VM_Warning(prog, "changeyaw: can not modify world entity\n");
5080                 return;
5081         }
5082         if (ent->priv.server->free)
5083         {
5084                 VM_Warning(prog, "changeyaw: can not modify free entity\n");
5085                 return;
5086         }
5087         current = PRVM_gameedictvector(ent, angles)[1];
5088         current = ANGLEMOD(current);
5089         ideal = PRVM_gameedictfloat(ent, ideal_yaw);
5090         speed = PRVM_gameedictfloat(ent, yaw_speed);
5091
5092         if (current == ideal)
5093                 return;
5094         move = ideal - current;
5095         if (ideal > current)
5096         {
5097                 if (move >= 180)
5098                         move = move - 360;
5099         }
5100         else
5101         {
5102                 if (move <= -180)
5103                         move = move + 360;
5104         }
5105         if (move > 0)
5106         {
5107                 if (move > speed)
5108                         move = speed;
5109         }
5110         else
5111         {
5112                 if (move < -speed)
5113                         move = -speed;
5114         }
5115
5116         current += move;
5117         PRVM_gameedictvector(ent, angles)[1] = ANGLEMOD(current);
5118 }
5119
5120 /*
5121 ==============
5122 VM_changepitch
5123 ==============
5124 */
5125 void VM_changepitch (prvm_prog_t *prog)
5126 {
5127         prvm_edict_t            *ent;
5128         float           ideal, current, move, speed;
5129
5130         VM_SAFEPARMCOUNT(1, VM_changepitch);
5131
5132         ent = PRVM_G_EDICT(OFS_PARM0);
5133         if (ent == prog->edicts)
5134         {
5135                 VM_Warning(prog, "changepitch: can not modify world entity\n");
5136                 return;
5137         }
5138         if (ent->priv.server->free)
5139         {
5140                 VM_Warning(prog, "changepitch: can not modify free entity\n");
5141                 return;
5142         }
5143         current = PRVM_gameedictvector(ent, angles)[0];
5144         current = ANGLEMOD(current);
5145         ideal = PRVM_gameedictfloat(ent, idealpitch);
5146         speed = PRVM_gameedictfloat(ent, pitch_speed);
5147
5148         if (current == ideal)
5149                 return;
5150         move = ideal - current;
5151         if (ideal > current)
5152         {
5153                 if (move >= 180)
5154                         move = move - 360;
5155         }
5156         else
5157         {
5158                 if (move <= -180)
5159                         move = move + 360;
5160         }
5161         if (move > 0)
5162         {
5163                 if (move > speed)
5164                         move = speed;
5165         }
5166         else
5167         {
5168                 if (move < -speed)
5169                         move = -speed;
5170         }
5171
5172         current += move;
5173         PRVM_gameedictvector(ent, angles)[0] = ANGLEMOD(current);
5174 }
5175
5176
5177 void VM_uncolorstring (prvm_prog_t *prog)
5178 {
5179         char szNewString[VM_STRINGTEMP_LENGTH];
5180         const char *szString;
5181
5182         // Prepare Strings
5183         VM_SAFEPARMCOUNT(1, VM_uncolorstring);
5184         szString = PRVM_G_STRING(OFS_PARM0);
5185         COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), TRUE);
5186         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString);
5187         
5188 }
5189
5190 // #221 float(string str, string sub[, float startpos]) strstrofs (FTE_STRINGS)
5191 //strstr, without generating a new string. Use in conjunction with FRIK_FILE's substring for more similar strstr.
5192 void VM_strstrofs (prvm_prog_t *prog)
5193 {
5194         const char *instr, *match;
5195         int firstofs;
5196         VM_SAFEPARMCOUNTRANGE(2, 3, VM_strstrofs);
5197         instr = PRVM_G_STRING(OFS_PARM0);
5198         match = PRVM_G_STRING(OFS_PARM1);
5199         firstofs = (prog->argc > 2)?(int)PRVM_G_FLOAT(OFS_PARM2):0;
5200         firstofs = u8_bytelen(instr, firstofs);
5201
5202         if (firstofs && (firstofs < 0 || firstofs > (int)strlen(instr)))
5203         {
5204                 PRVM_G_FLOAT(OFS_RETURN) = -1;
5205                 return;
5206         }
5207
5208         match = strstr(instr+firstofs, match);
5209         if (!match)
5210                 PRVM_G_FLOAT(OFS_RETURN) = -1;
5211         else
5212                 PRVM_G_FLOAT(OFS_RETURN) = u8_strnlen(instr, match-instr);
5213 }
5214
5215 //#222 string(string s, float index) str2chr (FTE_STRINGS)
5216 void VM_str2chr (prvm_prog_t *prog)
5217 {
5218         const char *s;
5219         Uchar ch;
5220         int index;
5221         VM_SAFEPARMCOUNT(2, VM_str2chr);
5222         s = PRVM_G_STRING(OFS_PARM0);
5223         index = u8_bytelen(s, (int)PRVM_G_FLOAT(OFS_PARM1));
5224
5225         if((unsigned)index < strlen(s))
5226         {
5227                 if (utf8_enable.integer)
5228                         ch = u8_getchar_noendptr(s + index);
5229                 else
5230                         ch = (unsigned char)s[index];
5231                 PRVM_G_FLOAT(OFS_RETURN) = ch;
5232         }
5233         else
5234                 PRVM_G_FLOAT(OFS_RETURN) = 0;
5235 }
5236
5237 //#223 string(float c, ...) chr2str (FTE_STRINGS)
5238 void VM_chr2str (prvm_prog_t *prog)
5239 {
5240         /*
5241         char    t[9];
5242         int             i;
5243         VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
5244         for(i = 0;i < prog->argc && i < (int)sizeof(t) - 1;i++)
5245                 t[i] = (unsigned char)PRVM_G_FLOAT(OFS_PARM0+i*3);
5246         t[i] = 0;
5247         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, t);
5248         */
5249         char t[9 * 4 + 1];
5250         int i;
5251         size_t len = 0;
5252         VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
5253         for(i = 0; i < prog->argc && len < sizeof(t)-1; ++i)
5254                 len += u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0+i*3), t + len, sizeof(t)-1);
5255         t[len] = 0;
5256         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, t);
5257 }
5258
5259 static int chrconv_number(int i, int base, int conv)
5260 {
5261         i -= base;
5262         switch (conv)
5263         {
5264         default:
5265         case 5:
5266         case 6:
5267         case 0:
5268                 break;
5269         case 1:
5270                 base = '0';
5271                 break;
5272         case 2:
5273                 base = '0'+128;
5274                 break;
5275         case 3:
5276                 base = '0'-30;
5277                 break;
5278         case 4:
5279                 base = '0'+128-30;
5280                 break;
5281         }
5282         return i + base;
5283 }
5284 static int chrconv_punct(int i, int base, int conv)
5285 {
5286         i -= base;
5287         switch (conv)
5288         {
5289         default:
5290         case 0:
5291                 break;
5292         case 1:
5293                 base = 0;
5294                 break;
5295         case 2:
5296                 base = 128;
5297                 break;
5298         }
5299         return i + base;
5300 }
5301
5302 static int chrchar_alpha(int i, int basec, int baset, int convc, int convt, int charnum)
5303 {
5304         //convert case and colour seperatly...
5305
5306         i -= baset + basec;
5307         switch (convt)
5308         {
5309         default:
5310         case 0:
5311                 break;
5312         case 1:
5313                 baset = 0;
5314                 break;
5315         case 2:
5316                 baset = 128;
5317                 break;
5318
5319         case 5:
5320         case 6:
5321                 baset = 128*((charnum&1) == (convt-5));
5322                 break;
5323         }
5324
5325         switch (convc)
5326         {
5327         default:
5328         case 0:
5329                 break;
5330         case 1:
5331                 basec = 'a';
5332                 break;
5333         case 2:
5334                 basec = 'A';
5335                 break;
5336         }
5337         return i + basec + baset;
5338 }
5339 // #224 string(float ccase, float calpha, float cnum, string s, ...) strconv (FTE_STRINGS)
5340 //bulk convert a string. change case or colouring.
5341 void VM_strconv (prvm_prog_t *prog)
5342 {
5343         int ccase, redalpha, rednum, len, i;
5344         unsigned char resbuf[VM_STRINGTEMP_LENGTH];
5345         unsigned char *result = resbuf;
5346
5347         VM_SAFEPARMCOUNTRANGE(3, 8, VM_strconv);
5348
5349         ccase = (int) PRVM_G_FLOAT(OFS_PARM0);  //0 same, 1 lower, 2 upper
5350         redalpha = (int) PRVM_G_FLOAT(OFS_PARM1);       //0 same, 1 white, 2 red,  5 alternate, 6 alternate-alternate
5351         rednum = (int) PRVM_G_FLOAT(OFS_PARM2); //0 same, 1 white, 2 red, 3 redspecial, 4 whitespecial, 5 alternate, 6 alternate-alternate
5352         VM_VarString(prog, 3, (char *) resbuf, sizeof(resbuf));
5353         len = strlen((char *) resbuf);
5354
5355         for (i = 0; i < len; i++, result++)     //should this be done backwards?
5356         {
5357                 if (*result >= '0' && *result <= '9')   //normal numbers...
5358                         *result = chrconv_number(*result, '0', rednum);
5359                 else if (*result >= '0'+128 && *result <= '9'+128)
5360                         *result = chrconv_number(*result, '0'+128, rednum);
5361                 else if (*result >= '0'+128-30 && *result <= '9'+128-30)
5362                         *result = chrconv_number(*result, '0'+128-30, rednum);
5363                 else if (*result >= '0'-30 && *result <= '9'-30)
5364                         *result = chrconv_number(*result, '0'-30, rednum);
5365
5366                 else if (*result >= 'a' && *result <= 'z')      //normal numbers...
5367                         *result = chrchar_alpha(*result, 'a', 0, ccase, redalpha, i);
5368                 else if (*result >= 'A' && *result <= 'Z')      //normal numbers...
5369                         *result = chrchar_alpha(*result, 'A', 0, ccase, redalpha, i);
5370                 else if (*result >= 'a'+128 && *result <= 'z'+128)      //normal numbers...
5371                         *result = chrchar_alpha(*result, 'a', 128, ccase, redalpha, i);
5372                 else if (*result >= 'A'+128 && *result <= 'Z'+128)      //normal numbers...
5373                         *result = chrchar_alpha(*result, 'A', 128, ccase, redalpha, i);
5374
5375                 else if ((*result & 127) < 16 || !redalpha)     //special chars..
5376                         *result = *result;
5377                 else if (*result < 128)
5378                         *result = chrconv_punct(*result, 0, redalpha);
5379                 else
5380                         *result = chrconv_punct(*result, 128, redalpha);
5381         }
5382         *result = '\0';
5383
5384         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, (char *) resbuf);
5385 }
5386
5387 // #225 string(float chars, string s, ...) strpad (FTE_STRINGS)
5388 void VM_strpad (prvm_prog_t *prog)
5389 {
5390         char src[VM_STRINGTEMP_LENGTH];
5391         char destbuf[VM_STRINGTEMP_LENGTH];
5392         int pad;
5393         VM_SAFEPARMCOUNTRANGE(1, 8, VM_strpad);
5394         pad = (int) PRVM_G_FLOAT(OFS_PARM0);
5395         VM_VarString(prog, 1, src, sizeof(src));
5396
5397         // note: < 0 = left padding, > 0 = right padding,
5398         // this is reverse logic of printf!
5399         dpsnprintf(destbuf, sizeof(destbuf), "%*s", -pad, src);
5400
5401         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, destbuf);
5402 }
5403
5404 // #226 string(string info, string key, string value, ...) infoadd (FTE_STRINGS)
5405 //uses qw style \key\value strings
5406 void VM_infoadd (prvm_prog_t *prog)
5407 {
5408         const char *info, *key;
5409         char value[VM_STRINGTEMP_LENGTH];
5410         char temp[VM_STRINGTEMP_LENGTH];
5411
5412         VM_SAFEPARMCOUNTRANGE(2, 8, VM_infoadd);
5413         info = PRVM_G_STRING(OFS_PARM0);
5414         key = PRVM_G_STRING(OFS_PARM1);
5415         VM_VarString(prog, 2, value, sizeof(value));
5416
5417         strlcpy(temp, info, VM_STRINGTEMP_LENGTH);
5418
5419         InfoString_SetValue(temp, VM_STRINGTEMP_LENGTH, key, value);
5420
5421         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, temp);
5422 }
5423
5424 // #227 string(string info, string key) infoget (FTE_STRINGS)
5425 //uses qw style \key\value strings
5426 void VM_infoget (prvm_prog_t *prog)
5427 {
5428         const char *info;
5429         const char *key;
5430         char value[VM_STRINGTEMP_LENGTH];
5431
5432         VM_SAFEPARMCOUNT(2, VM_infoget);
5433         info = PRVM_G_STRING(OFS_PARM0);
5434         key = PRVM_G_STRING(OFS_PARM1);
5435
5436         InfoString_GetValue(info, key, value, VM_STRINGTEMP_LENGTH);
5437
5438         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, value);
5439 }
5440
5441 //#228 float(string s1, string s2, float len) strncmp (FTE_STRINGS)
5442 // also float(string s1, string s2) strcmp (FRIK_FILE)
5443 void VM_strncmp (prvm_prog_t *prog)
5444 {
5445         const char *s1, *s2;
5446         VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncmp);
5447         s1 = PRVM_G_STRING(OFS_PARM0);
5448         s2 = PRVM_G_STRING(OFS_PARM1);
5449         if (prog->argc > 2)
5450         {
5451                 PRVM_G_FLOAT(OFS_RETURN) = strncmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5452         }
5453         else
5454         {
5455                 PRVM_G_FLOAT(OFS_RETURN) = strcmp(s1, s2);
5456         }
5457 }
5458
5459 // #229 float(string s1, string s2) strcasecmp (FTE_STRINGS)
5460 // #230 float(string s1, string s2, float len) strncasecmp (FTE_STRINGS)
5461 void VM_strncasecmp (prvm_prog_t *prog)
5462 {
5463         const char *s1, *s2;
5464         VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncasecmp);
5465         s1 = PRVM_G_STRING(OFS_PARM0);
5466         s2 = PRVM_G_STRING(OFS_PARM1);
5467         if (prog->argc > 2)
5468         {
5469                 PRVM_G_FLOAT(OFS_RETURN) = strncasecmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5470         }
5471         else
5472         {
5473                 PRVM_G_FLOAT(OFS_RETURN) = strcasecmp(s1, s2);
5474         }
5475 }
5476
5477 // #494 float(float caseinsensitive, string s, ...) crc16
5478 void VM_crc16(prvm_prog_t *prog)
5479 {
5480         float insensitive;
5481         char s[VM_STRINGTEMP_LENGTH];
5482         VM_SAFEPARMCOUNTRANGE(2, 8, VM_crc16);
5483         insensitive = PRVM_G_FLOAT(OFS_PARM0);
5484         VM_VarString(prog, 1, s, sizeof(s));
5485         PRVM_G_FLOAT(OFS_RETURN) = (unsigned short) ((insensitive ? CRC_Block_CaseInsensitive : CRC_Block) ((unsigned char *) s, strlen(s)));
5486 }
5487
5488 // #639 float(string digest, string data, ...) digest_hex
5489 void VM_digest_hex(prvm_prog_t *prog)
5490 {
5491         const char *digest;
5492
5493         char out[32];
5494         char outhex[65];
5495         int outlen;
5496
5497         char s[VM_STRINGTEMP_LENGTH];
5498         int len;
5499
5500         VM_SAFEPARMCOUNTRANGE(2, 8, VM_digest_hex);
5501         digest = PRVM_G_STRING(OFS_PARM0);
5502         if(!digest)
5503                 digest = "";
5504         VM_VarString(prog, 1, s, sizeof(s));
5505         len = strlen(s);
5506
5507         outlen = 0;
5508
5509         if(!strcmp(digest, "MD4"))
5510         {
5511                 outlen = 16;
5512                 mdfour((unsigned char *) out, (unsigned char *) s, len);
5513         }
5514         else if(!strcmp(digest, "SHA256") && Crypto_Available())
5515         {
5516                 outlen = 32;
5517                 sha256((unsigned char *) out, (unsigned char *) s, len);
5518         }
5519         // no warning needed on mismatch - we return string_null to QC
5520
5521         if(outlen)
5522         {
5523                 int i;
5524                 static const char *hexmap = "0123456789abcdef";
5525                 for(i = 0; i < outlen; ++i)
5526                 {
5527                         outhex[2*i]   = hexmap[(out[i] >> 4) & 15];
5528                         outhex[2*i+1] = hexmap[(out[i] >> 0) & 15];
5529                 }
5530                 outhex[2*i] = 0;
5531                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outhex);
5532         }
5533         else
5534                 PRVM_G_INT(OFS_RETURN) = 0;
5535 }
5536
5537 void VM_wasfreed (prvm_prog_t *prog)
5538 {
5539         VM_SAFEPARMCOUNT(1, VM_wasfreed);
5540         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICT(OFS_PARM0)->priv.required->free;
5541 }
5542
5543 void VM_SetTraceGlobals(prvm_prog_t *prog, const trace_t *trace)
5544 {
5545         PRVM_gameglobalfloat(trace_allsolid) = trace->allsolid;
5546         PRVM_gameglobalfloat(trace_startsolid) = trace->startsolid;
5547         PRVM_gameglobalfloat(trace_fraction) = trace->fraction;
5548         PRVM_gameglobalfloat(trace_inwater) = trace->inwater;
5549         PRVM_gameglobalfloat(trace_inopen) = trace->inopen;
5550         VectorCopy(trace->endpos, PRVM_gameglobalvector(trace_endpos));
5551         VectorCopy(trace->plane.normal, PRVM_gameglobalvector(trace_plane_normal));
5552         PRVM_gameglobalfloat(trace_plane_dist) = trace->plane.dist;
5553         PRVM_gameglobaledict(trace_ent) = PRVM_EDICT_TO_PROG(trace->ent ? trace->ent : prog->edicts);
5554         PRVM_gameglobalfloat(trace_dpstartcontents) = trace->startsupercontents;
5555         PRVM_gameglobalfloat(trace_dphitcontents) = trace->hitsupercontents;
5556         PRVM_gameglobalfloat(trace_dphitq3surfaceflags) = trace->hitq3surfaceflags;
5557         PRVM_gameglobalstring(trace_dphittexturename) = trace->hittexture ? PRVM_SetTempString(prog, trace->hittexture->name) : 0;
5558 }
5559
5560 void VM_ClearTraceGlobals(prvm_prog_t *prog)
5561 {
5562         // clean up all trace globals when leaving the VM (anti-triggerbot safeguard)
5563         PRVM_gameglobalfloat(trace_allsolid) = 0;
5564         PRVM_gameglobalfloat(trace_startsolid) = 0;
5565         PRVM_gameglobalfloat(trace_fraction) = 0;
5566         PRVM_gameglobalfloat(trace_inwater) = 0;
5567         PRVM_gameglobalfloat(trace_inopen) = 0;
5568         VectorClear(PRVM_gameglobalvector(trace_endpos));
5569         VectorClear(PRVM_gameglobalvector(trace_plane_normal));
5570         PRVM_gameglobalfloat(trace_plane_dist) = 0;
5571         PRVM_gameglobaledict(trace_ent) = PRVM_EDICT_TO_PROG(prog->edicts);
5572         PRVM_gameglobalfloat(trace_dpstartcontents) = 0;
5573         PRVM_gameglobalfloat(trace_dphitcontents) = 0;
5574         PRVM_gameglobalfloat(trace_dphitq3surfaceflags) = 0;
5575         PRVM_gameglobalstring(trace_dphittexturename) = 0;
5576 }
5577
5578 //=============
5579
5580 void VM_Cmd_Init(prvm_prog_t *prog)
5581 {
5582         // only init the stuff for the current prog
5583         VM_Files_Init(prog);
5584         VM_Search_Init(prog);
5585 }
5586
5587 void VM_Cmd_Reset(prvm_prog_t *prog)
5588 {
5589         CL_PurgeOwner( MENUOWNER );
5590         VM_Search_Reset(prog);
5591         VM_Files_CloseAll(prog);
5592 }
5593
5594 // #510 string(string input, ...) uri_escape (DP_QC_URI_ESCAPE)
5595 // does URI escaping on a string (replace evil stuff by %AB escapes)
5596 void VM_uri_escape (prvm_prog_t *prog)
5597 {
5598         char src[VM_STRINGTEMP_LENGTH];
5599         char dest[VM_STRINGTEMP_LENGTH];
5600         char *p, *q;
5601         static const char *hex = "0123456789ABCDEF";
5602
5603         VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_escape);
5604         VM_VarString(prog, 0, src, sizeof(src));
5605
5606         for(p = src, q = dest; *p && q < dest + sizeof(dest) - 3; ++p)
5607         {
5608                 if((*p >= 'A' && *p <= 'Z')
5609                         || (*p >= 'a' && *p <= 'z')
5610                         || (*p >= '0' && *p <= '9')
5611                         || (*p == '-')  || (*p == '_') || (*p == '.')
5612                         || (*p == '!')  || (*p == '~')
5613                         || (*p == '\'') || (*p == '(') || (*p == ')'))
5614                         *q++ = *p;
5615                 else
5616                 {
5617                         *q++ = '%';
5618                         *q++ = hex[(*(unsigned char *)p >> 4) & 0xF];
5619                         *q++ = hex[ *(unsigned char *)p       & 0xF];
5620                 }
5621         }
5622         *q++ = 0;
5623
5624         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, dest);
5625 }
5626
5627 // #510 string(string input, ...) uri_unescape (DP_QC_URI_ESCAPE)
5628 // does URI unescaping on a string (get back the evil stuff)
5629 void VM_uri_unescape (prvm_prog_t *prog)
5630 {
5631         char src[VM_STRINGTEMP_LENGTH];
5632         char dest[VM_STRINGTEMP_LENGTH];
5633         char *p, *q;
5634         int hi, lo;
5635
5636         VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_unescape);
5637         VM_VarString(prog, 0, src, sizeof(src));
5638
5639         for(p = src, q = dest; *p; ) // no need to check size, because unescape can't expand
5640         {
5641                 if(*p == '%')
5642                 {
5643                         if(p[1] >= '0' && p[1] <= '9')
5644                                 hi = p[1] - '0';
5645                         else if(p[1] >= 'a' && p[1] <= 'f')
5646                                 hi = p[1] - 'a' + 10;
5647                         else if(p[1] >= 'A' && p[1] <= 'F')
5648                                 hi = p[1] - 'A' + 10;
5649                         else
5650                                 goto nohex;
5651                         if(p[2] >= '0' && p[2] <= '9')
5652                                 lo = p[2] - '0';
5653                         else if(p[2] >= 'a' && p[2] <= 'f')
5654                                 lo = p[2] - 'a' + 10;
5655                         else if(p[2] >= 'A' && p[2] <= 'F')
5656                                 lo = p[2] - 'A' + 10;
5657                         else
5658                                 goto nohex;
5659                         if(hi != 0 || lo != 0) // don't unescape NUL bytes
5660                                 *q++ = (char) (hi * 0x10 + lo);
5661                         p += 3;
5662                         continue;
5663                 }
5664
5665 nohex:
5666                 // otherwise:
5667                 *q++ = *p++;
5668         }
5669         *q++ = 0;
5670
5671         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, dest);
5672 }
5673
5674 // #502 string(string filename) whichpack (DP_QC_WHICHPACK)
5675 // returns the name of the pack containing a file, or "" if it is not in any pack (but local or non-existant)
5676 void VM_whichpack (prvm_prog_t *prog)
5677 {
5678         const char *fn, *pack;
5679
5680         VM_SAFEPARMCOUNT(1, VM_whichpack);
5681         fn = PRVM_G_STRING(OFS_PARM0);
5682         pack = FS_WhichPack(fn);
5683
5684         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, pack ? pack : "");
5685 }
5686
5687 typedef struct
5688 {
5689         prvm_prog_t *prog;
5690         double starttime;
5691         float id;
5692         char buffer[MAX_INPUTLINE];
5693         unsigned char *postdata; // free when uri_to_prog_t is freed
5694         size_t postlen;
5695         char *sigdata; // free when uri_to_prog_t is freed
5696         size_t siglen;
5697 }
5698 uri_to_prog_t;
5699
5700 static void uri_to_string_callback(int status, size_t length_received, unsigned char *buffer, void *cbdata)
5701 {
5702         prvm_prog_t *prog;
5703         uri_to_prog_t *handle = (uri_to_prog_t *) cbdata;
5704
5705         prog = handle->prog;
5706         if(!prog->loaded)
5707         {
5708                 // curl reply came too late... so just drop it
5709                 if(handle->postdata)
5710                         Z_Free(handle->postdata);
5711                 if(handle->sigdata)
5712                         Z_Free(handle->sigdata);
5713                 Z_Free(handle);
5714                 return;
5715         }
5716
5717         if((prog->starttime == handle->starttime) && (PRVM_allfunction(URI_Get_Callback)))
5718         {
5719                 if(length_received >= sizeof(handle->buffer))
5720                         length_received = sizeof(handle->buffer) - 1;
5721                 handle->buffer[length_received] = 0;
5722
5723                 PRVM_G_FLOAT(OFS_PARM0) = handle->id;
5724                 PRVM_G_FLOAT(OFS_PARM1) = status;
5725                 PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(prog, handle->buffer);
5726                 prog->ExecuteProgram(prog, PRVM_allfunction(URI_Get_Callback), "QC function URI_Get_Callback is missing");
5727         }
5728
5729         if(handle->postdata)
5730                 Z_Free(handle->postdata);
5731         if(handle->sigdata)
5732                 Z_Free(handle->sigdata);
5733         Z_Free(handle);
5734 }
5735
5736 // uri_get() gets content from an URL and calls a callback "uri_get_callback" with it set as string; an unique ID of the transfer is returned
5737 // returns 1 on success, and then calls the callback with the ID, 0 or the HTTP status code, and the received data in a string
5738 void VM_uri_get (prvm_prog_t *prog)
5739 {
5740         const char *url;
5741         float id;
5742         qboolean ret;
5743         uri_to_prog_t *handle;
5744         const char *posttype = NULL;
5745         const char *postseparator = NULL;
5746         int poststringbuffer = -1;
5747         int postkeyid = -1;
5748         const char *query_string = NULL;
5749         size_t lq;
5750
5751         if(!PRVM_allfunction(URI_Get_Callback))
5752                 prog->error_cmd("uri_get called by %s without URI_Get_Callback defined", prog->name);
5753
5754         VM_SAFEPARMCOUNTRANGE(2, 6, VM_uri_get);
5755
5756         url = PRVM_G_STRING(OFS_PARM0);
5757         id = PRVM_G_FLOAT(OFS_PARM1);
5758         if(prog->argc >= 3)
5759                 posttype = PRVM_G_STRING(OFS_PARM2);
5760         if(prog->argc >= 4)
5761                 postseparator = PRVM_G_STRING(OFS_PARM3);
5762         if(prog->argc >= 5)
5763                 poststringbuffer = PRVM_G_FLOAT(OFS_PARM4);
5764         if(prog->argc >= 6)
5765                 postkeyid = PRVM_G_FLOAT(OFS_PARM5);
5766         handle = (uri_to_prog_t *) Z_Malloc(sizeof(*handle)); // this can't be the prog's mem pool, as curl may call the callback later!
5767
5768         query_string = strchr(url, '?');
5769         if(query_string)
5770                 ++query_string;
5771         lq = query_string ? strlen(query_string) : 0;
5772
5773         handle->prog = prog;
5774         handle->starttime = prog->starttime;
5775         handle->id = id;
5776         if(postseparator && posttype && *posttype)
5777         {
5778                 size_t l = strlen(postseparator);
5779                 if(poststringbuffer >= 0)
5780                 {
5781                         size_t ltotal;
5782                         int i;
5783                         // "implode"
5784                         prvm_stringbuffer_t *stringbuffer;
5785                         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, poststringbuffer);
5786                         if(!stringbuffer)
5787                         {
5788                                 VM_Warning(prog, "uri_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
5789                                 return;
5790                         }
5791                         ltotal = 0;
5792                         for(i = 0;i < stringbuffer->num_strings;i++)
5793                         {
5794                                 if(i > 0)
5795                                         ltotal += l;
5796                                 if(stringbuffer->strings[i])
5797                                         ltotal += strlen(stringbuffer->strings[i]);
5798                         }
5799                         handle->postdata = (unsigned char *)Z_Malloc(ltotal + 1 + lq);
5800                         handle->postlen = ltotal;
5801                         ltotal = 0;
5802                         for(i = 0;i < stringbuffer->num_strings;i++)
5803                         {
5804                                 if(i > 0)
5805                                 {
5806                                         memcpy(handle->postdata + ltotal, postseparator, l);
5807                                         ltotal += l;
5808                                 }
5809                                 if(stringbuffer->strings[i])
5810                                 {
5811                                         memcpy(handle->postdata + ltotal, stringbuffer->strings[i], strlen(stringbuffer->strings[i]));
5812                                         ltotal += strlen(stringbuffer->strings[i]);
5813                                 }
5814                         }
5815                         if(ltotal != handle->postlen)
5816                                 prog->error_cmd("%s: string buffer content size mismatch, possible overrun", prog->name);
5817                 }
5818                 else
5819                 {
5820                         handle->postdata = (unsigned char *)Z_Malloc(l + 1 + lq);
5821                         handle->postlen = l;
5822                         memcpy(handle->postdata, postseparator, l);
5823                 }
5824                 handle->postdata[handle->postlen] = 0;
5825                 if(query_string)
5826                         memcpy(handle->postdata + handle->postlen + 1, query_string, lq);
5827                 if(postkeyid >= 0)
5828                 {
5829                         // POST: we sign postdata \0 query string
5830                         size_t ll;
5831                         handle->sigdata = (char *)Z_Malloc(8192);
5832                         strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
5833                         l = strlen(handle->sigdata);
5834                         handle->siglen = Crypto_SignDataDetached(handle->postdata, handle->postlen + 1 + lq, postkeyid, handle->sigdata + l, 8192 - l);
5835                         if(!handle->siglen)
5836                         {
5837                                 Z_Free(handle->sigdata);
5838                                 handle->sigdata = NULL;
5839                                 goto out1;
5840                         }
5841                         ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
5842                         if(!ll)
5843                         {
5844                                 Z_Free(handle->sigdata);
5845                                 handle->sigdata = NULL;
5846                                 goto out1;
5847                         }
5848                         handle->siglen = l + ll;
5849                         handle->sigdata[handle->siglen] = 0;
5850                 }
5851 out1:
5852                 ret = Curl_Begin_ToMemory_POST(url, handle->sigdata, 0, posttype, handle->postdata, handle->postlen, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
5853         }
5854         else
5855         {
5856                 if(postkeyid >= 0 && query_string)
5857                 {
5858                         // GET: we sign JUST the query string
5859                         size_t l, ll;
5860                         handle->sigdata = (char *)Z_Malloc(8192);
5861                         strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
5862                         l = strlen(handle->sigdata);
5863                         handle->siglen = Crypto_SignDataDetached(query_string, lq, postkeyid, handle->sigdata + l, 8192 - l);
5864                         if(!handle->siglen)
5865                         {
5866                                 Z_Free(handle->sigdata);
5867                                 handle->sigdata = NULL;
5868                                 goto out2;
5869                         }
5870                         ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
5871                         if(!ll)
5872                         {
5873                                 Z_Free(handle->sigdata);
5874                                 handle->sigdata = NULL;
5875                                 goto out2;
5876                         }
5877                         handle->siglen = l + ll;
5878                         handle->sigdata[handle->siglen] = 0;
5879                 }
5880 out2:
5881                 handle->postdata = NULL;
5882                 handle->postlen = 0;
5883                 ret = Curl_Begin_ToMemory(url, 0, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
5884         }
5885         if(ret)
5886         {
5887                 PRVM_G_INT(OFS_RETURN) = 1;
5888         }
5889         else
5890         {
5891                 if(handle->postdata)
5892                         Z_Free(handle->postdata);
5893                 if(handle->sigdata)
5894                         Z_Free(handle->sigdata);
5895                 Z_Free(handle);
5896                 PRVM_G_INT(OFS_RETURN) = 0;
5897         }
5898 }
5899
5900 void VM_netaddress_resolve (prvm_prog_t *prog)
5901 {
5902         const char *ip;
5903         char normalized[128];
5904         int port;
5905         lhnetaddress_t addr;
5906
5907         VM_SAFEPARMCOUNTRANGE(1, 2, VM_netaddress_resolve);
5908
5909         ip = PRVM_G_STRING(OFS_PARM0);
5910         port = 0;
5911         if(prog->argc > 1)
5912                 port = (int) PRVM_G_FLOAT(OFS_PARM1);
5913
5914         if(LHNETADDRESS_FromString(&addr, ip, port) && LHNETADDRESS_ToString(&addr, normalized, sizeof(normalized), prog->argc > 1))
5915                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, normalized);
5916         else
5917                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
5918 }
5919
5920 //string(prvm_prog_t *prog) getextresponse = #624; // returns the next extResponse packet that was sent to this client
5921 void VM_CL_getextresponse (prvm_prog_t *prog)
5922 {
5923         VM_SAFEPARMCOUNT(0,VM_argv);
5924
5925         if (cl_net_extresponse_count <= 0)
5926                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
5927         else
5928         {
5929                 int first;
5930                 --cl_net_extresponse_count;
5931                 first = (cl_net_extresponse_last + NET_EXTRESPONSE_MAX - cl_net_extresponse_count) % NET_EXTRESPONSE_MAX;
5932                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cl_net_extresponse[first]);
5933         }
5934 }
5935
5936 void VM_SV_getextresponse (prvm_prog_t *prog)
5937 {
5938         VM_SAFEPARMCOUNT(0,VM_argv);
5939
5940         if (sv_net_extresponse_count <= 0)
5941                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
5942         else
5943         {
5944                 int first;
5945                 --sv_net_extresponse_count;
5946                 first = (sv_net_extresponse_last + NET_EXTRESPONSE_MAX - sv_net_extresponse_count) % NET_EXTRESPONSE_MAX;
5947                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, sv_net_extresponse[first]);
5948         }
5949 }
5950
5951 /*
5952 =========
5953 Common functions between menu.dat and clsprogs
5954 =========
5955 */
5956
5957 //#349 float() isdemo 
5958 void VM_CL_isdemo (prvm_prog_t *prog)
5959 {
5960         VM_SAFEPARMCOUNT(0, VM_CL_isdemo);
5961         PRVM_G_FLOAT(OFS_RETURN) = cls.demoplayback;
5962 }
5963
5964 //#355 float() videoplaying 
5965 void VM_CL_videoplaying (prvm_prog_t *prog)
5966 {
5967         VM_SAFEPARMCOUNT(0, VM_CL_videoplaying);
5968         PRVM_G_FLOAT(OFS_RETURN) = cl_videoplaying;
5969 }
5970
5971 /*
5972 =========
5973 VM_M_callfunction
5974
5975         callfunction(...,string function_name)
5976 Extension: pass
5977 =========
5978 */
5979 void VM_callfunction(prvm_prog_t *prog)
5980 {
5981         mfunction_t *func;
5982         const char *s;
5983
5984         VM_SAFEPARMCOUNTRANGE(1, 8, VM_callfunction);
5985
5986         s = PRVM_G_STRING(OFS_PARM0+(prog->argc - 1)*3);
5987
5988         VM_CheckEmptyString(prog, s);
5989
5990         func = PRVM_ED_FindFunction(prog, s);
5991
5992         if(!func)
5993                 prog->error_cmd("VM_callfunciton: function %s not found !", s);
5994         else if (func->first_statement < 0)
5995         {
5996                 // negative statements are built in functions
5997                 int builtinnumber = -func->first_statement;
5998                 prog->xfunction->builtinsprofile++;
5999                 if (builtinnumber < prog->numbuiltins && prog->builtins[builtinnumber])
6000                         prog->builtins[builtinnumber](prog);
6001                 else
6002                         prog->error_cmd("No such builtin #%i in %s; most likely cause: outdated engine build. Try updating!", builtinnumber, prog->name);
6003         }
6004         else if(func - prog->functions > 0)
6005         {
6006                 prog->argc--;
6007                 prog->ExecuteProgram(prog, func - prog->functions,"");
6008                 prog->argc++;
6009         }
6010 }
6011
6012 /*
6013 =========
6014 VM_isfunction
6015
6016 float   isfunction(string function_name)
6017 =========
6018 */
6019 void VM_isfunction(prvm_prog_t *prog)
6020 {
6021         mfunction_t *func;
6022         const char *s;
6023
6024         VM_SAFEPARMCOUNT(1, VM_isfunction);
6025
6026         s = PRVM_G_STRING(OFS_PARM0);
6027
6028         VM_CheckEmptyString(prog, s);
6029
6030         func = PRVM_ED_FindFunction(prog, s);
6031
6032         if(!func)
6033                 PRVM_G_FLOAT(OFS_RETURN) = false;
6034         else
6035                 PRVM_G_FLOAT(OFS_RETURN) = true;
6036 }
6037
6038 /*
6039 =========
6040 VM_sprintf
6041
6042 string sprintf(string format, ...)
6043 =========
6044 */
6045
6046 void VM_sprintf(prvm_prog_t *prog)
6047 {
6048         const char *s, *s0;
6049         char outbuf[MAX_INPUTLINE];
6050         char *o = outbuf, *end = outbuf + sizeof(outbuf), *err;
6051         int argpos = 1;
6052         int width, precision, thisarg, flags;
6053         char formatbuf[16];
6054         char *f;
6055         int isfloat;
6056         static int dummyivec[3] = {0, 0, 0};
6057         static float dummyvec[3] = {0, 0, 0};
6058         char vabuf[1024];
6059
6060 #define PRINTF_ALTERNATE 1
6061 #define PRINTF_ZEROPAD 2
6062 #define PRINTF_LEFT 4
6063 #define PRINTF_SPACEPOSITIVE 8
6064 #define PRINTF_SIGNPOSITIVE 16
6065
6066         formatbuf[0] = '%';
6067
6068         s = PRVM_G_STRING(OFS_PARM0);
6069
6070 #define GETARG_FLOAT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_FLOAT(OFS_PARM0 + 3 * (a))) : 0)
6071 #define GETARG_VECTOR(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyvec)
6072 #define GETARG_INT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_INT(OFS_PARM0 + 3 * (a))) : 0)
6073 #define GETARG_INTVECTOR(a) (((a)>=1 && (a)<prog->argc) ? ((int*) PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyivec)
6074 #define GETARG_STRING(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_STRING(OFS_PARM0 + 3 * (a))) : "")
6075
6076         for(;;)
6077         {
6078                 s0 = s;
6079                 switch(*s)
6080                 {
6081                         case 0:
6082                                 goto finished;
6083                         case '%':
6084                                 ++s;
6085
6086                                 if(*s == '%')
6087                                         goto verbatim;
6088
6089                                 // complete directive format:
6090                                 // %3$*1$.*2$ld
6091                                 
6092                                 width = -1;
6093                                 precision = -1;
6094                                 thisarg = -1;
6095                                 flags = 0;
6096                                 isfloat = -1;
6097
6098                                 // is number following?
6099                                 if(*s >= '0' && *s <= '9')
6100                                 {
6101                                         width = strtol(s, &err, 10);
6102                                         if(!err)
6103                                         {
6104                                                 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
6105                                                 goto finished;
6106                                         }
6107                                         if(*err == '$')
6108                                         {
6109                                                 thisarg = width;
6110                                                 width = -1;
6111                                                 s = err + 1;
6112                                         }
6113                                         else
6114                                         {
6115                                                 if(*s == '0')
6116                                                 {
6117                                                         flags |= PRINTF_ZEROPAD;
6118                                                         if(width == 0)
6119                                                                 width = -1; // it was just a flag
6120                                                 }
6121                                                 s = err;
6122                                         }
6123                                 }
6124
6125                                 if(width < 0)
6126                                 {
6127                                         for(;;)
6128                                         {
6129                                                 switch(*s)
6130                                                 {
6131                                                         case '#': flags |= PRINTF_ALTERNATE; break;
6132                                                         case '0': flags |= PRINTF_ZEROPAD; break;
6133                                                         case '-': flags |= PRINTF_LEFT; break;
6134                                                         case ' ': flags |= PRINTF_SPACEPOSITIVE; break;
6135                                                         case '+': flags |= PRINTF_SIGNPOSITIVE; break;
6136                                                         default:
6137                                                                 goto noflags;
6138                                                 }
6139                                                 ++s;
6140                                         }
6141 noflags:
6142                                         if(*s == '*')
6143                                         {
6144                                                 ++s;
6145                                                 if(*s >= '0' && *s <= '9')
6146                                                 {
6147                                                         width = strtol(s, &err, 10);
6148                                                         if(!err || *err != '$')
6149                                                         {
6150                                                                 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
6151                                                                 goto finished;
6152                                                         }
6153                                                         s = err + 1;
6154                                                 }
6155                                                 else
6156                                                         width = argpos++;
6157                                                 width = GETARG_FLOAT(width);
6158                                                 if(width < 0)
6159                                                 {
6160                                                         flags |= PRINTF_LEFT;
6161                                                         width = -width;
6162                                                 }
6163                                         }
6164                                         else if(*s >= '0' && *s <= '9')
6165                                         {
6166                                                 width = strtol(s, &err, 10);
6167                                                 if(!err)
6168                                                 {
6169                                                         VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
6170                                                         goto finished;
6171                                                 }
6172                                                 s = err;
6173                                                 if(width < 0)
6174                                                 {
6175                                                         flags |= PRINTF_LEFT;
6176                                                         width = -width;
6177                                                 }
6178                                         }
6179                                         // otherwise width stays -1
6180                                 }
6181
6182                                 if(*s == '.')
6183                                 {
6184                                         ++s;
6185                                         if(*s == '*')
6186                                         {
6187                                                 ++s;
6188                                                 if(*s >= '0' && *s <= '9')
6189                                                 {
6190                                                         precision = strtol(s, &err, 10);
6191                                                         if(!err || *err != '$')
6192                                                         {
6193                                                                 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
6194                                                                 goto finished;
6195                                                         }
6196                                                         s = err + 1;
6197                                                 }
6198                                                 else
6199                                                         precision = argpos++;
6200                                                 precision = GETARG_FLOAT(precision);
6201                                         }
6202                                         else if(*s >= '0' && *s <= '9')
6203                                         {
6204                                                 precision = strtol(s, &err, 10);
6205                                                 if(!err)
6206                                                 {
6207                                                         VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
6208                                                         goto finished;
6209                                                 }
6210                                                 s = err;
6211                                         }
6212                                         else
6213                                         {
6214                                                 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
6215                                                 goto finished;
6216                                         }
6217                                 }
6218
6219                                 for(;;)
6220                                 {
6221                                         switch(*s)
6222                                         {
6223                                                 case 'h': isfloat = 1; break;
6224                                                 case 'l': isfloat = 0; break;
6225                                                 case 'L': isfloat = 0; break;
6226                                                 case 'j': break;
6227                                                 case 'z': break;
6228                                                 case 't': break;
6229                                                 default:
6230                                                         goto nolength;
6231                                         }
6232                                         ++s;
6233                                 }
6234 nolength:
6235
6236                                 // now s points to the final directive char and is no longer changed
6237                                 if(isfloat < 0)
6238                                 {
6239                                         if(*s == 'i')
6240                                                 isfloat = 0;
6241                                         else
6242                                                 isfloat = 1;
6243                                 }
6244
6245                                 if(thisarg < 0)
6246                                         thisarg = argpos++;
6247
6248                                 if(o < end - 1)
6249                                 {
6250                                         f = &formatbuf[1];
6251                                         if(*s != 's' && *s != 'c')
6252                                                 if(flags & PRINTF_ALTERNATE) *f++ = '#';
6253                                         if(flags & PRINTF_ZEROPAD) *f++ = '0';
6254                                         if(flags & PRINTF_LEFT) *f++ = '-';
6255                                         if(flags & PRINTF_SPACEPOSITIVE) *f++ = ' ';
6256                                         if(flags & PRINTF_SIGNPOSITIVE) *f++ = '+';
6257                                         *f++ = '*';
6258                                         if(precision >= 0)
6259                                         {
6260                                                 *f++ = '.';
6261                                                 *f++ = '*';
6262                                         }
6263                                         *f++ = *s;
6264                                         *f++ = 0;
6265
6266                                         if(width < 0) // not set
6267                                                 width = 0;
6268
6269                                         switch(*s)
6270                                         {
6271                                                 case 'd': case 'i':
6272                                                         if(precision < 0) // not set
6273                                                                 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (int) GETARG_FLOAT(thisarg) : (int) GETARG_INT(thisarg)));
6274                                                         else
6275                                                                 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (int) GETARG_FLOAT(thisarg) : (int) GETARG_INT(thisarg)));
6276                                                         break;
6277                                                 case 'o': case 'u': case 'x': case 'X':
6278                                                         if(precision < 0) // not set
6279                                                                 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6280                                                         else
6281                                                                 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6282                                                         break;
6283                                                 case 'e': case 'E': case 'f': case 'F': case 'g': case 'G':
6284                                                         if(precision < 0) // not set
6285                                                                 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6286                                                         else
6287                                                                 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6288                                                         break;
6289                                                 case 'v': case 'V':
6290                                                         f[-2] += 'g' - 'v';
6291                                                         if(precision < 0) // not set
6292                                                                 o += dpsnprintf(o, end - o, va(vabuf, sizeof(vabuf), "%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6293                                                                         width, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6294                                                                         width, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6295                                                                         width, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6296                                                                 );
6297                                                         else
6298                                                                 o += dpsnprintf(o, end - o, va(vabuf, sizeof(vabuf), "%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6299                                                                         width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6300                                                                         width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6301                                                                         width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6302                                                                 );
6303                                                         break;
6304                                                 case 'c':
6305                                                         if(flags & PRINTF_ALTERNATE)
6306                                                         {
6307                                                                 if(precision < 0) // not set
6308                                                                         o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6309                                                                 else
6310                                                                         o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6311                                                         }
6312                                                         else
6313                                                         {
6314                                                                 unsigned int c = (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg));
6315                                                                 char charbuf16[16];
6316                                                                 const char *buf = u8_encodech(c, NULL, charbuf16);
6317                                                                 if(!buf)
6318                                                                         buf = "";
6319                                                                 if(precision < 0) // not set
6320                                                                         precision = end - o - 1;
6321                                                                 o += u8_strpad(o, end - o, buf, (flags & PRINTF_LEFT) != 0, width, precision);
6322                                                         }
6323                                                         break;
6324                                                 case 's':
6325                                                         if(flags & PRINTF_ALTERNATE)
6326                                                         {
6327                                                                 if(precision < 0) // not set
6328                                                                         o += dpsnprintf(o, end - o, formatbuf, width, GETARG_STRING(thisarg));
6329                                                                 else
6330                                                                         o += dpsnprintf(o, end - o, formatbuf, width, precision, GETARG_STRING(thisarg));
6331                                                         }
6332                                                         else
6333                                                         {
6334                                                                 if(precision < 0) // not set
6335                                                                         precision = end - o - 1;
6336                                                                 if(flags & PRINTF_SIGNPOSITIVE)
6337                                                                         o += u8_strpad(o, end - o, GETARG_STRING(thisarg), (flags & PRINTF_LEFT) != 0, width, precision);
6338                                                                 else
6339                                                                         o += u8_strpad_colorcodes(o, end - o, GETARG_STRING(thisarg), (flags & PRINTF_LEFT) != 0, width, precision);
6340                                                         }
6341                                                         break;
6342                                                 default:
6343                                                         VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
6344                                                         goto finished;
6345                                         }
6346                                 }
6347                                 ++s;
6348                                 break;
6349                         default:
6350 verbatim:
6351                                 if(o < end - 1)
6352                                         *o++ = *s++;
6353                                 break;
6354                 }
6355         }
6356 finished:
6357         *o = 0;
6358         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outbuf);
6359 }
6360
6361
6362 // surface querying
6363
6364 static dp_model_t *getmodel(prvm_prog_t *prog, prvm_edict_t *ed)
6365 {
6366         if (prog == SVVM_prog)
6367                 return SV_GetModelFromEdict(ed);
6368         else if (prog == CLVM_prog)
6369                 return CL_GetModelFromEdict(ed);
6370         else
6371                 return NULL;
6372 }
6373
6374 typedef struct
6375 {
6376         unsigned int progid;
6377         dp_model_t *model;
6378         frameblend_t frameblend[MAX_FRAMEBLENDS];
6379         skeleton_t *skeleton_p;
6380         skeleton_t skeleton;
6381         float *data_vertex3f;
6382         float *data_svector3f;
6383         float *data_tvector3f;
6384         float *data_normal3f;
6385         int max_vertices;
6386         float *buf_vertex3f;
6387         float *buf_svector3f;
6388         float *buf_tvector3f;
6389         float *buf_normal3f;
6390 }
6391 animatemodel_cache_t;
6392 static animatemodel_cache_t animatemodel_cache;
6393
6394 static void animatemodel(prvm_prog_t *prog, dp_model_t *model, prvm_edict_t *ed)
6395 {
6396         skeleton_t *skeleton;
6397         int skeletonindex = -1;
6398         qboolean need = false;
6399         if(!(model->surfmesh.isanimated && model->AnimateVertices))
6400         {
6401                 animatemodel_cache.data_vertex3f = model->surfmesh.data_vertex3f;
6402                 animatemodel_cache.data_svector3f = model->surfmesh.data_svector3f;
6403                 animatemodel_cache.data_tvector3f = model->surfmesh.data_tvector3f;
6404                 animatemodel_cache.data_normal3f = model->surfmesh.data_normal3f;
6405                 return;
6406         }
6407         if(animatemodel_cache.progid != prog->id)
6408                 memset(&animatemodel_cache, 0, sizeof(animatemodel_cache));
6409         need |= (animatemodel_cache.model != model);
6410         VM_GenerateFrameGroupBlend(prog, ed->priv.server->framegroupblend, ed);
6411         VM_FrameBlendFromFrameGroupBlend(ed->priv.server->frameblend, ed->priv.server->framegroupblend, model);
6412         need |= (memcmp(&animatemodel_cache.frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend))) != 0;
6413         skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
6414         if (!(skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones))
6415                 skeleton = NULL;
6416         need |= (animatemodel_cache.skeleton_p != skeleton);
6417         if(skeleton)
6418                 need |= (memcmp(&animatemodel_cache.skeleton, skeleton, sizeof(ed->priv.server->skeleton))) != 0;
6419         if(!need)
6420                 return;
6421         if(model->surfmesh.num_vertices > animatemodel_cache.max_vertices)
6422         {
6423                 animatemodel_cache.max_vertices = model->surfmesh.num_vertices * 2;
6424                 if(animatemodel_cache.buf_vertex3f) Mem_Free(animatemodel_cache.buf_vertex3f);
6425                 if(animatemodel_cache.buf_svector3f) Mem_Free(animatemodel_cache.buf_svector3f);
6426                 if(animatemodel_cache.buf_tvector3f) Mem_Free(animatemodel_cache.buf_tvector3f);
6427                 if(animatemodel_cache.buf_normal3f) Mem_Free(animatemodel_cache.buf_normal3f);
6428                 animatemodel_cache.buf_vertex3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6429                 animatemodel_cache.buf_svector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6430                 animatemodel_cache.buf_tvector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6431                 animatemodel_cache.buf_normal3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6432         }
6433         animatemodel_cache.data_vertex3f = animatemodel_cache.buf_vertex3f;
6434         animatemodel_cache.data_svector3f = animatemodel_cache.buf_svector3f;
6435         animatemodel_cache.data_tvector3f = animatemodel_cache.buf_tvector3f;
6436         animatemodel_cache.data_normal3f = animatemodel_cache.buf_normal3f;
6437         VM_UpdateEdictSkeleton(prog, ed, model, ed->priv.server->frameblend);
6438         model->AnimateVertices(model, ed->priv.server->frameblend, &ed->priv.server->skeleton, animatemodel_cache.data_vertex3f, animatemodel_cache.data_normal3f, animatemodel_cache.data_svector3f, animatemodel_cache.data_tvector3f);
6439         animatemodel_cache.progid = prog->id;
6440         animatemodel_cache.model = model;
6441         memcpy(&animatemodel_cache.frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend));
6442         animatemodel_cache.skeleton_p = skeleton;
6443         if(skeleton)
6444                 memcpy(&animatemodel_cache.skeleton, skeleton, sizeof(ed->priv.server->skeleton));
6445 }
6446
6447 static void getmatrix(prvm_prog_t *prog, prvm_edict_t *ed, matrix4x4_t *out)
6448 {
6449         if (prog == SVVM_prog)
6450                 SV_GetEntityMatrix(prog, ed, out, false);
6451         else if (prog == CLVM_prog)
6452                 CL_GetEntityMatrix(prog, ed, out, false);
6453         else
6454                 *out = identitymatrix;
6455 }
6456
6457 static void applytransform_forward(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6458 {
6459         matrix4x4_t m;
6460         getmatrix(prog, ed, &m);
6461         Matrix4x4_Transform(&m, in, out);
6462 }
6463
6464 static void applytransform_forward_direction(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6465 {
6466         matrix4x4_t m;
6467         getmatrix(prog, ed, &m);
6468         Matrix4x4_Transform3x3(&m, in, out);
6469 }
6470
6471 static void applytransform_inverted(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6472 {
6473         matrix4x4_t m, n;
6474         getmatrix(prog, ed, &m);
6475         Matrix4x4_Invert_Full(&n, &m);
6476         Matrix4x4_Transform3x3(&n, in, out);
6477 }
6478
6479 static void applytransform_forward_normal(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6480 {
6481         matrix4x4_t m;
6482         float p[4];
6483         getmatrix(prog, ed, &m);
6484         Matrix4x4_TransformPositivePlane(&m, in[0], in[1], in[2], 0, p);
6485         VectorCopy(p, out);
6486 }
6487
6488 static void clippointtosurface(prvm_prog_t *prog, prvm_edict_t *ed, dp_model_t *model, msurface_t *surface, vec3_t p, vec3_t out)
6489 {
6490         int i, j, k;
6491         float *v[3], facenormal[3], edgenormal[3], sidenormal[3], temp[3], offsetdist, dist, bestdist;
6492         const int *e;
6493         animatemodel(prog, model, ed);
6494         bestdist = 1000000000;
6495         VectorCopy(p, out);
6496         for (i = 0, e = (model->surfmesh.data_element3i + 3 * surface->num_firsttriangle);i < surface->num_triangles;i++, e += 3)
6497         {
6498                 // clip original point to each triangle of the surface and find the
6499                 // triangle that is closest
6500                 v[0] = animatemodel_cache.data_vertex3f + e[0] * 3;
6501                 v[1] = animatemodel_cache.data_vertex3f + e[1] * 3;
6502                 v[2] = animatemodel_cache.data_vertex3f + e[2] * 3;
6503                 TriangleNormal(v[0], v[1], v[2], facenormal);
6504                 VectorNormalize(facenormal);
6505                 offsetdist = DotProduct(v[0], facenormal) - DotProduct(p, facenormal);
6506                 VectorMA(p, offsetdist, facenormal, temp);
6507                 for (j = 0, k = 2;j < 3;k = j, j++)
6508                 {
6509                         VectorSubtract(v[k], v[j], edgenormal);
6510                         CrossProduct(edgenormal, facenormal, sidenormal);
6511                         VectorNormalize(sidenormal);
6512                         offsetdist = DotProduct(v[k], sidenormal) - DotProduct(temp, sidenormal);
6513                         if (offsetdist < 0)
6514                                 VectorMA(temp, offsetdist, sidenormal, temp);
6515                 }
6516                 dist = VectorDistance2(temp, p);
6517                 if (bestdist > dist)
6518                 {
6519                         bestdist = dist;
6520                         VectorCopy(temp, out);
6521                 }
6522         }
6523 }
6524
6525 static msurface_t *getsurface(dp_model_t *model, int surfacenum)
6526 {
6527         if (surfacenum < 0 || surfacenum >= model->nummodelsurfaces)
6528                 return NULL;
6529         return model->data_surfaces + surfacenum + model->firstmodelsurface;
6530 }
6531
6532
6533 //PF_getsurfacenumpoints, // #434 float(entity e, float s) getsurfacenumpoints = #434;
6534 void VM_getsurfacenumpoints(prvm_prog_t *prog)
6535 {
6536         dp_model_t *model;
6537         msurface_t *surface;
6538         VM_SAFEPARMCOUNT(2, VM_getsurfacenumpoints);
6539         // return 0 if no such surface
6540         if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6541         {
6542                 PRVM_G_FLOAT(OFS_RETURN) = 0;
6543                 return;
6544         }
6545
6546         // note: this (incorrectly) assumes it is a simple polygon
6547         PRVM_G_FLOAT(OFS_RETURN) = surface->num_vertices;
6548 }
6549 //PF_getsurfacepoint,     // #435 vector(entity e, float s, float n) getsurfacepoint = #435;
6550 void VM_getsurfacepoint(prvm_prog_t *prog)
6551 {
6552         prvm_edict_t *ed;
6553         dp_model_t *model;
6554         msurface_t *surface;
6555         int pointnum;
6556         VM_SAFEPARMCOUNT(3, VM_getsurfacepoint);
6557         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6558         ed = PRVM_G_EDICT(OFS_PARM0);
6559         if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6560                 return;
6561         // note: this (incorrectly) assumes it is a simple polygon
6562         pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6563         if (pointnum < 0 || pointnum >= surface->num_vertices)
6564                 return;
6565         animatemodel(prog, model, ed);
6566         applytransform_forward(prog, &(animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6567 }
6568 //PF_getsurfacepointattribute,     // #486 vector(entity e, float s, float n, float a) getsurfacepointattribute = #486;
6569 // float SPA_POSITION = 0;
6570 // float SPA_S_AXIS = 1;
6571 // float SPA_T_AXIS = 2;
6572 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6573 // float SPA_TEXCOORDS0 = 4;
6574 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6575 // float SPA_LIGHTMAP0_COLOR = 6;
6576 void VM_getsurfacepointattribute(prvm_prog_t *prog)
6577 {
6578         prvm_edict_t *ed;
6579         dp_model_t *model;
6580         msurface_t *surface;
6581         int pointnum;
6582         int attributetype;
6583
6584         VM_SAFEPARMCOUNT(4, VM_getsurfacepoint);
6585         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6586         ed = PRVM_G_EDICT(OFS_PARM0);
6587         if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6588                 return;
6589         pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6590         if (pointnum < 0 || pointnum >= surface->num_vertices)
6591                 return;
6592         attributetype = (int) PRVM_G_FLOAT(OFS_PARM3);
6593
6594         animatemodel(prog, model, ed);
6595
6596         switch( attributetype ) {
6597                 // float SPA_POSITION = 0;
6598                 case 0:
6599                         applytransform_forward(prog, &(animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6600                         break;
6601                 // float SPA_S_AXIS = 1;
6602                 case 1:
6603                         applytransform_forward_direction(prog, &(animatemodel_cache.data_svector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6604                         break;
6605                 // float SPA_T_AXIS = 2;
6606                 case 2:
6607                         applytransform_forward_direction(prog, &(animatemodel_cache.data_tvector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6608                         break;
6609                 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6610                 case 3:
6611                         applytransform_forward_direction(prog, &(animatemodel_cache.data_normal3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6612                         break;
6613                 // float SPA_TEXCOORDS0 = 4;
6614                 case 4: {
6615                         float *ret = PRVM_G_VECTOR(OFS_RETURN);
6616                         float *texcoord = &(model->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[pointnum * 2];
6617                         ret[0] = texcoord[0];
6618                         ret[1] = texcoord[1];
6619                         ret[2] = 0.0f;
6620                         break;
6621                 }
6622                 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6623                 case 5: {
6624                         float *ret = PRVM_G_VECTOR(OFS_RETURN);
6625                         float *texcoord = &(model->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[pointnum * 2];
6626                         ret[0] = texcoord[0];
6627                         ret[1] = texcoord[1];
6628                         ret[2] = 0.0f;
6629                         break;
6630                 }
6631                 // float SPA_LIGHTMAP0_COLOR = 6;
6632                 case 6:
6633                         // ignore alpha for now..
6634                         VectorCopy( &(model->surfmesh.data_lightmapcolor4f + 4 * surface->num_firstvertex)[pointnum * 4], PRVM_G_VECTOR(OFS_RETURN));
6635                         break;
6636                 default:
6637                         VectorSet( PRVM_G_VECTOR(OFS_RETURN), 0.0f, 0.0f, 0.0f );
6638                         break;
6639         }
6640 }
6641 //PF_getsurfacenormal,    // #436 vector(entity e, float s) getsurfacenormal = #436;
6642 void VM_getsurfacenormal(prvm_prog_t *prog)
6643 {
6644         dp_model_t *model;
6645         msurface_t *surface;
6646         vec3_t normal;
6647         VM_SAFEPARMCOUNT(2, VM_getsurfacenormal);
6648         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6649         if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6650                 return;
6651         // note: this only returns the first triangle, so it doesn't work very
6652         // well for curved surfaces or arbitrary meshes
6653         animatemodel(prog, model, PRVM_G_EDICT(OFS_PARM0));
6654         TriangleNormal((animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex), (animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex) + 3, (animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex) + 6, normal);
6655         applytransform_forward_normal(prog, normal, PRVM_G_EDICT(OFS_PARM0), PRVM_G_VECTOR(OFS_RETURN));
6656         VectorNormalize(PRVM_G_VECTOR(OFS_RETURN));
6657 }
6658 //PF_getsurfacetexture,   // #437 string(entity e, float s) getsurfacetexture = #437;
6659 void VM_getsurfacetexture(prvm_prog_t *prog)
6660 {
6661         dp_model_t *model;
6662         msurface_t *surface;
6663         VM_SAFEPARMCOUNT(2, VM_getsurfacetexture);
6664         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
6665         if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6666                 return;
6667         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, surface->texture->name);
6668 }
6669 //PF_getsurfacenearpoint, // #438 float(entity e, vector p) getsurfacenearpoint = #438;
6670 void VM_getsurfacenearpoint(prvm_prog_t *prog)
6671 {
6672         int surfacenum, best;
6673         vec3_t clipped, p;
6674         vec_t dist, bestdist;
6675         prvm_edict_t *ed;
6676         dp_model_t *model;
6677         msurface_t *surface;
6678         vec_t *point;
6679         VM_SAFEPARMCOUNT(2, VM_getsurfacenearpoint);
6680         PRVM_G_FLOAT(OFS_RETURN) = -1;
6681         ed = PRVM_G_EDICT(OFS_PARM0);
6682         point = PRVM_G_VECTOR(OFS_PARM1);
6683
6684         if (!ed || ed->priv.server->free)
6685                 return;
6686         model = getmodel(prog, ed);
6687         if (!model || !model->num_surfaces)
6688                 return;
6689
6690         animatemodel(prog, model, ed);
6691
6692         applytransform_inverted(prog, point, ed, p);
6693         best = -1;
6694         bestdist = 1000000000;
6695         for (surfacenum = 0;surfacenum < model->nummodelsurfaces;surfacenum++)
6696         {
6697                 surface = model->data_surfaces + surfacenum + model->firstmodelsurface;
6698                 // first see if the nearest point on the surface's box is closer than the previous match
6699                 clipped[0] = bound(surface->mins[0], p[0], surface->maxs[0]) - p[0];
6700                 clipped[1] = bound(surface->mins[1], p[1], surface->maxs[1]) - p[1];
6701                 clipped[2] = bound(surface->mins[2], p[2], surface->maxs[2]) - p[2];
6702                 dist = VectorLength2(clipped);
6703                 if (dist < bestdist)
6704                 {
6705                         // it is, check the nearest point on the actual geometry
6706                         clippointtosurface(prog, ed, model, surface, p, clipped);
6707                         VectorSubtract(clipped, p, clipped);
6708                         dist += VectorLength2(clipped);
6709                         if (dist < bestdist)
6710                         {
6711                                 // that's closer too, store it as the best match
6712                                 best = surfacenum;
6713                                 bestdist = dist;
6714                         }
6715                 }
6716         }
6717         PRVM_G_FLOAT(OFS_RETURN) = best;
6718 }
6719 //PF_getsurfaceclippedpoint, // #439 vector(entity e, float s, vector p) getsurfaceclippedpoint = #439;
6720 void VM_getsurfaceclippedpoint(prvm_prog_t *prog)
6721 {
6722         prvm_edict_t *ed;
6723         dp_model_t *model;
6724         msurface_t *surface;
6725         vec3_t p, out;
6726         VM_SAFEPARMCOUNT(3, VM_te_getsurfaceclippedpoint);
6727         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6728         ed = PRVM_G_EDICT(OFS_PARM0);
6729         if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6730                 return;
6731         animatemodel(prog, model, ed);
6732         applytransform_inverted(prog, PRVM_G_VECTOR(OFS_PARM2), ed, p);
6733         clippointtosurface(prog, ed, model, surface, p, out);
6734         VectorAdd(out, PRVM_serveredictvector(ed, origin), PRVM_G_VECTOR(OFS_RETURN));
6735 }
6736
6737 //PF_getsurfacenumtriangles, // #??? float(entity e, float s) getsurfacenumtriangles = #???;
6738 void VM_getsurfacenumtriangles(prvm_prog_t *prog)
6739 {
6740        dp_model_t *model;
6741        msurface_t *surface;
6742        VM_SAFEPARMCOUNT(2, VM_SV_getsurfacenumtriangles);
6743        // return 0 if no such surface
6744        if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6745        {
6746                PRVM_G_FLOAT(OFS_RETURN) = 0;
6747                return;
6748        }
6749
6750        PRVM_G_FLOAT(OFS_RETURN) = surface->num_triangles;
6751 }
6752 //PF_getsurfacetriangle,     // #??? vector(entity e, float s, float n) getsurfacetriangle = #???;
6753 void VM_getsurfacetriangle(prvm_prog_t *prog)
6754 {
6755        const vec3_t d = {-1, -1, -1};
6756        prvm_edict_t *ed;
6757        dp_model_t *model;
6758        msurface_t *surface;
6759        int trinum;
6760        VM_SAFEPARMCOUNT(3, VM_SV_getsurfacetriangle);
6761        VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6762        ed = PRVM_G_EDICT(OFS_PARM0);
6763        if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6764                return;
6765        trinum = (int)PRVM_G_FLOAT(OFS_PARM2);
6766        if (trinum < 0 || trinum >= surface->num_triangles)
6767                return;
6768        // FIXME: implement rotation/scaling
6769        VectorMA(&(model->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[trinum * 3], surface->num_firstvertex, d, PRVM_G_VECTOR(OFS_RETURN));
6770 }
6771
6772 //
6773 // physics builtins
6774 //
6775
6776 #define VM_physics_ApplyCmd(ed,f) if (!ed->priv.server->ode_body) VM_physics_newstackfunction(prog, ed, f); else World_Physics_ApplyCmd(ed, f)
6777
6778 static edict_odefunc_t *VM_physics_newstackfunction(prvm_prog_t *prog, prvm_edict_t *ed, edict_odefunc_t *f)
6779 {
6780         edict_odefunc_t *newfunc, *func;
6781
6782         newfunc = (edict_odefunc_t *)Mem_Alloc(prog->progs_mempool, sizeof(edict_odefunc_t));
6783         memcpy(newfunc, f, sizeof(edict_odefunc_t));
6784         newfunc->next = NULL;
6785         if (!ed->priv.server->ode_func)
6786                 ed->priv.server->ode_func = newfunc;
6787         else
6788         {
6789                 for (func = ed->priv.server->ode_func; func->next; func = func->next);
6790                 func->next = newfunc;
6791         }
6792         return newfunc;
6793 }
6794
6795 // void(entity e, float physics_enabled) physics_enable = #;
6796 void VM_physics_enable(prvm_prog_t *prog)
6797 {
6798         prvm_edict_t *ed;
6799         edict_odefunc_t f;
6800         
6801         VM_SAFEPARMCOUNT(2, VM_physics_enable);
6802         ed = PRVM_G_EDICT(OFS_PARM0);
6803         if (!ed)
6804         {
6805                 if (developer.integer > 0)
6806                         VM_Warning(prog, "VM_physics_enable: null entity!\n");
6807                 return;
6808         }
6809         // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6810         if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6811         {
6812                 VM_Warning(prog, "VM_physics_enable: entity is not MOVETYPE_PHYSICS!\n");
6813                 return;
6814         }
6815         f.type = PRVM_G_FLOAT(OFS_PARM1) == 0 ? ODEFUNC_DISABLE : ODEFUNC_ENABLE;
6816         VM_physics_ApplyCmd(ed, &f);
6817 }
6818
6819 // void(entity e, vector force, vector relative_ofs) physics_addforce = #;
6820 void VM_physics_addforce(prvm_prog_t *prog)
6821 {
6822         prvm_edict_t *ed;
6823         edict_odefunc_t f;
6824         
6825         VM_SAFEPARMCOUNT(3, VM_physics_addforce);
6826         ed = PRVM_G_EDICT(OFS_PARM0);
6827         if (!ed)
6828         {
6829                 if (developer.integer > 0)
6830                         VM_Warning(prog, "VM_physics_addforce: null entity!\n");
6831                 return;
6832         }
6833         // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6834         if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6835         {
6836                 VM_Warning(prog, "VM_physics_addforce: entity is not MOVETYPE_PHYSICS!\n");
6837                 return;
6838         }
6839         f.type = ODEFUNC_FORCE;
6840         VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
6841         VectorCopy(PRVM_G_VECTOR(OFS_PARM2), f.v2);
6842         VM_physics_ApplyCmd(ed, &f);
6843 }
6844
6845 // void(entity e, vector torque) physics_addtorque = #;
6846 void VM_physics_addtorque(prvm_prog_t *prog)
6847 {
6848         prvm_edict_t *ed;
6849         edict_odefunc_t f;
6850         
6851         VM_SAFEPARMCOUNT(2, VM_physics_addtorque);
6852         ed = PRVM_G_EDICT(OFS_PARM0);
6853         if (!ed)
6854         {
6855                 if (developer.integer > 0)
6856                         VM_Warning(prog, "VM_physics_addtorque: null entity!\n");
6857                 return;
6858         }
6859         // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6860         if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6861         {
6862                 VM_Warning(prog, "VM_physics_addtorque: entity is not MOVETYPE_PHYSICS!\n");
6863                 return;
6864         }
6865         f.type = ODEFUNC_TORQUE;
6866         VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
6867         VM_physics_ApplyCmd(ed, &f);
6868 }