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