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