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