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