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
13 #include "cl_collision.h"
14 #include "clvm_cmds.h"
19 extern cvar_t prvm_backtraceforwarnings;
21 extern dllhandle_t ode_dll;
24 // LadyHavoc: changed this to NOT use a return statement, so that it can be used in functions that must return a value
25 void VM_Warning(prvm_prog_t *prog, const char *fmt, ...)
28 char msg[MAX_INPUTLINE];
29 static double recursive = -1;
30 int outfd = sys.outfd;
32 // set output to stderr
33 sys.outfd = fileno(stderr);
36 dpvsnprintf(msg,sizeof(msg),fmt,argptr);
39 Con_Printf(CON_WARN "%s VM warning: %s", prog->name, msg);
41 // TODO: either add a cvar/cmd to control the state dumping or replace some of the calls with Con_Printf [9/13/2006 Black]
42 if(prvm_backtraceforwarnings.integer && recursive != host.realtime) // NOTE: this compares to the time, just in case if PRVM_PrintState causes a Host_Error and keeps recursive set
44 recursive = host.realtime;
45 PRVM_PrintState(prog, 0);
49 // restore configured outfd
54 //============================================================================
57 // TODO DONE: move vm_files and vm_fssearchlist to prvm_prog_t struct
58 // TODO: move vm_files and vm_fssearchlist back [9/13/2006 Black]
59 // TODO: (move vm_files and vm_fssearchlist to prvm_prog_t struct again) [2007-01-23 LadyHavoc]
60 // TODO: will this war ever end? [2007-01-23 LadyHavoc]
62 void VM_CheckEmptyString(prvm_prog_t *prog, const char *s)
64 if (ISWHITESPACE(s[0]))
65 prog->error_cmd("%s: Bad string", prog->name);
68 qbool PRVM_ConsoleCommand(prvm_prog_t *prog, const char *text, size_t textlen, int *func, qbool preserve_self, int curself, double ptime, const char *error_message)
70 int restorevm_tempstringsbuf_cursize;
71 int save_self = 0; // hush compiler warning
80 save_self = PRVM_gameglobaledict(self);
82 PRVM_gameglobalfloat(time) = ptime;
83 PRVM_gameglobaledict(self) = curself;
84 restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
85 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, text, textlen);
86 prog->ExecuteProgram(prog, *func, error_message);
87 prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
89 PRVM_gameglobaledict(self) = save_self;
90 r = (int) PRVM_G_FLOAT(OFS_RETURN) != 0;
96 void VM_GenerateFrameGroupBlend(prvm_prog_t *prog, framegroupblend_t *framegroupblend, const prvm_edict_t *ed)
98 // self.frame is the interpolation target (new frame)
99 // self.frame1time is the animation base time for the interpolation target
100 // self.frame2 is the interpolation start (previous frame)
101 // self.frame2time is the animation base time for the interpolation start
102 // self.lerpfrac is the interpolation strength for self.frame2
103 // self.lerpfrac3 is the interpolation strength for self.frame3
104 // self.lerpfrac4 is the interpolation strength for self.frame4
105 // pitch angle on a player model where the animator set up 5 sets of
106 // animations and the csqc simply lerps between sets)
107 framegroupblend[0].frame = (int) PRVM_gameedictfloat(ed, frame );
108 framegroupblend[1].frame = (int) PRVM_gameedictfloat(ed, frame2 );
109 framegroupblend[2].frame = (int) PRVM_gameedictfloat(ed, frame3 );
110 framegroupblend[3].frame = (int) PRVM_gameedictfloat(ed, frame4 );
111 framegroupblend[0].start = PRVM_gameedictfloat(ed, frame1time);
112 framegroupblend[1].start = PRVM_gameedictfloat(ed, frame2time);
113 framegroupblend[2].start = PRVM_gameedictfloat(ed, frame3time);
114 framegroupblend[3].start = PRVM_gameedictfloat(ed, frame4time);
115 framegroupblend[1].lerp = PRVM_gameedictfloat(ed, lerpfrac );
116 framegroupblend[2].lerp = PRVM_gameedictfloat(ed, lerpfrac3 );
117 framegroupblend[3].lerp = PRVM_gameedictfloat(ed, lerpfrac4 );
118 // assume that the (missing) lerpfrac1 is whatever remains after lerpfrac2+lerpfrac3+lerpfrac4 are summed
119 framegroupblend[0].lerp = 1 - framegroupblend[1].lerp - framegroupblend[2].lerp - framegroupblend[3].lerp;
122 // LadyHavoc: quite tempting to break apart this function to reuse the
123 // duplicated code, but I suspect it is better for performance
125 void VM_FrameBlendFromFrameGroupBlend(frameblend_t *frameblend, const framegroupblend_t *framegroupblend, const model_t *model, double curtime)
127 int sub2, numframes, f, i, k;
128 int isfirstframegroup = true;
130 double sublerp, lerp, d;
131 const animscene_t *scene;
132 const framegroupblend_t *g;
133 frameblend_t *blend = frameblend;
135 memset(blend, 0, MAX_FRAMEBLENDS * sizeof(*blend));
137 // rpolzer: Not testing isanimated here - a model might have
138 // "animations" that move no vertices (but only bones), thus rendering
139 // may assume it's not animated while processing can't.
146 nolerp = ((model->type == mod_sprite) ? !r_lerpsprites.integer : !r_lerpmodels.integer) || (model->nolerp == true);
147 numframes = model->numframes;
148 for (k = 0, g = framegroupblend;k < MAX_FRAMEGROUPBLENDS;k++, g++)
151 if ((unsigned int)f >= (unsigned int)numframes)
153 if (developer_extra.integer)
154 Con_DPrintf("VM_FrameBlendFromFrameGroupBlend: no such frame %d in model %s\n", f, model->name);
162 if (isfirstframegroup)
165 isfirstframegroup = false;
170 if (model->animscenes)
172 scene = model->animscenes + f;
173 f = scene->firstframe;
174 if (scene->framecount > 1)
176 // this code path is only used on .zym models and torches
177 sublerp = scene->framerate * (curtime - g->start);
178 f = (int) floor(sublerp);
181 if (sublerp < (1.0 / 65536.0f))
183 if (sublerp > (65535.0f / 65536.0f))
189 f = (f % scene->framecount);
190 sub2 = (sub2 % scene->framecount);
192 f = bound(0, f, (scene->framecount - 1)) + scene->firstframe;
193 sub2 = bound(0, sub2, (scene->framecount - 1)) + scene->firstframe;
195 // two framelerps produced from one animation
198 for (i = 0;i < MAX_FRAMEBLENDS;i++)
200 if (blend[i].lerp <= 0 || blend[i].subframe == sub2)
202 blend[i].subframe = sub2;
208 d = (1 - sublerp) * lerp;
213 for (i = 0;i < MAX_FRAMEBLENDS;i++)
215 if (blend[i].lerp <= 0 || blend[i].subframe == f)
217 blend[i].subframe = f;
226 void VM_UpdateEdictSkeleton(prvm_prog_t *prog, prvm_edict_t *ed, const model_t *edmodel, const frameblend_t *frameblend)
228 if (ed->priv.server->skeleton.model != edmodel)
230 VM_RemoveEdictSkeleton(prog, ed);
231 ed->priv.server->skeleton.model = edmodel;
233 if (!ed->priv.server->skeleton.model || !ed->priv.server->skeleton.model->num_bones)
235 if(ed->priv.server->skeleton.relativetransforms)
236 Mem_Free(ed->priv.server->skeleton.relativetransforms);
237 ed->priv.server->skeleton.relativetransforms = NULL;
242 int skeletonindex = -1;
243 skeleton_t *skeleton;
244 skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
245 if (skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones)
247 // custom skeleton controlled by the game (FTE_CSQC_SKELETONOBJECTS)
248 if (!ed->priv.server->skeleton.relativetransforms)
249 ed->priv.server->skeleton.relativetransforms = (matrix4x4_t *)Mem_Alloc(prog->progs_mempool, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
250 memcpy(ed->priv.server->skeleton.relativetransforms, skeleton->relativetransforms, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
254 if(ed->priv.server->skeleton.relativetransforms)
255 Mem_Free(ed->priv.server->skeleton.relativetransforms);
256 ed->priv.server->skeleton.relativetransforms = NULL;
261 void VM_RemoveEdictSkeleton(prvm_prog_t *prog, prvm_edict_t *ed)
263 if (ed->priv.server->skeleton.relativetransforms)
264 Mem_Free(ed->priv.server->skeleton.relativetransforms);
265 memset(&ed->priv.server->skeleton, 0, sizeof(ed->priv.server->skeleton));
271 //============================================================================
275 // memccpy() is standard in POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD, C23.
276 // Microsoft supports it, but apparently complains if we use it.
278 #define memccpy _memccpy
280 size_t VM_VarString(prvm_prog_t *prog, int first, char *out, size_t outsize)
285 char *outend = out + outsize - 1;
287 // bones_was_here: && out < outend improves perf significantly in some tests that don't trigger the warning,
288 // which seems odd, surely it would only help when the warning is printed?
289 for (i = first;i < prog->argc && out < outend;i++)
291 s = PRVM_G_STRING((OFS_PARM0+i*3));
294 // like dp_stpecpy but with a VM_Warning for use with `prvm_backtraceforwarnings 1`
295 p = (char *)memccpy(out, s, '\0', (outend + 1) - out);
300 VM_Warning(prog, "%lu of %lu bytes available, will truncate %lu byte string \"%s\"\n", (unsigned long)(outend - out), (unsigned long)outsize - 1, (unsigned long)strlen(s), s);
309 return outsize - ((outend + 1) - out);
316 returns true if the extension is supported by the server
318 checkextension(extensionname)
322 // kind of helper function
323 static qbool checkextension(prvm_prog_t *prog, const char *name)
327 for (e = prog->extensionstring;*e;e++)
329 if(!strcasecmp(*e, name))
332 // special sheck for ODE
333 if (!strncasecmp("DP_PHYSICS_ODE", name, 14))
335 #ifndef LINK_TO_LIBODE
336 return ode_dll ? true : false;
338 #ifdef LINK_TO_LIBODE
347 // special sheck for d0_blind_id
348 if (!strcasecmp("DP_CRYPTO", name))
349 return Crypto_Available();
350 if (!strcasecmp("DP_QC_DIGEST_SHA256", name))
351 return Crypto_Available();
353 // special shreck for libcurl
354 if (!strcasecmp("DP_QC_URI_GET", name) || !strcasecmp("DP_QC_URI_POST", name))
355 return Curl_Available();
363 void VM_checkextension(prvm_prog_t *prog)
365 VM_SAFEPARMCOUNT(1,VM_checkextension);
367 PRVM_G_FLOAT(OFS_RETURN) = checkextension(prog, PRVM_G_STRING(OFS_PARM0));
374 This is a TERMINAL error, which will kill off the entire prog.
380 void VM_error(prvm_prog_t *prog)
383 char string[VM_TEMPSTRING_MAXSIZE];
385 VM_VarString(prog, 0, string, sizeof(string));
386 Con_Printf(CON_ERROR "======%s ERROR in %s:\n%s\n", prog->name, PRVM_GetString(prog, prog->xfunction->s_name), string);
387 ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
388 PRVM_ED_Print(prog, ed, NULL);
390 prog->error_cmd("%s: Program error in function %s:\n%s\nTip: read above for entity information\n", prog->name, PRVM_GetString(prog, prog->xfunction->s_name), string);
397 Dumps out self, then an error message. The program is aborted and self is
398 removed, but the level can continue.
403 void VM_objerror(prvm_prog_t *prog)
406 char string[VM_TEMPSTRING_MAXSIZE];
408 VM_VarString(prog, 0, string, sizeof(string));
409 Con_Printf(CON_ERROR "======OBJECT ERROR======\n"); // , prog->name, PRVM_GetString(prog->xfunction->s_name), string); // or include them? FIXME
410 ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
411 PRVM_ED_Print(prog, ed, NULL);
412 PRVM_ED_Free (prog, ed);
413 Con_Printf(CON_ERROR "%s OBJECT ERROR in %s:\n%s\nTip: read above for entity information\n", prog->name, PRVM_GetString(prog, prog->xfunction->s_name), string);
425 void VM_print(prvm_prog_t *prog)
427 char string[VM_TEMPSTRING_MAXSIZE];
429 VM_VarString(prog, 0, string, sizeof(string));
437 broadcast print to everyone on server
442 void VM_bprint(prvm_prog_t *prog)
444 char string[VM_TEMPSTRING_MAXSIZE];
448 VM_Warning(prog, "VM_bprint: game is not server(%s) !\n", prog->name);
452 VM_VarString(prog, 0, string, sizeof(string));
453 SV_BroadcastPrint(string);
458 VM_sprint (menu & client but only if server.active == true)
460 single print to a specific client
462 sprint(float clientnum,...[string])
465 void VM_sprint(prvm_prog_t *prog)
469 char string[VM_TEMPSTRING_MAXSIZE];
471 VM_SAFEPARMCOUNTRANGE(1, 8, VM_sprint);
473 //find client for this entity
474 clientnum = (int)PRVM_G_FLOAT(OFS_PARM0);
475 if (!sv.active || clientnum < 0 || clientnum >= svs.maxclients || !svs.clients[clientnum].active)
477 VM_Warning(prog, "VM_sprint: %s: invalid client or server is not active !\n", prog->name);
481 client = svs.clients + clientnum;
482 if (!client->netconnection)
485 VM_VarString(prog, 1, string, sizeof(string));
486 MSG_WriteChar(&client->netconnection->message,svc_print);
487 MSG_WriteString(&client->netconnection->message, string);
494 single print to the screen
499 void VM_centerprint(prvm_prog_t *prog)
501 char string[VM_TEMPSTRING_MAXSIZE];
503 VM_SAFEPARMCOUNTRANGE(1, 8, VM_centerprint);
504 VM_VarString(prog, 0, string, sizeof(string));
505 SCR_CenterPrint(string);
512 vector normalize(vector)
515 void VM_normalize(prvm_prog_t *prog)
521 VM_SAFEPARMCOUNT(1,VM_normalize);
523 value1 = PRVM_G_VECTOR(OFS_PARM0);
525 f = VectorLength2(value1);
529 VectorScale(value1, f, newvalue);
532 VectorClear(newvalue);
534 VectorCopy (newvalue, PRVM_G_VECTOR(OFS_RETURN));
544 void VM_vlen(prvm_prog_t *prog)
546 VM_SAFEPARMCOUNT(1,VM_vlen);
547 PRVM_G_FLOAT(OFS_RETURN) = VectorLength(PRVM_G_VECTOR(OFS_PARM0));
554 float vectoyaw(vector)
557 void VM_vectoyaw(prvm_prog_t *prog)
562 VM_SAFEPARMCOUNT(1,VM_vectoyaw);
564 value1 = PRVM_G_VECTOR(OFS_PARM0);
566 if (value1[1] == 0 && value1[0] == 0)
570 yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI);
575 PRVM_G_FLOAT(OFS_RETURN) = yaw;
583 vector vectoangles(vector[, vector])
586 void VM_vectoangles(prvm_prog_t *prog)
588 vec3_t result, forward, up;
589 VM_SAFEPARMCOUNTRANGE(1, 2,VM_vectoangles);
591 VectorCopy(PRVM_G_VECTOR(OFS_PARM0), forward);
594 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), up);
595 AnglesFromVectors(result, forward, up, true);
598 AnglesFromVectors(result, forward, NULL, true);
599 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
606 Returns a random number > 0 and < 1
611 void VM_random(prvm_prog_t *prog)
613 VM_SAFEPARMCOUNT(0,VM_random);
615 PRVM_G_FLOAT(OFS_RETURN) = lhrandom(0, 1);
622 localsound(string sample, float chan, float vol)
625 void VM_localsound(prvm_prog_t *prog)
630 VM_SAFEPARMCOUNTRANGE(1, 3,VM_localsound);
632 s = PRVM_G_STRING(OFS_PARM0);
635 chan = PRVM_G_FLOAT(OFS_PARM1);
636 vol = PRVM_G_FLOAT(OFS_PARM2) == 0 ? 1 : PRVM_G_FLOAT(OFS_PARM2);
637 if(!S_LocalSoundEx(s, chan, vol))
639 PRVM_G_FLOAT(OFS_RETURN) = -4;
640 VM_Warning(prog, "VM_localsound: Failed to play %s for %s !\n", s, prog->name);
644 else if(!S_LocalSound (s))
646 PRVM_G_FLOAT(OFS_RETURN) = -4;
647 VM_Warning(prog, "VM_localsound: Failed to play %s for %s !\n", s, prog->name);
651 PRVM_G_FLOAT(OFS_RETURN) = 1;
661 void VM_break(prvm_prog_t *prog)
663 prog->error_cmd("%s: break statement", prog->name);
666 //============================================================================
672 Sends text over to the client's execution buffer
674 [localcmd (string, ...) or]
678 void VM_localcmd_local(prvm_prog_t *prog)
680 char string[VM_TEMPSTRING_MAXSIZE];
681 VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd_local);
682 VM_VarString(prog, 0, string, sizeof(string));
683 Cbuf_AddText(cmd_local, string);
690 Sends text over to the server's execution buffer
692 [localcmd (string, ...) or]
696 void VM_localcmd_server(prvm_prog_t *prog)
698 char string[VM_TEMPSTRING_MAXSIZE];
699 VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd_server);
700 VM_VarString(prog, 0, string, sizeof(string));
701 Cbuf_AddText(cmd_local, string);
704 static qbool PRVM_Cvar_ReadOk(prvm_prog_t *prog, const char *string)
707 cvar = Cvar_FindVar(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask);
708 return ((cvar) && ((cvar->flags & CF_PRIVATE) == 0));
718 void VM_cvar(prvm_prog_t *prog)
720 char string[VM_TEMPSTRING_MAXSIZE];
721 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
722 VM_VarString(prog, 0, string, sizeof(string));
723 VM_CheckEmptyString(prog, string);
724 PRVM_G_FLOAT(OFS_RETURN) = PRVM_Cvar_ReadOk(prog, string) ? Cvar_VariableValue(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask) : 0;
731 float cvar_type (string)
732 float CVAR_TYPEFLAG_EXISTS = 1;
733 float CVAR_TYPEFLAG_SAVED = 2;
734 float CVAR_TYPEFLAG_PRIVATE = 4;
735 float CVAR_TYPEFLAG_ENGINE = 8;
736 float CVAR_TYPEFLAG_HASDESCRIPTION = 16;
737 float CVAR_TYPEFLAG_READONLY = 32;
740 void VM_cvar_type(prvm_prog_t *prog)
742 char string[VM_TEMPSTRING_MAXSIZE];
746 VM_SAFEPARMCOUNTRANGE(1, 8, VM_cvar_type);
747 VM_VarString(prog, 0, string, sizeof(string));
748 VM_CheckEmptyString(prog, string);
749 cvar = Cvar_FindVar(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask);
754 PRVM_G_FLOAT(OFS_RETURN) = 0;
755 return; // CVAR_TYPE_NONE
758 ret = 1; // CVAR_EXISTS
759 if(cvar->flags & CF_ARCHIVE)
760 ret |= 2; // CVAR_TYPE_SAVED
761 if(cvar->flags & CF_PRIVATE)
762 ret |= 4; // CVAR_TYPE_PRIVATE
763 if(!(cvar->flags & CF_ALLOCATED))
764 ret |= 8; // CVAR_TYPE_ENGINE
765 if(cvar->description != cvar_dummy_description)
766 ret |= 16; // CVAR_TYPE_HASDESCRIPTION
767 if(cvar->flags & CF_READONLY)
768 ret |= 32; // CVAR_TYPE_READONLY
770 PRVM_G_FLOAT(OFS_RETURN) = ret;
777 const string VM_cvar_string (string, ...)
780 void VM_cvar_string(prvm_prog_t *prog)
782 char cvar_name[VM_TEMPSTRING_MAXSIZE];
784 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_string);
785 VM_VarString(prog, 0, cvar_name, sizeof(cvar_name));
786 VM_CheckEmptyString(prog, cvar_name);
787 if (PRVM_Cvar_ReadOk(prog, cvar_name))
789 const char *cvar_string = Cvar_VariableString(prog->console_cmd->cvars, cvar_name, prog->console_cmd->cvars_flagsmask);
790 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cvar_string, strlen(cvar_string));
793 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
798 ========================
801 const string VM_cvar_defstring (string, ...)
802 ========================
804 void VM_cvar_defstring(prvm_prog_t *prog)
806 char cvar_name[VM_TEMPSTRING_MAXSIZE];
807 const char *cvar_defstring;
809 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_defstring);
810 VM_VarString(prog, 0, cvar_name, sizeof(cvar_name));
811 VM_CheckEmptyString(prog, cvar_name);
812 cvar_defstring = Cvar_VariableDefString(prog->console_cmd->cvars, cvar_name, prog->console_cmd->cvars_flagsmask);
813 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cvar_defstring, strlen(cvar_defstring));
817 ========================
820 const string VM_cvar_description (string, ...)
821 ========================
823 void VM_cvar_description(prvm_prog_t *prog)
825 char cvar_name[VM_TEMPSTRING_MAXSIZE];
826 const char *cvar_desc;
828 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_description);
829 VM_VarString(prog, 0, cvar_name, sizeof(cvar_name));
830 VM_CheckEmptyString(prog, cvar_name);
831 cvar_desc = Cvar_VariableDescription(prog->console_cmd->cvars, cvar_name, prog->console_cmd->cvars_flagsmask);
832 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cvar_desc, strlen(cvar_desc));
838 void cvar_set (string,string, ...)
841 void VM_cvar_set(prvm_prog_t *prog)
844 char value[VM_TEMPSTRING_MAXSIZE];
847 VM_SAFEPARMCOUNTRANGE(2,8,VM_cvar_set);
848 name = PRVM_G_STRING(OFS_PARM0);
849 VM_CheckEmptyString(prog, name);
850 cvar = Cvar_FindVar(prog->console_cmd->cvars, name, prog->console_cmd->cvars_flagsmask);
853 VM_Warning(prog, "VM_cvar_set: variable %s not found\n", name);
856 if (cvar->flags & CF_READONLY)
858 VM_Warning(prog, "VM_cvar_set: variable %s is read-only\n", cvar->name);
861 VM_VarString(prog, 1, value, sizeof(value));
862 Cvar_SetQuick(cvar, value);
872 void VM_dprint(prvm_prog_t *prog)
874 char string[VM_TEMPSTRING_MAXSIZE];
875 VM_SAFEPARMCOUNTRANGE(1, 8, VM_dprint);
876 VM_VarString(prog, 0, string, sizeof(string));
878 Con_DPrintf("%s", string);
880 Con_DPrintf("%s: %s", prog->name, string);
892 void VM_ftos(prvm_prog_t *prog)
898 VM_SAFEPARMCOUNT(1, VM_ftos);
900 v = PRVM_G_FLOAT(OFS_PARM0);
902 if ((prvm_vec_t)((prvm_int_t)v) == v)
903 slen = dpsnprintf(s, sizeof(s), "%.0f", v);
905 slen = dpsnprintf(s, sizeof(s), "%f", v);
906 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
917 void VM_fabs(prvm_prog_t *prog)
921 VM_SAFEPARMCOUNT(1,VM_fabs);
923 v = PRVM_G_FLOAT(OFS_PARM0);
924 PRVM_G_FLOAT(OFS_RETURN) = fabs(v);
935 void VM_vtos(prvm_prog_t *prog)
940 VM_SAFEPARMCOUNT(1,VM_vtos);
942 slen = dpsnprintf(s, sizeof(s), "'%5.1f %5.1f %5.1f'", PRVM_G_VECTOR(OFS_PARM0)[0], PRVM_G_VECTOR(OFS_PARM0)[1], PRVM_G_VECTOR(OFS_PARM0)[2]);
943 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
954 void VM_etos(prvm_prog_t *prog)
959 VM_SAFEPARMCOUNT(1, VM_etos);
961 slen = dpsnprintf(s, sizeof(s), "entity %i", PRVM_G_EDICTNUM(OFS_PARM0));
962 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
969 float stof(...[string])
972 void VM_stof(prvm_prog_t *prog)
974 char string[VM_TEMPSTRING_MAXSIZE];
975 VM_SAFEPARMCOUNTRANGE(1, 8, VM_stof);
976 VM_VarString(prog, 0, string, sizeof(string));
977 PRVM_G_FLOAT(OFS_RETURN) = atof(string);
981 ========================
985 ========================
987 void VM_itof(prvm_prog_t *prog)
989 VM_SAFEPARMCOUNT(1, VM_itof);
990 PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
994 ========================
997 entity ftoe(float num)
998 ========================
1000 void VM_ftoe(prvm_prog_t *prog)
1003 VM_SAFEPARMCOUNT(1, VM_ftoe);
1005 ent = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM0);
1006 if (ent < 0 || ent >= prog->max_edicts || PRVM_PROG_TO_EDICT(ent)->free)
1007 ent = 0; // return world instead of a free or invalid entity
1009 PRVM_G_INT(OFS_RETURN) = ent;
1013 ========================
1016 float etof(entity ent)
1017 ========================
1019 void VM_etof(prvm_prog_t *prog)
1021 VM_SAFEPARMCOUNT(1, VM_etof);
1022 PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICTNUM(OFS_PARM0);
1029 string strftime(float uselocaltime, string[, string ...])
1032 void VM_strftime(prvm_prog_t *prog)
1035 #if _MSC_VER >= 1400
1041 char fmt[VM_TEMPSTRING_MAXSIZE];
1042 char result[VM_TEMPSTRING_MAXSIZE];
1045 VM_SAFEPARMCOUNTRANGE(2, 8, VM_strftime);
1046 VM_VarString(prog, 1, fmt, sizeof(fmt));
1048 #if _MSC_VER >= 1400
1049 if (PRVM_G_FLOAT(OFS_PARM0))
1050 tmresult = localtime_s(&tm, &t);
1052 tmresult = gmtime_s(&tm, &t);
1055 if (PRVM_G_FLOAT(OFS_PARM0))
1062 PRVM_G_INT(OFS_RETURN) = 0;
1065 #if _MSC_VER >= 1400
1066 result_len = strftime(result, sizeof(result), fmt, &tm);
1068 result_len = strftime(result, sizeof(result), fmt, tm);
1070 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, result, result_len);
1081 void VM_spawn(prvm_prog_t *prog)
1084 VM_SAFEPARMCOUNT(0, VM_spawn);
1085 prog->xfunction->builtinsprofile += 20;
1086 ed = PRVM_ED_Alloc(prog);
1087 VM_RETURN_EDICT(ed);
1098 void VM_remove(prvm_prog_t *prog)
1101 prog->xfunction->builtinsprofile += 20;
1103 VM_SAFEPARMCOUNT(1, VM_remove);
1105 ed = PRVM_G_EDICT(OFS_PARM0);
1106 if( PRVM_NUM_FOR_EDICT(ed) <= prog->reserved_edicts )
1108 if (developer.integer > 0)
1109 VM_Warning(prog, "VM_remove: tried to remove the null entity or a reserved entity!\n" );
1113 if (developer.integer > 0)
1114 VM_Warning(prog, "VM_remove: tried to remove an already freed entity!\n" );
1117 PRVM_ED_Free (prog, ed);
1124 entity find(entity start, .string field, string match)
1128 void VM_find(prvm_prog_t *prog)
1135 VM_SAFEPARMCOUNT(3,VM_find);
1137 e = PRVM_G_EDICTNUM(OFS_PARM0);
1138 f = PRVM_G_INT(OFS_PARM1);
1139 s = PRVM_G_STRING(OFS_PARM2);
1141 // LadyHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1142 // expects it to find all the monsters, so we must be careful to support
1145 for (e++ ; e < prog->num_edicts ; e++)
1147 prog->xfunction->builtinsprofile++;
1148 ed = PRVM_EDICT_NUM(e);
1151 t = PRVM_E_STRING(ed,f);
1156 VM_RETURN_EDICT(ed);
1161 VM_RETURN_EDICT(prog->edicts);
1168 entity findfloat(entity start, .float field, float match)
1169 entity findentity(entity start, .entity field, entity match)
1172 // LadyHavoc: added this for searching float, int, and entity reference fields
1173 void VM_findfloat(prvm_prog_t *prog)
1180 VM_SAFEPARMCOUNT(3,VM_findfloat);
1182 e = PRVM_G_EDICTNUM(OFS_PARM0);
1183 f = PRVM_G_INT(OFS_PARM1);
1184 s = PRVM_G_FLOAT(OFS_PARM2);
1186 for (e++ ; e < prog->num_edicts ; e++)
1188 prog->xfunction->builtinsprofile++;
1189 ed = PRVM_EDICT_NUM(e);
1192 if (PRVM_E_FLOAT(ed,f) == s)
1194 VM_RETURN_EDICT(ed);
1199 VM_RETURN_EDICT(prog->edicts);
1206 entity findchain(.string field, string match)
1209 // chained search for strings in entity fields
1210 // entity(.string field, string match) findchain = #402;
1211 void VM_findchain(prvm_prog_t *prog)
1216 prvm_edict_t *ent, *chain;
1219 VM_SAFEPARMCOUNTRANGE(2,3,VM_findchain);
1222 chainfield = PRVM_G_INT(OFS_PARM2);
1224 chainfield = prog->fieldoffsets.chain;
1226 prog->error_cmd("VM_findchain: %s doesnt have the specified chain field !", prog->name);
1228 chain = prog->edicts;
1230 f = PRVM_G_INT(OFS_PARM0);
1231 s = PRVM_G_STRING(OFS_PARM1);
1233 // LadyHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1234 // expects it to find all the monsters, so we must be careful to support
1237 ent = PRVM_NEXT_EDICT(prog->edicts);
1238 for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1240 prog->xfunction->builtinsprofile++;
1243 t = PRVM_E_STRING(ent,f);
1249 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_NUM_FOR_EDICT(chain);
1253 VM_RETURN_EDICT(chain);
1260 entity findchainfloat(.string field, float match)
1261 entity findchainentity(.string field, entity match)
1264 // LadyHavoc: chained search for float, int, and entity reference fields
1265 // entity(.string field, float match) findchainfloat = #403;
1266 void VM_findchainfloat(prvm_prog_t *prog)
1271 prvm_edict_t *ent, *chain;
1274 VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainfloat);
1277 chainfield = PRVM_G_INT(OFS_PARM2);
1279 chainfield = prog->fieldoffsets.chain;
1281 prog->error_cmd("VM_findchainfloat: %s doesnt have the specified chain field !", prog->name);
1283 chain = (prvm_edict_t *)prog->edicts;
1285 f = PRVM_G_INT(OFS_PARM0);
1286 s = PRVM_G_FLOAT(OFS_PARM1);
1288 ent = PRVM_NEXT_EDICT(prog->edicts);
1289 for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1291 prog->xfunction->builtinsprofile++;
1294 if (PRVM_E_FLOAT(ent,f) != s)
1297 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1301 VM_RETURN_EDICT(chain);
1305 ========================
1308 entity findflags(entity start, .float field, float match)
1309 ========================
1311 // LadyHavoc: search for flags in float fields
1312 void VM_findflags(prvm_prog_t *prog)
1319 VM_SAFEPARMCOUNT(3, VM_findflags);
1322 e = PRVM_G_EDICTNUM(OFS_PARM0);
1323 f = PRVM_G_INT(OFS_PARM1);
1324 s = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM2);
1326 for (e++ ; e < prog->num_edicts ; e++)
1328 prog->xfunction->builtinsprofile++;
1329 ed = PRVM_EDICT_NUM(e);
1332 if (!PRVM_E_FLOAT(ed,f))
1334 if ((prvm_int_t)PRVM_E_FLOAT(ed,f) & s)
1336 VM_RETURN_EDICT(ed);
1341 VM_RETURN_EDICT(prog->edicts);
1345 ========================
1348 entity findchainflags(.float field, float match)
1349 ========================
1351 // LadyHavoc: chained search for flags in float fields
1352 void VM_findchainflags(prvm_prog_t *prog)
1357 prvm_edict_t *ent, *chain;
1360 VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainflags);
1363 chainfield = PRVM_G_INT(OFS_PARM2);
1365 chainfield = prog->fieldoffsets.chain;
1367 prog->error_cmd("VM_findchainflags: %s doesnt have the specified chain field !", prog->name);
1369 chain = (prvm_edict_t *)prog->edicts;
1371 f = PRVM_G_INT(OFS_PARM0);
1372 s = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM1);
1374 ent = PRVM_NEXT_EDICT(prog->edicts);
1375 for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1377 prog->xfunction->builtinsprofile++;
1380 if (!PRVM_E_FLOAT(ent,f))
1382 if (!((prvm_int_t)PRVM_E_FLOAT(ent,f) & s))
1385 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1389 VM_RETURN_EDICT(chain);
1396 string precache_sound (string sample)
1399 void VM_precache_sound(prvm_prog_t *prog)
1403 VM_SAFEPARMCOUNT(1, VM_precache_sound);
1405 s = PRVM_G_STRING(OFS_PARM0);
1406 PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1407 //VM_CheckEmptyString(prog, s);
1409 if(snd_initialized.integer && !S_PrecacheSound(s, true, true))
1411 VM_Warning(prog, "VM_precache_sound: Failed to load %s for %s\n", s, prog->name);
1420 returns the same string as output
1422 does nothing, only used by qcc to build .pak archives
1425 void VM_precache_file(prvm_prog_t *prog)
1427 VM_SAFEPARMCOUNT(1,VM_precache_file);
1428 // precache_file is only used to copy files with qcc, it does nothing
1429 PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1439 void VM_coredump(prvm_prog_t *prog)
1441 VM_SAFEPARMCOUNT(0,VM_coredump);
1443 Cbuf_AddText(cmd_local, "prvm_edicts ");
1444 Cbuf_AddText(cmd_local, prog->name);
1445 Cbuf_AddText(cmd_local, "\n");
1455 void VM_stackdump(prvm_prog_t *prog)
1457 VM_SAFEPARMCOUNT(0, VM_stackdump);
1459 PRVM_StackTrace(prog);
1470 void VM_crash(prvm_prog_t *prog)
1472 VM_SAFEPARMCOUNT(0, VM_crash);
1474 prog->error_cmd("Crash called by %s",prog->name);
1484 void VM_traceon(prvm_prog_t *prog)
1486 VM_SAFEPARMCOUNT(0,VM_traceon);
1498 void VM_traceoff(prvm_prog_t *prog)
1500 VM_SAFEPARMCOUNT(0,VM_traceoff);
1502 prog->trace = false;
1512 void VM_eprint(prvm_prog_t *prog)
1514 VM_SAFEPARMCOUNT(1,VM_eprint);
1516 PRVM_ED_PrintNum (prog, PRVM_G_EDICTNUM(OFS_PARM0), NULL);
1526 void VM_rint(prvm_prog_t *prog)
1529 VM_SAFEPARMCOUNT(1,VM_rint);
1531 f = PRVM_G_FLOAT(OFS_PARM0);
1533 PRVM_G_FLOAT(OFS_RETURN) = floor(f + 0.5);
1535 PRVM_G_FLOAT(OFS_RETURN) = ceil(f - 0.5);
1545 void VM_floor(prvm_prog_t *prog)
1547 VM_SAFEPARMCOUNT(1,VM_floor);
1549 PRVM_G_FLOAT(OFS_RETURN) = floor(PRVM_G_FLOAT(OFS_PARM0));
1559 void VM_ceil(prvm_prog_t *prog)
1561 VM_SAFEPARMCOUNT(1,VM_ceil);
1563 PRVM_G_FLOAT(OFS_RETURN) = ceil(PRVM_G_FLOAT(OFS_PARM0));
1571 entity nextent(entity)
1574 void VM_nextent(prvm_prog_t *prog)
1579 VM_SAFEPARMCOUNT(1, VM_nextent);
1581 i = PRVM_G_EDICTNUM(OFS_PARM0);
1584 prog->xfunction->builtinsprofile++;
1586 if (i == prog->num_edicts)
1588 VM_RETURN_EDICT(prog->edicts);
1591 ent = PRVM_EDICT_NUM(i);
1594 VM_RETURN_EDICT(ent);
1600 //=============================================================================
1607 changelevel(string map)
1610 void VM_changelevel(prvm_prog_t *prog)
1613 VM_SAFEPARMCOUNT(1, VM_changelevel);
1617 VM_Warning(prog, "VM_changelevel: game is not server (%s)\n", prog->name);
1621 // make sure we don't issue two changelevels
1622 if (svs.changelevel_issued)
1624 svs.changelevel_issued = true;
1626 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "changelevel %s\n", PRVM_G_STRING(OFS_PARM0)));
1636 void VM_sin(prvm_prog_t *prog)
1638 VM_SAFEPARMCOUNT(1,VM_sin);
1639 PRVM_G_FLOAT(OFS_RETURN) = sin(PRVM_G_FLOAT(OFS_PARM0));
1648 void VM_cos(prvm_prog_t *prog)
1650 VM_SAFEPARMCOUNT(1,VM_cos);
1651 PRVM_G_FLOAT(OFS_RETURN) = cos(PRVM_G_FLOAT(OFS_PARM0));
1661 void VM_sqrt(prvm_prog_t *prog)
1663 VM_SAFEPARMCOUNT(1,VM_sqrt);
1664 PRVM_G_FLOAT(OFS_RETURN) = sqrt(PRVM_G_FLOAT(OFS_PARM0));
1674 void VM_asin(prvm_prog_t *prog)
1676 VM_SAFEPARMCOUNT(1,VM_asin);
1677 PRVM_G_FLOAT(OFS_RETURN) = asin(PRVM_G_FLOAT(OFS_PARM0));
1686 void VM_acos(prvm_prog_t *prog)
1688 VM_SAFEPARMCOUNT(1,VM_acos);
1689 PRVM_G_FLOAT(OFS_RETURN) = acos(PRVM_G_FLOAT(OFS_PARM0));
1698 void VM_atan(prvm_prog_t *prog)
1700 VM_SAFEPARMCOUNT(1,VM_atan);
1701 PRVM_G_FLOAT(OFS_RETURN) = atan(PRVM_G_FLOAT(OFS_PARM0));
1707 float atan2(float,float)
1710 void VM_atan2(prvm_prog_t *prog)
1712 VM_SAFEPARMCOUNT(2,VM_atan2);
1713 PRVM_G_FLOAT(OFS_RETURN) = atan2(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1722 void VM_tan(prvm_prog_t *prog)
1724 VM_SAFEPARMCOUNT(1,VM_tan);
1725 PRVM_G_FLOAT(OFS_RETURN) = tan(PRVM_G_FLOAT(OFS_PARM0));
1732 Returns a vector of length < 1 and > 0
1737 void VM_randomvec(prvm_prog_t *prog)
1740 VM_SAFEPARMCOUNT(0, VM_randomvec);
1742 VectorCopy(temp, PRVM_G_VECTOR(OFS_RETURN));
1745 //=============================================================================
1751 float registercvar (string name, string value[, float flags])
1754 void VM_registercvar(prvm_prog_t *prog)
1756 const char *name, *value;
1759 VM_SAFEPARMCOUNTRANGE(2, 3, VM_registercvar);
1761 name = PRVM_G_STRING(OFS_PARM0);
1762 value = PRVM_G_STRING(OFS_PARM1);
1763 flags = prog->argc >= 3 ? (int)PRVM_G_FLOAT(OFS_PARM2) : 0;
1764 PRVM_G_FLOAT(OFS_RETURN) = 0;
1766 if(flags > CF_MAXFLAGSVAL)
1769 // first check to see if it has already been defined
1770 if (Cvar_FindVar (prog->console_cmd->cvars, name, prog->console_cmd->cvars_flagsmask))
1773 // check for overlap with a command
1774 if (Cmd_Exists(cmd_local, name))
1776 VM_Warning(prog, "VM_registercvar: %s is a command\n", name);
1780 Cvar_Get(prog->console_cmd->cvars, name, value, prog->console_cmd->cvars_flagsmask | flags, NULL);
1782 PRVM_G_FLOAT(OFS_RETURN) = 1; // success
1790 returns the minimum of two supplied floats
1792 float min(float a, float b, ...[float])
1795 void VM_min(prvm_prog_t *prog)
1797 VM_SAFEPARMCOUNTRANGE(2, 8, VM_min);
1798 // LadyHavoc: 3+ argument enhancement suggested by FrikaC
1799 if (prog->argc >= 3)
1802 float f = PRVM_G_FLOAT(OFS_PARM0);
1803 for (i = 1;i < prog->argc;i++)
1804 if (f > PRVM_G_FLOAT((OFS_PARM0+i*3)))
1805 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1806 PRVM_G_FLOAT(OFS_RETURN) = f;
1809 PRVM_G_FLOAT(OFS_RETURN) = min(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1816 returns the maximum of two supplied floats
1818 float max(float a, float b, ...[float])
1821 void VM_max(prvm_prog_t *prog)
1823 VM_SAFEPARMCOUNTRANGE(2, 8, VM_max);
1824 // LadyHavoc: 3+ argument enhancement suggested by FrikaC
1825 if (prog->argc >= 3)
1828 float f = PRVM_G_FLOAT(OFS_PARM0);
1829 for (i = 1;i < prog->argc;i++)
1830 if (f < PRVM_G_FLOAT((OFS_PARM0+i*3)))
1831 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1832 PRVM_G_FLOAT(OFS_RETURN) = f;
1835 PRVM_G_FLOAT(OFS_RETURN) = max(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1842 returns number bounded by supplied range
1844 float bound(float min, float value, float max)
1847 void VM_bound(prvm_prog_t *prog)
1849 VM_SAFEPARMCOUNT(3,VM_bound);
1850 PRVM_G_FLOAT(OFS_RETURN) = bound(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1), PRVM_G_FLOAT(OFS_PARM2));
1857 returns a raised to power b
1859 float pow(float a, float b)
1862 void VM_pow(prvm_prog_t *prog)
1864 VM_SAFEPARMCOUNT(2,VM_pow);
1865 PRVM_G_FLOAT(OFS_RETURN) = pow(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1868 void VM_log(prvm_prog_t *prog)
1870 VM_SAFEPARMCOUNT(1,VM_log);
1871 PRVM_G_FLOAT(OFS_RETURN) = log(PRVM_G_FLOAT(OFS_PARM0));
1874 void VM_Files_Init(prvm_prog_t *prog)
1877 for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1878 prog->openfiles[i] = NULL;
1881 void VM_Files_CloseAll(prvm_prog_t *prog)
1884 for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1886 if (prog->openfiles[i])
1887 FS_Close(prog->openfiles[i]);
1888 prog->openfiles[i] = NULL;
1892 static qfile_t *VM_GetFileHandle(prvm_prog_t *prog, int index)
1894 if (index < 0 || index >= PRVM_MAX_OPENFILES)
1896 Con_Printf("VM_GetFileHandle: invalid file handle %i used in %s\n", index, prog->name);
1899 if (prog->openfiles[index] == NULL)
1901 Con_Printf("VM_GetFileHandle: no such file handle %i (or file has been closed) in %s\n", index, prog->name);
1904 return prog->openfiles[index];
1911 float fopen(string filename, float mode)
1914 // float(string filename, float mode) fopen = #110;
1915 // opens a file inside quake/gamedir/data/ (mode is FILE_READ, FILE_APPEND, or FILE_WRITE),
1916 // returns fhandle >= 0 if successful, or fhandle < 0 if unable to open file for any reason
1917 void VM_fopen(prvm_prog_t *prog)
1920 const char *modestring, *filename;
1923 VM_SAFEPARMCOUNT(2,VM_fopen);
1925 for (filenum = 0;filenum < PRVM_MAX_OPENFILES;filenum++)
1926 if (prog->openfiles[filenum] == NULL)
1928 if (filenum >= PRVM_MAX_OPENFILES)
1930 PRVM_G_FLOAT(OFS_RETURN) = -2;
1931 VM_Warning(prog, "VM_fopen: %s ran out of file handles (%i)\n", prog->name, PRVM_MAX_OPENFILES);
1934 filename = PRVM_G_STRING(OFS_PARM0);
1935 mode = (int)PRVM_G_FLOAT(OFS_PARM1);
1938 case 0: // FILE_READ
1940 prog->openfiles[filenum] = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "data/%s", filename), false);
1941 if (prog->openfiles[filenum] == NULL)
1942 prog->openfiles[filenum] = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "%s", filename), false);
1944 case 1: // FILE_APPEND
1946 prog->openfiles[filenum] = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "data/%s", filename), modestring, false);
1948 case 2: // FILE_WRITE
1950 prog->openfiles[filenum] = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "data/%s", filename), modestring, false);
1953 PRVM_G_FLOAT(OFS_RETURN) = -3;
1954 VM_Warning(prog, "VM_fopen: %s: no such mode %i (valid: 0 = read, 1 = append, 2 = write)\n", prog->name, mode);
1958 if (prog->openfiles[filenum] == NULL)
1960 PRVM_G_FLOAT(OFS_RETURN) = -1;
1961 if (developer_extra.integer)
1962 VM_Warning(prog, "VM_fopen: %s: %s mode %s failed\n", prog->name, filename, modestring);
1966 PRVM_G_FLOAT(OFS_RETURN) = filenum;
1967 if (developer_extra.integer)
1968 Con_DPrintf("VM_fopen: %s: %s mode %s opened as #%i\n", prog->name, filename, modestring, filenum);
1969 prog->openfiles_origin[filenum] = PRVM_AllocationOrigin(prog);
1977 fclose(float fhandle)
1980 //void(float fhandle) fclose = #111; // closes a file
1981 void VM_fclose(prvm_prog_t *prog)
1985 VM_SAFEPARMCOUNT(1,VM_fclose);
1987 filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1988 if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1990 VM_Warning(prog, "VM_fclose: invalid file handle %i used in %s\n", filenum, prog->name);
1993 if (prog->openfiles[filenum] == NULL)
1995 VM_Warning(prog, "VM_fclose: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
1998 FS_Close(prog->openfiles[filenum]);
1999 prog->openfiles[filenum] = NULL;
2000 if(prog->openfiles_origin[filenum])
2001 PRVM_Free((char *)prog->openfiles_origin[filenum]);
2002 if (developer_extra.integer)
2003 Con_DPrintf("VM_fclose: %s: #%i closed\n", prog->name, filenum);
2010 string fgets(float fhandle)
2013 //string(float fhandle) fgets = #112; // reads a line of text from the file and returns as a tempstring
2014 void VM_fgets(prvm_prog_t *prog)
2017 char string[VM_TEMPSTRING_MAXSIZE];
2020 VM_SAFEPARMCOUNT(1,VM_fgets);
2022 // set the return value regardless of any possible errors
2023 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2025 filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
2026 if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
2028 VM_Warning(prog, "VM_fgets: invalid file handle %i used in %s\n", filenum, prog->name);
2031 if (prog->openfiles[filenum] == NULL)
2033 VM_Warning(prog, "VM_fgets: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
2039 c = FS_Getc(prog->openfiles[filenum]);
2040 if (c == '\r' || c == '\n' || c < 0)
2042 if (end < VM_TEMPSTRING_MAXSIZE - 1)
2046 // remove \n following \r
2049 c = FS_Getc(prog->openfiles[filenum]);
2051 FS_UnGetc(prog->openfiles[filenum], (unsigned char)c);
2053 if (developer_extra.integer)
2054 Con_DPrintf("fgets: %s: %s\n", prog->name, string);
2056 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, end);
2063 fputs(float fhandle, string s)
2066 //void(float fhandle, string s) fputs = #113; // writes a line of text to the end of the file
2067 void VM_fputs(prvm_prog_t *prog)
2069 size_t stringlength;
2070 char string[VM_TEMPSTRING_MAXSIZE];
2073 VM_SAFEPARMCOUNT(2,VM_fputs);
2075 filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
2076 if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
2078 VM_Warning(prog, "VM_fputs: invalid file handle %i used in %s\n", filenum, prog->name);
2081 if (prog->openfiles[filenum] == NULL)
2083 VM_Warning(prog, "VM_fputs: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
2086 stringlength = VM_VarString(prog, 1, string, sizeof(string));
2088 FS_Write(prog->openfiles[filenum], string, stringlength);
2089 if (developer_extra.integer)
2090 Con_DPrintf("fputs: %s: %s\n", prog->name, string);
2097 writetofile(float fhandle, entity ent)
2100 void VM_writetofile(prvm_prog_t *prog)
2105 VM_SAFEPARMCOUNT(2, VM_writetofile);
2107 file = VM_GetFileHandle(prog, (int)PRVM_G_FLOAT(OFS_PARM0));
2110 VM_Warning(prog, "VM_writetofile: invalid or closed file handle\n");
2114 ent = PRVM_G_EDICT(OFS_PARM1);
2117 VM_Warning(prog, "VM_writetofile: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2121 PRVM_ED_Write (prog, file, ent);
2124 // KrimZon - DP_QC_ENTITYDATA
2129 float() numentityfields
2130 Return the number of entity fields - NOT offsets
2133 void VM_numentityfields(prvm_prog_t *prog)
2135 PRVM_G_FLOAT(OFS_RETURN) = prog->numfielddefs;
2138 // KrimZon - DP_QC_ENTITYDATA
2143 string(float fieldnum) entityfieldname
2144 Return name of the specified field as a string, or empty if the field is invalid (warning)
2147 void VM_entityfieldname(prvm_prog_t *prog)
2150 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2152 if (i < 0 || i >= prog->numfielddefs)
2154 VM_Warning(prog, "VM_entityfieldname: %s: field index out of bounds\n", prog->name);
2155 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2159 d = &prog->fielddefs[i];
2160 PRVM_G_INT(OFS_RETURN) = d->s_name; // presuming that s_name points to a string already
2163 // KrimZon - DP_QC_ENTITYDATA
2168 float(float fieldnum) entityfieldtype
2171 void VM_entityfieldtype(prvm_prog_t *prog)
2174 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2176 if (i < 0 || i >= prog->numfielddefs)
2178 VM_Warning(prog, "VM_entityfieldtype: %s: field index out of bounds\n", prog->name);
2179 PRVM_G_FLOAT(OFS_RETURN) = -1.0;
2183 d = &prog->fielddefs[i];
2184 PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t)d->type;
2187 // KrimZon - DP_QC_ENTITYDATA
2190 VM_getentityfieldstring
2192 string(float fieldnum, entity ent) getentityfieldstring
2195 void VM_getentityfieldstring(prvm_prog_t *prog)
2197 // put the data into a string
2202 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2203 char valuebuf[MAX_INPUTLINE];
2205 if (i < 0 || i >= prog->numfielddefs)
2207 VM_Warning(prog, "VM_entityfielddata: %s: field index out of bounds\n", prog->name);
2208 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2212 d = &prog->fielddefs[i];
2215 ent = PRVM_G_EDICT(OFS_PARM1);
2218 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2219 VM_Warning(prog, "VM_entityfielddata: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2222 val = (prvm_eval_t *)(ent->fields.fp + d->ofs);
2224 // if it's 0 or blank, return an empty string
2225 type = d->type & ~DEF_SAVEGLOBAL;
2226 for (j=0 ; j<prvm_type_size[type] ; j++)
2227 if (val->ivector[j])
2229 if (j == prvm_type_size[type])
2231 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2235 PRVM_UglyValueString(prog, (etype_t)d->type, val, valuebuf, sizeof(valuebuf));
2236 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, valuebuf, strlen(valuebuf));
2239 // KrimZon - DP_QC_ENTITYDATA
2242 VM_putentityfieldstring
2244 float(float fieldnum, entity ent, string s) putentityfieldstring
2247 void VM_putentityfieldstring(prvm_prog_t *prog)
2251 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2253 if (i < 0 || i >= prog->numfielddefs)
2255 VM_Warning(prog, "VM_entityfielddata: %s: field index out of bounds\n", prog->name);
2256 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2260 d = &prog->fielddefs[i];
2263 ent = PRVM_G_EDICT(OFS_PARM1);
2266 VM_Warning(prog, "VM_entityfielddata: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2267 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2271 // parse the string into the value
2272 PRVM_G_FLOAT(OFS_RETURN) = ( PRVM_ED_ParseEpair(prog, ent, d, PRVM_G_STRING(OFS_PARM2), false) ) ? 1.0f : 0.0f;
2279 float strlen(string s)
2282 //float(string s) strlen = #114; // returns how many characters are in a string
2283 void VM_strlen(prvm_prog_t *prog)
2285 VM_SAFEPARMCOUNT(1,VM_strlen);
2287 //PRVM_G_FLOAT(OFS_RETURN) = strlen(PRVM_G_STRING(OFS_PARM0));
2288 PRVM_G_FLOAT(OFS_RETURN) = u8_strlen(PRVM_G_STRING(OFS_PARM0));
2291 // DRESK - Decolorized String
2296 string strdecolorize(string s)
2299 // string (string s) strdecolorize = #472; // returns the passed in string with color codes stripped
2300 void VM_strdecolorize(prvm_prog_t *prog)
2302 char szNewString[VM_TEMPSTRING_MAXSIZE];
2303 size_t szNewString_len;
2304 const char *szString;
2307 VM_SAFEPARMCOUNT(1,VM_strdecolorize);
2308 szString = PRVM_G_STRING(OFS_PARM0);
2309 szNewString_len = COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), true);
2310 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
2313 // DRESK - String Length (not counting color codes)
2318 float strlennocol(string s)
2321 // float(string s) strlennocol = #471; // returns how many characters are in a string not including color codes
2322 // For example, ^2Dresk returns a length of 5
2323 void VM_strlennocol(prvm_prog_t *prog)
2325 const char *szString;
2328 VM_SAFEPARMCOUNT(1,VM_strlennocol);
2330 szString = PRVM_G_STRING(OFS_PARM0);
2332 //nCnt = (int)COM_StringLengthNoColors(szString, 0, NULL);
2333 nCnt = (int)u8_COM_StringLengthNoColors(szString, 0, NULL);
2335 PRVM_G_FLOAT(OFS_RETURN) = nCnt;
2338 // DRESK - String to Uppercase and Lowercase
2343 string strtolower(string s)
2346 // string (string s) strtolower = #480; // returns passed in string in lowercase form
2347 void VM_strtolower(prvm_prog_t *prog)
2349 char szNewString[VM_TEMPSTRING_MAXSIZE];
2350 size_t szNewString_len;
2351 const char *szString;
2354 VM_SAFEPARMCOUNT(1,VM_strtolower);
2355 szString = PRVM_G_STRING(OFS_PARM0);
2357 szNewString_len = COM_ToLowerString(szString, szNewString, sizeof(szNewString) );
2359 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
2366 string strtoupper(string s)
2369 // string (string s) strtoupper = #481; // returns passed in string in uppercase form
2370 void VM_strtoupper(prvm_prog_t *prog)
2372 char szNewString[VM_TEMPSTRING_MAXSIZE];
2373 size_t szNewString_len;
2374 const char *szString;
2377 VM_SAFEPARMCOUNT(1,VM_strtoupper);
2378 szString = PRVM_G_STRING(OFS_PARM0);
2380 szNewString_len = COM_ToUpperString(szString, szNewString, sizeof(szNewString) );
2382 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
2389 string strcat(string s, string...)
2392 //string(string s, string...) strcat = #115;
2393 // concatenates strings (for example "abc", "def" would return "abcdef")
2394 // and returns as a tempstring
2395 void VM_strcat(prvm_prog_t *prog)
2397 char s[VM_TEMPSTRING_MAXSIZE];
2400 VM_SAFEPARMCOUNTRANGE(1, 8, VM_strcat);
2402 slen = VM_VarString(prog, 0, s, sizeof(s));
2403 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
2410 string substring(string s, float start, float length)
2413 // string(string s, float start, float length) substring = #116;
2414 // returns a section of a string as a tempstring
2415 void VM_substring(prvm_prog_t *prog)
2418 int u_slength = 0, u_start;
2421 char string[VM_TEMPSTRING_MAXSIZE];
2423 VM_SAFEPARMCOUNT(3,VM_substring);
2426 s = PRVM_G_STRING(OFS_PARM0);
2427 start = (int)PRVM_G_FLOAT(OFS_PARM1);
2428 length = (int)PRVM_G_FLOAT(OFS_PARM2);
2429 slength = strlen(s);
2431 if (start < 0) // FTE_STRINGS feature
2433 start = bound(0, start, slength);
2435 if (length < 0) // FTE_STRINGS feature
2436 length += slength - start + 1;
2437 maxlen = min((int)sizeof(string) - 1, slength - start);
2438 length = bound(0, length, maxlen);
2440 memcpy(string, s + start, length);
2442 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2445 s = PRVM_G_STRING(OFS_PARM0);
2446 start = (int)PRVM_G_FLOAT(OFS_PARM1);
2447 length = (int)PRVM_G_FLOAT(OFS_PARM2);
2449 if (start < 0) // FTE_STRINGS feature
2451 u_slength = (int)u8_strlen(s);
2453 start = bound(0, start, u_slength);
2456 if (length < 0) // FTE_STRINGS feature
2458 if (!u_slength) // it's not calculated when it's not needed above
2459 u_slength = (int)u8_strlen(s);
2460 length += u_slength - start + 1;
2463 // positive start, positive length
2464 u_start = u8_byteofs(s, start, NULL);
2467 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2470 u_length = u8_bytelen(s + u_start, length);
2471 if (u_length >= sizeof(string)-1)
2472 u_length = sizeof(string)-1;
2474 memcpy(string, s + u_start, u_length);
2475 string[u_length] = '\0';
2476 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, u_length);
2483 string(string search, string replace, string subject) strreplace = #484;
2486 // replaces all occurrences of search with replace in the string subject, and returns the result
2487 void VM_strreplace(prvm_prog_t *prog)
2490 const char *search, *replace, *subject;
2491 char string[VM_TEMPSTRING_MAXSIZE];
2492 int search_len, replace_len, subject_len;
2494 VM_SAFEPARMCOUNT(3,VM_strreplace);
2496 search = PRVM_G_STRING(OFS_PARM0);
2497 replace = PRVM_G_STRING(OFS_PARM1);
2498 subject = PRVM_G_STRING(OFS_PARM2);
2500 search_len = (int)strlen(search);
2501 replace_len = (int)strlen(replace);
2502 subject_len = (int)strlen(subject);
2505 for (i = 0; i <= subject_len - search_len; i++)
2507 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2508 if (subject[i+j] != search[j])
2510 if (j == search_len)
2512 // NOTE: if search_len == 0, we always hit THIS case, and never the other
2513 // found it at offset 'i'
2514 for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2515 string[si++] = replace[j];
2518 i += search_len - 1;
2522 // the above would subtract 1 from i... so we
2523 // don't do that, but instead output the next
2525 if (si < (int)sizeof(string) - 1)
2526 string[si++] = subject[i];
2531 // in THIS case, we know search_len > 0, thus i < subject_len
2533 if (si < (int)sizeof(string) - 1)
2534 string[si++] = subject[i];
2537 // remaining chars (these cannot match)
2538 for (; i < subject_len; i++)
2539 if (si < (int)sizeof(string) - 1)
2540 string[si++] = subject[i];
2543 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, si);
2550 string(string search, string replace, string subject) strireplace = #485;
2553 // case-insensitive version of strreplace
2554 void VM_strireplace(prvm_prog_t *prog)
2557 const char *search, *replace, *subject;
2558 char string[VM_TEMPSTRING_MAXSIZE];
2559 int search_len, replace_len, subject_len;
2561 VM_SAFEPARMCOUNT(3, VM_strireplace);
2563 search = PRVM_G_STRING(OFS_PARM0);
2564 replace = PRVM_G_STRING(OFS_PARM1);
2565 subject = PRVM_G_STRING(OFS_PARM2);
2567 search_len = (int)strlen(search);
2568 replace_len = (int)strlen(replace);
2569 subject_len = (int)strlen(subject);
2572 for (i = 0; i <= subject_len - search_len; i++)
2574 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2575 if (tolower(subject[i+j]) != tolower(search[j]))
2577 if (j == search_len)
2579 // NOTE: if search_len == 0, we always hit THIS case, and never the other
2580 // found it at offset 'i'
2581 for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2582 string[si++] = replace[j];
2585 i += search_len - 1;
2589 // the above would subtract 1 from i... so we
2590 // don't do that, but instead output the next
2592 if (si < (int)sizeof(string) - 1)
2593 string[si++] = subject[i];
2598 // in THIS case, we know search_len > 0, thus i < subject_len
2600 if (si < (int)sizeof(string) - 1)
2601 string[si++] = subject[i];
2604 // remaining chars (these cannot match)
2605 for (; i < subject_len; i++)
2606 if (si < (int)sizeof(string) - 1)
2607 string[si++] = subject[i];
2610 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, si);
2617 vector stov(string s)
2620 //vector(string s) stov = #117; // returns vector value from a string
2621 void VM_stov(prvm_prog_t *prog)
2623 char string[VM_TEMPSTRING_MAXSIZE];
2625 VM_SAFEPARMCOUNT(1,VM_stov);
2627 VM_VarString(prog, 0, string, sizeof(string));
2628 Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
2635 string strzone(string s)
2638 //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)
2639 void VM_strzone(prvm_prog_t *prog)
2642 char string[VM_TEMPSTRING_MAXSIZE];
2645 VM_SAFEPARMCOUNT(1,VM_strzone);
2647 alloclen = VM_VarString(prog, 0, string, sizeof(string)) + 1;
2648 PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(prog, alloclen, &out);
2649 memcpy(out, string, alloclen);
2659 //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!!!)
2660 void VM_strunzone(prvm_prog_t *prog)
2662 VM_SAFEPARMCOUNT(1,VM_strunzone);
2663 PRVM_FreeString(prog, PRVM_G_INT(OFS_PARM0));
2670 float tokenize(string s)
2673 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
2674 //this function originally written by KrimZon, made shorter by LadyHavoc
2675 //20040203: rewritten by LadyHavoc (no longer uses allocations)
2676 static int num_tokens = 0;
2677 static int tokens[VM_TEMPSTRING_MAXSIZE / 2];
2678 static int tokens_startpos[VM_TEMPSTRING_MAXSIZE / 2];
2679 static int tokens_endpos[VM_TEMPSTRING_MAXSIZE / 2];
2680 static char tokenize_string[VM_TEMPSTRING_MAXSIZE];
2681 void VM_tokenize (prvm_prog_t *prog)
2685 VM_SAFEPARMCOUNT(1,VM_tokenize);
2687 dp_strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2688 p = tokenize_string;
2693 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2696 // skip whitespace here to find token start pos
2697 while(*p && ISWHITESPACE(*p))
2700 tokens_startpos[num_tokens] = p - tokenize_string;
2701 if(!COM_ParseToken_VM_Tokenize(&p, false))
2703 tokens_endpos[num_tokens] = p - tokenize_string;
2704 tokens[num_tokens] = PRVM_SetTempString(prog, com_token, com_token_len);
2708 PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2711 //float(string s) tokenize = #514; // takes apart a string into individal words (access them with argv), returns how many
2712 void VM_tokenize_console (prvm_prog_t *prog)
2716 VM_SAFEPARMCOUNT(1, VM_tokenize_console);
2718 dp_strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2719 p = tokenize_string;
2724 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2727 // skip whitespace here to find token start pos
2728 while(*p && ISWHITESPACE(*p))
2731 tokens_startpos[num_tokens] = p - tokenize_string;
2732 if(!COM_ParseToken_Console(&p))
2734 tokens_endpos[num_tokens] = p - tokenize_string;
2735 tokens[num_tokens] = PRVM_SetTempString(prog, com_token, com_token_len);
2739 PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2744 VM_tokenizebyseparator
2746 float tokenizebyseparator(string s, string separator1, ...)
2749 //float(string s, string separator1, ...) tokenizebyseparator = #479; // takes apart a string into individal words (access them with argv), returns how many
2750 //this function returns the token preceding each instance of a separator (of
2751 //which there can be multiple), and the text following the last separator
2752 //useful for parsing certain kinds of data like IP addresses
2754 //numnumbers = tokenizebyseparator("10.1.2.3", ".");
2755 //returns 4 and the tokens "10" "1" "2" "3".
2756 void VM_tokenizebyseparator (prvm_prog_t *prog)
2760 int separatorlen[7];
2761 const char *separators[7];
2764 char tokentext[MAX_INPUTLINE];
2766 VM_SAFEPARMCOUNTRANGE(2, 8,VM_tokenizebyseparator);
2768 dp_strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2769 p = tokenize_string;
2772 for (j = 1;j < prog->argc;j++)
2774 // skip any blank separator strings
2775 const char *s = PRVM_G_STRING(OFS_PARM0+j*3);
2778 separators[numseparators] = s;
2779 separatorlen[numseparators] = (int)strlen(s);
2786 while (num_tokens < (int)(sizeof(tokens)/sizeof(tokens[0])))
2788 token = tokentext + j;
2789 tokens_startpos[num_tokens] = p - tokenize_string;
2793 for (k = 0;k < numseparators;k++)
2795 if (!strncmp(p, separators[k], separatorlen[k]))
2797 p += separatorlen[k];
2801 if (k < numseparators)
2803 if (j < (int)sizeof(tokentext)-1)
2804 tokentext[j++] = *p;
2808 tokens_endpos[num_tokens] = p0 - tokenize_string;
2809 if (j >= (int)sizeof(tokentext))
2811 tokentext[j++] = '\0';
2812 tokens[num_tokens++] = PRVM_SetTempString(prog, token, j - 1);
2817 PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2820 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
2821 //this function originally written by KrimZon, made shorter by LadyHavoc
2822 void VM_argv (prvm_prog_t *prog)
2826 VM_SAFEPARMCOUNT(1,VM_argv);
2828 token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2831 token_num += num_tokens;
2833 if (token_num >= 0 && token_num < num_tokens)
2834 PRVM_G_INT(OFS_RETURN) = tokens[token_num];
2836 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2839 //float(float n) argv_start_index = #515; // returns the start index of a token
2840 void VM_argv_start_index (prvm_prog_t *prog)
2844 VM_SAFEPARMCOUNT(1,VM_argv);
2846 token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2849 token_num += num_tokens;
2851 if (token_num >= 0 && token_num < num_tokens)
2852 PRVM_G_FLOAT(OFS_RETURN) = tokens_startpos[token_num];
2854 PRVM_G_FLOAT(OFS_RETURN) = -1;
2857 //float(float n) argv_end_index = #516; // returns the end index of a token
2858 void VM_argv_end_index (prvm_prog_t *prog)
2862 VM_SAFEPARMCOUNT(1,VM_argv);
2864 token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2867 token_num += num_tokens;
2869 if (token_num >= 0 && token_num < num_tokens)
2870 PRVM_G_FLOAT(OFS_RETURN) = tokens_endpos[token_num];
2872 PRVM_G_FLOAT(OFS_RETURN) = -1;
2882 void VM_isserver(prvm_prog_t *prog)
2884 VM_SAFEPARMCOUNT(0, VM_isserver);
2886 PRVM_G_FLOAT(OFS_RETURN) = sv.active;
2896 void VM_clientcount(prvm_prog_t *prog)
2898 VM_SAFEPARMCOUNT(0,VM_clientcount);
2900 PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
2910 void VM_clientstate(prvm_prog_t *prog)
2912 VM_SAFEPARMCOUNT(0,VM_clientstate);
2915 switch( cls.state ) {
2916 case ca_uninitialized:
2918 PRVM_G_FLOAT(OFS_RETURN) = 0;
2920 case ca_disconnected:
2921 PRVM_G_FLOAT(OFS_RETURN) = 1;
2924 PRVM_G_FLOAT(OFS_RETURN) = 2;
2927 // should never be reached!
2936 float getostype(prvm_prog_t *prog)
2938 */ // not used at the moment -> not included in the common list
2939 void VM_getostype(prvm_prog_t *prog)
2941 VM_SAFEPARMCOUNT(0,VM_getostype);
2946 OS_MAC - not supported
2950 PRVM_G_FLOAT(OFS_RETURN) = 0;
2951 #elif defined(MACOSX)
2952 PRVM_G_FLOAT(OFS_RETURN) = 2;
2954 PRVM_G_FLOAT(OFS_RETURN) = 1;
2962 float gettime(prvm_prog_t *prog)
2965 float CDAudio_GetPosition(void);
2966 void VM_gettime(prvm_prog_t *prog)
2970 VM_SAFEPARMCOUNTRANGE(0,1,VM_gettime);
2974 PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t) host.realtime;
2978 timer_index = (int) PRVM_G_FLOAT(OFS_PARM0);
2981 case 0: // GETTIME_FRAMESTART
2982 PRVM_G_FLOAT(OFS_RETURN) = host.realtime;
2984 case 1: // GETTIME_REALTIME
2985 PRVM_G_FLOAT(OFS_RETURN) = Sys_DirtyTime();
2987 case 2: // GETTIME_HIRES
2988 PRVM_G_FLOAT(OFS_RETURN) = (Sys_DirtyTime() - host.dirtytime);
2990 case 3: // GETTIME_UPTIME
2991 PRVM_G_FLOAT(OFS_RETURN) = host.realtime;
2993 case 4: // GETTIME_CDTRACK
2994 PRVM_G_FLOAT(OFS_RETURN) = CDAudio_GetPosition();
2997 VM_Warning(prog, "VM_gettime: %s: unsupported timer specified, returning realtime\n", prog->name);
2998 PRVM_G_FLOAT(OFS_RETURN) = host.realtime;
3008 float getsoundtime(prvm_prog_t *prog)
3012 void VM_getsoundtime (prvm_prog_t *prog)
3014 int entnum, entchannel;
3015 VM_SAFEPARMCOUNT(2,VM_getsoundtime);
3017 if (prog == SVVM_prog)
3018 entnum = PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
3019 else if (prog == CLVM_prog)
3020 entnum = MAX_EDICTS + PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
3023 VM_Warning(prog, "VM_getsoundtime: %s: not supported on this progs\n", prog->name);
3024 PRVM_G_FLOAT(OFS_RETURN) = -1;
3027 entchannel = (int)PRVM_G_FLOAT(OFS_PARM1);
3028 entchannel = CHAN_USER2ENGINE(entchannel);
3029 if (!IS_CHAN(entchannel))
3030 VM_Warning(prog, "VM_getsoundtime: %s: bad channel %i\n", prog->name, entchannel);
3031 PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t)S_GetEntChannelPosition(entnum, entchannel);
3038 string soundlength (string sample)
3041 void VM_soundlength (prvm_prog_t *prog)
3045 VM_SAFEPARMCOUNT(1, VM_soundlength);
3047 s = PRVM_G_STRING(OFS_PARM0);
3048 PRVM_G_FLOAT(OFS_RETURN) = S_SoundLength(s);
3055 loadfromdata(string data)
3058 void VM_loadfromdata(prvm_prog_t *prog)
3060 VM_SAFEPARMCOUNT(1, VM_loadfromdata);
3062 PRVM_ED_LoadFromFile(prog, PRVM_G_STRING(OFS_PARM0));
3066 ========================
3069 parseentitydata(entity ent, string data)
3070 ========================
3072 void VM_parseentitydata(prvm_prog_t *prog)
3077 VM_SAFEPARMCOUNT(2, VM_parseentitydata);
3079 // get edict and test it
3080 ent = PRVM_G_EDICT(OFS_PARM0);
3082 prog->error_cmd("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", prog->name, PRVM_NUM_FOR_EDICT(ent));
3084 data = PRVM_G_STRING(OFS_PARM1);
3086 // parse the opening brace
3087 if (!COM_ParseToken_Simple(&data, false, false, true) || com_token[0] != '{' )
3088 prog->error_cmd("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", prog->name, data );
3090 PRVM_ED_ParseEdict (prog, data, ent);
3097 loadfromfile(string file)
3100 void VM_loadfromfile(prvm_prog_t *prog)
3102 const char *filename;
3105 VM_SAFEPARMCOUNT(1,VM_loadfromfile);
3107 filename = PRVM_G_STRING(OFS_PARM0);
3108 if (FS_CheckNastyPath(filename, false))
3110 PRVM_G_FLOAT(OFS_RETURN) = -4;
3111 VM_Warning(prog, "VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", prog->name, filename);
3115 // not conform with VM_fopen
3116 data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
3118 PRVM_G_FLOAT(OFS_RETURN) = -1;
3120 PRVM_ED_LoadFromFile(prog, data);
3131 float mod(float val, float m)
3134 void VM_modulo(prvm_prog_t *prog)
3138 VM_SAFEPARMCOUNT(2, VM_modulo);
3140 val = PRVM_G_FLOAT(OFS_PARM0);
3141 m = PRVM_G_FLOAT(OFS_PARM1);
3143 // matches how gmqcc implements % when mod() builtin isn't defined, and FTEQW mod()
3145 PRVM_G_FLOAT(OFS_RETURN) = val - m * (prvm_int_t)(val / m);
3148 VM_Warning(prog, "Attempted modulo of %f by zero\n", val);
3149 PRVM_G_FLOAT(OFS_RETURN) = 0;
3153 static void VM_Search_Init(prvm_prog_t *prog)
3156 for (i = 0;i < PRVM_MAX_OPENSEARCHES;i++)
3157 prog->opensearches[i] = NULL;
3160 static void VM_Search_Reset(prvm_prog_t *prog)
3163 // reset the fssearch list
3164 for(i = 0; i < PRVM_MAX_OPENSEARCHES; i++)
3166 if(prog->opensearches[i])
3167 FS_FreeSearch(prog->opensearches[i]);
3168 prog->opensearches[i] = NULL;
3176 float search_begin(string pattern, float caseinsensitive, float quiet[, string packfile])
3179 void VM_search_begin(prvm_prog_t *prog)
3182 const char *packfile = NULL, *pattern;
3183 int caseinsens, quiet;
3185 VM_SAFEPARMCOUNTRANGE(3, 4, VM_search_begin);
3187 pattern = PRVM_G_STRING(OFS_PARM0);
3189 VM_CheckEmptyString(prog, pattern);
3191 caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
3192 quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
3194 // optional packfile parameter (DP_QC_FS_SEARCH_PACKFILE)
3196 packfile = PRVM_G_STRING(OFS_PARM3);
3198 for(handle = 0; handle < PRVM_MAX_OPENSEARCHES; handle++)
3199 if(!prog->opensearches[handle])
3202 if(handle >= PRVM_MAX_OPENSEARCHES)
3204 PRVM_G_FLOAT(OFS_RETURN) = -2;
3205 VM_Warning(prog, "VM_search_begin: %s ran out of search handles (%i)\n", prog->name, PRVM_MAX_OPENSEARCHES);
3209 if(!(prog->opensearches[handle] = FS_Search(pattern,caseinsens, quiet, packfile)))
3210 PRVM_G_FLOAT(OFS_RETURN) = -1;
3213 prog->opensearches_origin[handle] = PRVM_AllocationOrigin(prog);
3214 PRVM_G_FLOAT(OFS_RETURN) = handle;
3222 void search_end(float handle)
3225 void VM_search_end(prvm_prog_t *prog)
3228 VM_SAFEPARMCOUNT(1, VM_search_end);
3230 handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3232 if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3234 VM_Warning(prog, "VM_search_end: invalid handle %i used in %s\n", handle, prog->name);
3237 if(prog->opensearches[handle] == NULL)
3239 VM_Warning(prog, "VM_search_end: no such handle %i in %s\n", handle, prog->name);
3243 FS_FreeSearch(prog->opensearches[handle]);
3244 prog->opensearches[handle] = NULL;
3245 if(prog->opensearches_origin[handle])
3246 PRVM_Free((char *)prog->opensearches_origin[handle]);
3253 float search_getsize(float handle)
3256 void VM_search_getsize(prvm_prog_t *prog)
3259 VM_SAFEPARMCOUNT(1, VM_search_getsize);
3261 handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3263 if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3265 VM_Warning(prog, "VM_search_getsize: invalid handle %i used in %s\n", handle, prog->name);
3268 if(prog->opensearches[handle] == NULL)
3270 VM_Warning(prog, "VM_search_getsize: no such handle %i in %s\n", handle, prog->name);
3274 PRVM_G_FLOAT(OFS_RETURN) = prog->opensearches[handle]->numfilenames;
3279 VM_search_getfilename
3281 string search_getfilename(float handle, float num)
3284 void VM_search_getfilename(prvm_prog_t *prog)
3286 int handle, filenum;
3288 VM_SAFEPARMCOUNT(2, VM_search_getfilename);
3290 handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3291 filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
3293 if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3295 VM_Warning(prog, "VM_search_getfilename: invalid handle %i used in %s\n", handle, prog->name);
3298 if(prog->opensearches[handle] == NULL)
3300 VM_Warning(prog, "VM_search_getfilename: no such handle %i in %s\n", handle, prog->name);
3303 if(filenum < 0 || filenum >= prog->opensearches[handle]->numfilenames)
3305 VM_Warning(prog, "VM_search_getfilename: invalid filenum %i in %s\n", filenum, prog->name);
3309 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog,
3310 prog->opensearches[handle]->filenames[filenum],
3311 strlen(prog->opensearches[handle]->filenames[filenum]));
3318 string chr(float ascii)
3321 void VM_chr(prvm_prog_t *prog)
3325 VM_SAFEPARMCOUNT(1, VM_chr);
3327 tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
3330 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, tmp);
3336 VM_SAFEPARMCOUNT(1, VM_chr);
3337 len = u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0), tmp, sizeof(tmp));
3339 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, tmp, len);
3346 string keynumtostring(float keynum)
3349 void VM_keynumtostring (prvm_prog_t *prog)
3351 char tinystr[TINYSTR_LEN];
3352 const char *str; // Key_KeynumToString doesn't always return tinystr
3354 VM_SAFEPARMCOUNT(1, VM_keynumtostring);
3355 str = Key_KeynumToString((int)PRVM_G_FLOAT(OFS_PARM0), tinystr, sizeof(tinystr));
3356 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, str, strlen(str));
3361 VM_findkeysforcommand
3363 string findkeysforcommand(string command, float bindmap)
3365 the returned string is an altstring
3368 #define FKFC_NUMKEYS 5
3369 void M_FindKeysForCommand(const char *command, int *keys);
3370 void VM_findkeysforcommand(prvm_prog_t *prog)
3373 char ret[VM_TEMPSTRING_MAXSIZE];
3375 int keys[FKFC_NUMKEYS];
3380 VM_SAFEPARMCOUNTRANGE(1, 2, VM_findkeysforcommand);
3382 cmd = PRVM_G_STRING(OFS_PARM0);
3384 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3386 bindmap = 0; // consistent to "bind"
3388 VM_CheckEmptyString(prog, cmd);
3390 Key_FindKeysForCommand(cmd, keys, FKFC_NUMKEYS, bindmap);
3393 for(i = 0; i < FKFC_NUMKEYS; i++)
3394 ret_len = dp_strlcat(ret, va(vabuf, sizeof(vabuf), " \'%i\'", keys[i]), sizeof(ret));
3396 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, ret, ret_len);
3403 float stringtokeynum(string key)
3406 void VM_stringtokeynum (prvm_prog_t *prog)
3408 VM_SAFEPARMCOUNT( 1, VM_stringtokeynum );
3410 PRVM_G_FLOAT(OFS_RETURN) = Key_StringToKeynum(PRVM_G_STRING(OFS_PARM0));
3417 string getkeybind(float key, float bindmap)
3420 void VM_getkeybind (prvm_prog_t *prog)
3425 VM_SAFEPARMCOUNTRANGE(1, 2, VM_getkeybind);
3427 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3429 bindmap = 0; // consistent to "bind"
3430 bind = Key_GetBind((int)PRVM_G_FLOAT(OFS_PARM0), bindmap);
3431 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, bind, strlen(bind));
3438 float setkeybind(float key, string cmd, float bindmap)
3441 void VM_setkeybind (prvm_prog_t *prog)
3444 VM_SAFEPARMCOUNTRANGE(2, 3, VM_setkeybind);
3446 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM2), MAX_BINDMAPS-1);
3448 bindmap = 0; // consistent to "bind"
3450 PRVM_G_FLOAT(OFS_RETURN) = 0;
3451 if(Key_SetBinding((int)PRVM_G_FLOAT(OFS_PARM0), bindmap, PRVM_G_STRING(OFS_PARM1)))
3452 PRVM_G_FLOAT(OFS_RETURN) = 1;
3459 vector getbindmaps()
3462 void VM_getbindmaps (prvm_prog_t *prog)
3465 VM_SAFEPARMCOUNT(0, VM_getbindmaps);
3466 Key_GetBindMap(&fg, &bg);
3467 PRVM_G_VECTOR(OFS_RETURN)[0] = fg;
3468 PRVM_G_VECTOR(OFS_RETURN)[1] = bg;
3469 PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
3476 float setbindmaps(vector bindmap)
3479 void VM_setbindmaps (prvm_prog_t *prog)
3481 VM_SAFEPARMCOUNT(1, VM_setbindmaps);
3482 PRVM_G_FLOAT(OFS_RETURN) = 0;
3483 if(PRVM_G_VECTOR(OFS_PARM0)[2] == 0)
3484 if(Key_SetBindMap((int)PRVM_G_VECTOR(OFS_PARM0)[0], (int)PRVM_G_VECTOR(OFS_PARM0)[1]))
3485 PRVM_G_FLOAT(OFS_RETURN) = 1;
3489 ========================
3492 float[bool] gecko_create( string name )
3493 ========================
3495 void VM_gecko_create(prvm_prog_t *prog) {
3497 PRVM_G_FLOAT( OFS_RETURN ) = 0;
3501 ========================
3504 void gecko_destroy( string name )
3505 ========================
3507 void VM_gecko_destroy(prvm_prog_t *prog) {
3512 ========================
3515 void gecko_navigate( string name, string URI )
3516 ========================
3518 void VM_gecko_navigate(prvm_prog_t *prog) {
3523 ========================
3526 float[bool] gecko_keyevent( string name, float key, float eventtype )
3527 ========================
3529 void VM_gecko_keyevent(prvm_prog_t *prog) {
3531 PRVM_G_FLOAT( OFS_RETURN ) = 0;
3535 ========================
3538 void gecko_mousemove( string name, float x, float y )
3539 ========================
3541 void VM_gecko_movemouse(prvm_prog_t *prog) {
3547 ========================
3550 void gecko_resize( string name, float w, float h )
3551 ========================
3553 void VM_gecko_resize(prvm_prog_t *prog) {
3559 ========================
3560 VM_gecko_get_texture_extent
3562 vector gecko_get_texture_extent( string name )
3563 ========================
3565 void VM_gecko_get_texture_extent(prvm_prog_t *prog) {
3567 PRVM_G_VECTOR(OFS_RETURN)[0] = 0;
3568 PRVM_G_VECTOR(OFS_RETURN)[1] = 0;
3577 Writes new values for v_forward, v_up, and v_right based on angles
3578 void makevectors(vector angle)
3581 void VM_makevectors (prvm_prog_t *prog)
3583 vec3_t angles, forward, right, up;
3584 VM_SAFEPARMCOUNT(1, VM_makevectors);
3585 VectorCopy(PRVM_G_VECTOR(OFS_PARM0), angles);
3586 AngleVectors(angles, forward, right, up);
3587 VectorCopy(forward, PRVM_gameglobalvector(v_forward));
3588 VectorCopy(right, PRVM_gameglobalvector(v_right));
3589 VectorCopy(up, PRVM_gameglobalvector(v_up));
3596 Writes new values for v_forward, v_up, and v_right based on the given forward vector
3597 vectorvectors(vector)
3600 void VM_vectorvectors (prvm_prog_t *prog)
3602 vec3_t forward, right, up;
3603 VM_SAFEPARMCOUNT(1, VM_vectorvectors);
3604 VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), forward);
3605 VectorVectors(forward, right, up);
3606 VectorCopy(forward, PRVM_gameglobalvector(v_forward));
3607 VectorCopy(right, PRVM_gameglobalvector(v_right));
3608 VectorCopy(up, PRVM_gameglobalvector(v_up));
3611 // float(float number, float quantity) bitshift (EXT_BITSHIFT)
3612 void VM_bitshift (prvm_prog_t *prog)
3615 VM_SAFEPARMCOUNT(2, VM_bitshift);
3617 n1 = (prvm_int_t)fabs((prvm_vec_t)((prvm_int_t)PRVM_G_FLOAT(OFS_PARM0)));
3618 n2 = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM1);
3620 PRVM_G_FLOAT(OFS_RETURN) = n1;
3623 PRVM_G_FLOAT(OFS_RETURN) = (n1 >> -n2);
3625 PRVM_G_FLOAT(OFS_RETURN) = (n1 << n2);
3628 ////////////////////////////////////////
3629 // AltString functions
3630 ////////////////////////////////////////
3633 ========================
3636 float altstr_count(string)
3637 ========================
3639 void VM_altstr_count(prvm_prog_t *prog)
3641 const char *altstr, *pos;
3644 VM_SAFEPARMCOUNT( 1, VM_altstr_count );
3646 altstr = PRVM_G_STRING( OFS_PARM0 );
3647 //VM_CheckEmptyString(prog, altstr );
3649 for( count = 0, pos = altstr ; *pos ; pos++ ) {
3650 if( *pos == '\\' ) {
3654 } else if( *pos == '\'' ) {
3659 PRVM_G_FLOAT( OFS_RETURN ) = (prvm_vec_t) (count / 2);
3663 ========================
3666 string altstr_prepare(string)
3667 ========================
3669 void VM_altstr_prepare(prvm_prog_t *prog)
3671 const char *instr, *in;
3672 char outstr[VM_TEMPSTRING_MAXSIZE];
3675 VM_SAFEPARMCOUNT( 1, VM_altstr_prepare );
3677 instr = PRVM_G_STRING( OFS_PARM0 );
3679 for (in = instr, outpos = 0; *in && outpos < sizeof(outstr) - 1; ++in)
3681 if (*in == '\'' && outpos < sizeof(outstr) - 2)
3683 outstr[outpos++] = '\\';
3684 outstr[outpos++] = '\'';
3687 outstr[outpos++] = *in;
3690 outstr[outpos] = '\0';
3691 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, outpos);
3695 ========================
3698 string altstr_get(string, float)
3699 ========================
3701 void VM_altstr_get(prvm_prog_t *prog)
3703 const char *altstr, *pos;
3706 char outstr[VM_TEMPSTRING_MAXSIZE];
3708 VM_SAFEPARMCOUNT( 2, VM_altstr_get );
3710 altstr = PRVM_G_STRING( OFS_PARM0 );
3712 count = (int)PRVM_G_FLOAT( OFS_PARM1 );
3713 count = count * 2 + 1;
3715 for( pos = altstr ; *pos && count ; pos++ )
3716 if( *pos == '\\' ) {
3719 } else if( *pos == '\'' )
3723 PRVM_G_INT( OFS_RETURN ) = 0;
3727 for( out = outstr, size = sizeof(outstr) - 1 ; size && *pos ; size--, pos++, out++ )
3728 if( *pos == '\\' ) {
3733 } else if( *pos == '\'' )
3739 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, out - outstr);
3743 ========================
3746 string altstr_set(string altstr, float num, string set)
3747 ========================
3749 void VM_altstr_set(prvm_prog_t *prog)
3752 const char *altstr, *str;
3755 char outstr[VM_TEMPSTRING_MAXSIZE];
3757 VM_SAFEPARMCOUNT( 3, VM_altstr_set );
3759 altstr = PRVM_G_STRING( OFS_PARM0 );
3761 num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3763 str = PRVM_G_STRING( OFS_PARM2 );
3766 for( num = num * 2 + 1, in = altstr; *in && num; *out++ = *in++ )
3771 } else if( *in == '\'' ) {
3776 for( ; *str; *out++ = *str++ );
3777 // now jump over the old content
3779 if( *in == '\'' || (*in == '\\' && !*++in) )
3782 out += dp_strlcpy(out, in, outstr + sizeof(outstr) - out);
3783 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, out - outstr);
3787 ========================
3790 string altstr_ins(string altstr, float num, string set)
3791 ========================
3793 void VM_altstr_ins(prvm_prog_t *prog)
3799 char outstr[VM_TEMPSTRING_MAXSIZE];
3801 VM_SAFEPARMCOUNT(3, VM_altstr_ins);
3803 in = PRVM_G_STRING( OFS_PARM0 );
3804 num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3805 set = PRVM_G_STRING( OFS_PARM2 );
3808 for( num = num * 2 + 2 ; *in && num > 0 ; *out++ = *in++ )
3813 } else if( *in == '\'' ) {
3818 for( ; *set ; *out++ = *set++ );
3821 out += dp_strlcpy(out, in, outstr + sizeof(outstr) - out);
3822 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, out - outstr);
3826 ////////////////////////////////////////
3827 // BufString functions
3828 ////////////////////////////////////////
3829 //[515]: string buffers support
3831 static size_t stringbuffers_sortlength;
3833 static void BufStr_Expand(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer, int strindex)
3835 if (stringbuffer->max_strings <= strindex)
3837 char **oldstrings = stringbuffer->strings;
3838 stringbuffer->max_strings = max(stringbuffer->max_strings * 2, 128);
3839 while (stringbuffer->max_strings <= strindex)
3840 stringbuffer->max_strings *= 2;
3841 stringbuffer->strings = (char **) Mem_Alloc(prog->progs_mempool, stringbuffer->max_strings * sizeof(stringbuffer->strings[0]));
3842 if (stringbuffer->num_strings > 0)
3843 memcpy(stringbuffer->strings, oldstrings, stringbuffer->num_strings * sizeof(stringbuffer->strings[0]));
3845 Mem_Free(oldstrings);
3849 static void BufStr_Shrink(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer)
3851 // reduce num_strings if there are empty string slots at the end
3852 while (stringbuffer->num_strings > 0 && stringbuffer->strings[stringbuffer->num_strings - 1] == NULL)
3853 stringbuffer->num_strings--;
3855 // if empty, free the string pointer array
3856 if (stringbuffer->num_strings == 0)
3858 stringbuffer->max_strings = 0;
3859 if (stringbuffer->strings)
3860 Mem_Free(stringbuffer->strings);
3861 stringbuffer->strings = NULL;
3865 static int BufStr_SortStringsUP (const void *in1, const void *in2)
3868 a = *((const char **) in1);
3869 b = *((const char **) in2);
3870 if(!a || !a[0]) return 1;
3871 if(!b || !b[0]) return -1;
3872 return strncmp(a, b, stringbuffers_sortlength);
3875 static int BufStr_SortStringsDOWN (const void *in1, const void *in2)
3878 a = *((const char **) in1);
3879 b = *((const char **) in2);
3880 if(!a || !a[0]) return 1;
3881 if(!b || !b[0]) return -1;
3882 return strncmp(b, a, stringbuffers_sortlength);
3885 prvm_stringbuffer_t *BufStr_FindCreateReplace (prvm_prog_t *prog, int bufindex, unsigned flags, const char *format)
3887 prvm_stringbuffer_t *stringbuffer;
3893 // find buffer with wanted index
3894 if (bufindex < (int)Mem_ExpandableArray_IndexRange(&prog->stringbuffersarray))
3896 if ( (stringbuffer = (prvm_stringbuffer_t*) Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, bufindex)) )
3898 if (stringbuffer->flags & STRINGBUFFER_TEMP)
3899 stringbuffer->flags = flags; // created but has not been used yet
3900 return stringbuffer;
3905 // allocate new buffer with wanted index
3908 stringbuffer = (prvm_stringbuffer_t *) Mem_ExpandableArray_AllocRecord(&prog->stringbuffersarray);
3909 stringbuffer->flags = STRINGBUFFER_TEMP;
3910 for (i = 0;stringbuffer != Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);i++);
3913 stringbuffer->flags = flags; // mark as used
3917 return stringbuffer;
3920 void BufStr_Set(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer, int strindex, const char *str)
3924 if (!stringbuffer || strindex < 0)
3927 BufStr_Expand(prog, stringbuffer, strindex);
3928 stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
3929 if (stringbuffer->strings[strindex])
3930 Mem_Free(stringbuffer->strings[strindex]);
3931 stringbuffer->strings[strindex] = NULL;
3935 // not the NULL string!
3936 alloclen = strlen(str) + 1;
3937 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
3938 memcpy(stringbuffer->strings[strindex], str, alloclen);
3941 BufStr_Shrink(prog, stringbuffer);
3944 void BufStr_Del(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer)
3951 for (i = 0;i < stringbuffer->num_strings;i++)
3952 if (stringbuffer->strings[i])
3953 Mem_Free(stringbuffer->strings[i]);
3954 if (stringbuffer->strings)
3955 Mem_Free(stringbuffer->strings);
3956 if(stringbuffer->origin)
3957 PRVM_Free((char *)stringbuffer->origin);
3958 Mem_ExpandableArray_FreeRecord(&prog->stringbuffersarray, stringbuffer);
3961 void BufStr_Flush(prvm_prog_t *prog)
3963 prvm_stringbuffer_t *stringbuffer;
3966 numbuffers = (int)Mem_ExpandableArray_IndexRange(&prog->stringbuffersarray);
3967 for (i = 0; i < numbuffers; i++)
3968 if ( (stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i)) )
3969 BufStr_Del(prog, stringbuffer);
3970 Mem_ExpandableArray_NewArray(&prog->stringbuffersarray, prog->progs_mempool, sizeof(prvm_stringbuffer_t), 64);
3974 ========================
3976 creates new buffer, and returns it's index, returns -1 if failed
3977 float buf_create(prvm_prog_t *prog) = #460;
3978 float newbuf(string format, float flags) = #460;
3979 ========================
3982 void VM_buf_create (prvm_prog_t *prog)
3984 prvm_stringbuffer_t *stringbuffer;
3987 VM_SAFEPARMCOUNTRANGE(0, 2, VM_buf_create);
3989 // VorteX: optional parm1 (buffer format) is unfinished, to keep intact with future databuffers extension must be set to "string"
3990 if(prog->argc >= 1 && strcmp(PRVM_G_STRING(OFS_PARM0), "string"))
3992 PRVM_G_FLOAT(OFS_RETURN) = -1;
3995 stringbuffer = (prvm_stringbuffer_t *) Mem_ExpandableArray_AllocRecord(&prog->stringbuffersarray);
3996 for (i = 0;stringbuffer != Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);i++);
3997 stringbuffer->origin = PRVM_AllocationOrigin(prog);
3998 // optional flags parm
3999 if (prog->argc >= 2)
4000 stringbuffer->flags = (int)PRVM_G_FLOAT(OFS_PARM1) & STRINGBUFFER_QCFLAGS;
4001 PRVM_G_FLOAT(OFS_RETURN) = i;
4007 ========================
4009 deletes buffer and all strings in it
4010 void buf_del(float bufhandle) = #461;
4011 ========================
4013 void VM_buf_del (prvm_prog_t *prog)
4015 prvm_stringbuffer_t *stringbuffer;
4016 VM_SAFEPARMCOUNT(1, VM_buf_del);
4017 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4019 BufStr_Del(prog, stringbuffer);
4022 VM_Warning(prog, "VM_buf_del: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4028 ========================
4030 how many strings are stored in buffer
4031 float buf_getsize(float bufhandle) = #462;
4032 ========================
4034 void VM_buf_getsize (prvm_prog_t *prog)
4036 prvm_stringbuffer_t *stringbuffer;
4037 VM_SAFEPARMCOUNT(1, VM_buf_getsize);
4039 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4042 PRVM_G_FLOAT(OFS_RETURN) = -1;
4043 VM_Warning(prog, "VM_buf_getsize: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4047 PRVM_G_FLOAT(OFS_RETURN) = stringbuffer->num_strings;
4051 ========================
4053 copy all content from one buffer to another, make sure it exists
4054 void buf_copy(float bufhandle_from, float bufhandle_to) = #463;
4055 ========================
4057 void VM_buf_copy (prvm_prog_t *prog)
4059 prvm_stringbuffer_t *srcstringbuffer, *dststringbuffer;
4061 VM_SAFEPARMCOUNT(2, VM_buf_copy);
4063 srcstringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4064 if(!srcstringbuffer)
4066 VM_Warning(prog, "VM_buf_copy: invalid source buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4069 i = (int)PRVM_G_FLOAT(OFS_PARM1);
4070 if(i == (int)PRVM_G_FLOAT(OFS_PARM0))
4072 VM_Warning(prog, "VM_buf_copy: source == destination (%i) in %s\n", i, prog->name);
4075 dststringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4076 if(!dststringbuffer)
4078 VM_Warning(prog, "VM_buf_copy: invalid destination buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
4082 for (i = 0;i < dststringbuffer->num_strings;i++)
4083 if (dststringbuffer->strings[i])
4084 Mem_Free(dststringbuffer->strings[i]);
4085 if (dststringbuffer->strings)
4086 Mem_Free(dststringbuffer->strings);
4087 *dststringbuffer = *srcstringbuffer;
4088 if (dststringbuffer->max_strings)
4089 dststringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(dststringbuffer->strings[0]) * dststringbuffer->max_strings);
4091 for (i = 0;i < dststringbuffer->num_strings;i++)
4093 if (srcstringbuffer->strings[i])
4096 stringlen = strlen(srcstringbuffer->strings[i]) + 1;
4097 dststringbuffer->strings[i] = (char *)Mem_Alloc(prog->progs_mempool, stringlen);
4098 memcpy(dststringbuffer->strings[i], srcstringbuffer->strings[i], stringlen);
4104 ========================
4106 sort buffer by beginnings of strings (cmplength defaults it's length)
4107 "backward == true" means that sorting goes upside-down
4108 void buf_sort(float bufhandle, float cmplength, float backward) = #464;
4109 ========================
4111 void VM_buf_sort (prvm_prog_t *prog)
4113 prvm_stringbuffer_t *stringbuffer;
4114 VM_SAFEPARMCOUNT(3, VM_buf_sort);
4116 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4119 VM_Warning(prog, "VM_buf_sort: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4122 if(stringbuffer->num_strings <= 0)
4124 VM_Warning(prog, "VM_buf_sort: tried to sort empty buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4127 stringbuffers_sortlength = (int)PRVM_G_FLOAT(OFS_PARM1);
4128 if(stringbuffers_sortlength <= 0)
4129 stringbuffers_sortlength = 0x7FFFFFFF;
4131 if(!PRVM_G_FLOAT(OFS_PARM2))
4132 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsUP);
4134 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsDOWN);
4136 BufStr_Shrink(prog, stringbuffer);
4140 ========================
4142 concantenates all buffer string into one with "glue" separator and returns it as tempstring
4143 string buf_implode(float bufhandle, string glue) = #465;
4144 ========================
4146 void VM_buf_implode (prvm_prog_t *prog)
4148 prvm_stringbuffer_t *stringbuffer;
4149 char k[VM_TEMPSTRING_MAXSIZE];
4155 VM_SAFEPARMCOUNT(2, VM_buf_implode);
4157 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4158 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4161 VM_Warning(prog, "VM_buf_implode: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4164 if(!stringbuffer->num_strings)
4166 sep = PRVM_G_STRING(OFS_PARM1);
4169 for(l = i = 0;i < stringbuffer->num_strings;i++)
4171 if(stringbuffer->strings[i])
4173 l += (i > 0 ? strlen(sep) : 0) + strlen(stringbuffer->strings[i]);
4174 if (l >= sizeof(k) - 1)
4176 dp_strlcat(k, sep, sizeof(k));
4177 k_len = dp_strlcat(k, stringbuffer->strings[i], sizeof(k));
4180 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, k, k_len);
4184 ========================
4186 get a string from buffer, returns tempstring, dont str_unzone it!
4187 string bufstr_get(float bufhandle, float string_index) = #465;
4188 ========================
4190 void VM_bufstr_get (prvm_prog_t *prog)
4192 prvm_stringbuffer_t *stringbuffer;
4194 VM_SAFEPARMCOUNT(2, VM_bufstr_get);
4196 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4197 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4200 VM_Warning(prog, "VM_bufstr_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4203 strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4206 // VM_Warning(prog, "VM_bufstr_get: invalid string index %i used in %s\n", strindex, prog->name);
4209 if (strindex < stringbuffer->num_strings && stringbuffer->strings[strindex])
4210 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, stringbuffer->strings[strindex], strlen(stringbuffer->strings[strindex]));
4214 ========================
4216 copies a string into selected slot of buffer
4217 void bufstr_set(float bufhandle, float string_index, string str) = #466;
4218 ========================
4220 void VM_bufstr_set (prvm_prog_t *prog)
4223 prvm_stringbuffer_t *stringbuffer;
4226 VM_SAFEPARMCOUNT(3, VM_bufstr_set);
4228 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4231 VM_Warning(prog, "VM_bufstr_set: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4234 strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4235 if(strindex < 0 || strindex >= 1000000) // huge number of strings
4237 VM_Warning(prog, "VM_bufstr_set: invalid string index %i used in %s\n", strindex, prog->name);
4241 news = PRVM_G_STRING(OFS_PARM2);
4242 BufStr_Set(prog, stringbuffer, strindex, news);
4246 ========================
4248 adds string to buffer in first free slot and returns its index
4249 "order == true" means that string will be added after last "full" slot
4250 float bufstr_add(float bufhandle, string str, float order) = #467;
4251 ========================
4253 void VM_bufstr_add (prvm_prog_t *prog)
4255 int order, strindex;
4256 prvm_stringbuffer_t *stringbuffer;
4260 VM_SAFEPARMCOUNT(3, VM_bufstr_add);
4262 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4263 PRVM_G_FLOAT(OFS_RETURN) = -1;
4266 VM_Warning(prog, "VM_bufstr_add: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4269 if(!PRVM_G_INT(OFS_PARM1)) // NULL string
4271 VM_Warning(prog, "VM_bufstr_add: can not add an empty string to buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4274 string = PRVM_G_STRING(OFS_PARM1);
4275 order = (int)PRVM_G_FLOAT(OFS_PARM2);
4277 strindex = stringbuffer->num_strings;
4279 for (strindex = 0;strindex < stringbuffer->num_strings;strindex++)
4280 if (stringbuffer->strings[strindex] == NULL)
4283 BufStr_Expand(prog, stringbuffer, strindex);
4285 stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4286 alloclen = strlen(string) + 1;
4287 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4288 memcpy(stringbuffer->strings[strindex], string, alloclen);
4290 PRVM_G_FLOAT(OFS_RETURN) = strindex;
4294 ========================
4296 delete string from buffer
4297 void bufstr_free(float bufhandle, float string_index) = #468;
4298 ========================
4300 void VM_bufstr_free (prvm_prog_t *prog)
4303 prvm_stringbuffer_t *stringbuffer;
4304 VM_SAFEPARMCOUNT(2, VM_bufstr_free);
4306 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4309 VM_Warning(prog, "VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4312 i = (int)PRVM_G_FLOAT(OFS_PARM1);
4315 VM_Warning(prog, "VM_bufstr_free: invalid string index %i used in %s\n", i, prog->name);
4319 if (i < stringbuffer->num_strings)
4321 if(stringbuffer->strings[i])
4322 Mem_Free(stringbuffer->strings[i]);
4323 stringbuffer->strings[i] = NULL;
4326 BufStr_Shrink(prog, stringbuffer);
4330 ========================
4332 load a file into string buffer, return 0 or 1
4333 float buf_loadfile(string filename, float bufhandle) = #535;
4334 ========================
4336 void VM_buf_loadfile(prvm_prog_t *prog)
4339 prvm_stringbuffer_t *stringbuffer;
4340 char string[VM_TEMPSTRING_MAXSIZE];
4341 int strindex, c, end;
4342 const char *filename;
4346 VM_SAFEPARMCOUNT(2, VM_buf_loadfile);
4349 filename = PRVM_G_STRING(OFS_PARM0);
4350 file = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "data/%s", filename), false);
4352 file = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "%s", filename), false);
4355 if (developer_extra.integer)
4356 VM_Warning(prog, "VM_buf_loadfile: failed to open file %s in %s\n", filename, prog->name);
4357 PRVM_G_FLOAT(OFS_RETURN) = 0;
4361 // get string buffer
4362 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM1));
4365 VM_Warning(prog, "VM_buf_loadfile: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
4366 PRVM_G_FLOAT(OFS_RETURN) = 0;
4370 // read file (append to the end of buffer)
4371 strindex = stringbuffer->num_strings;
4379 if (c == '\r' || c == '\n' || c < 0)
4381 if (end < VM_TEMPSTRING_MAXSIZE - 1)
4385 // remove \n following \r
4390 FS_UnGetc(file, (unsigned char)c);
4395 BufStr_Expand(prog, stringbuffer, strindex);
4396 stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4397 alloclen = strlen(string) + 1;
4398 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4399 memcpy(stringbuffer->strings[strindex], string, alloclen);
4400 strindex = stringbuffer->num_strings;
4408 PRVM_G_FLOAT(OFS_RETURN) = 1;
4412 ========================
4414 writes stringbuffer to a file, returns 0 or 1
4415 float buf_writefile(float filehandle, float bufhandle, [, float startpos, float numstrings]) = #468;
4416 ========================
4419 void VM_buf_writefile(prvm_prog_t *prog)
4421 int filenum, strindex, strnum, strlength;
4422 prvm_stringbuffer_t *stringbuffer;
4424 VM_SAFEPARMCOUNTRANGE(2, 4, VM_buf_writefile);
4427 filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
4428 if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
4430 VM_Warning(prog, "VM_buf_writefile: invalid file handle %i used in %s\n", filenum, prog->name);
4433 if (prog->openfiles[filenum] == NULL)
4435 VM_Warning(prog, "VM_buf_writefile: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
4439 // get string buffer
4440 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM1));
4443 VM_Warning(prog, "VM_buf_writefile: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
4444 PRVM_G_FLOAT(OFS_RETURN) = 0;
4448 // get start and end parms
4451 strindex = (int)PRVM_G_FLOAT(OFS_PARM2);
4452 strnum = (int)PRVM_G_FLOAT(OFS_PARM3);
4454 else if (prog->argc > 2)
4456 strindex = (int)PRVM_G_FLOAT(OFS_PARM2);
4457 strnum = stringbuffer->num_strings - strindex;
4462 strnum = stringbuffer->num_strings;
4464 if (strindex < 0 || strindex >= stringbuffer->num_strings)
4466 VM_Warning(prog, "VM_buf_writefile: wrong start string index %i used in %s\n", strindex, prog->name);
4467 PRVM_G_FLOAT(OFS_RETURN) = 0;
4472 VM_Warning(prog, "VM_buf_writefile: wrong strings count %i used in %s\n", strnum, prog->name);
4473 PRVM_G_FLOAT(OFS_RETURN) = 0;
4478 while(strindex < stringbuffer->num_strings && strnum)
4480 if (stringbuffer->strings[strindex])
4482 if ((strlength = (int)strlen(stringbuffer->strings[strindex])))
4483 FS_Write(prog->openfiles[filenum], stringbuffer->strings[strindex], strlength);
4484 FS_Write(prog->openfiles[filenum], "\n", 1);
4490 PRVM_G_FLOAT(OFS_RETURN) = 1;
4493 #define MATCH_AUTO 0
4494 #define MATCH_WHOLE 1
4495 #define MATCH_LEFT 2
4496 #define MATCH_RIGHT 3
4497 #define MATCH_MIDDLE 4
4498 #define MATCH_PATTERN 5
4500 static const char *detect_match_rule(char *pattern, int *matchrule)
4505 patternlength = (int)strlen(pattern);
4506 ppos = strchr(pattern, '*');
4507 qpos = strchr(pattern, '?');
4511 *matchrule = MATCH_PATTERN;
4514 // has * - left, mid, right or pattern
4517 // starts with * - may be right/mid or pattern
4518 if ((ppos - pattern) == 0)
4520 ppos = strchr(pattern+1, '*');
4524 *matchrule = MATCH_RIGHT;
4528 if ((ppos - pattern) == patternlength)
4530 *matchrule = MATCH_MIDDLE;
4535 *matchrule = MATCH_PATTERN;
4538 // end with * - left
4539 if ((ppos - pattern) == patternlength)
4541 *matchrule = MATCH_LEFT;
4546 *matchrule = MATCH_PATTERN;
4549 // have no wildcards - whole string
4550 *matchrule = MATCH_WHOLE;
4554 // todo: support UTF8
4555 static qbool match_rule(const char *string, int max_string, const char *pattern, int patternlength, int rule)
4560 return !strncmp(string, pattern, max_string) ? true : false;
4562 return !strncmp(string, pattern, patternlength) ? true : false;
4565 mid = strstr(string, pattern);
4566 return mid && !*(mid+patternlength);
4569 return strstr(string, pattern) ? true : false;
4571 return matchpattern_with_separator(string, pattern, false, "", false) ? true : false;
4575 ========================
4577 find an index of bufstring matching rule
4578 float bufstr_find(float bufhandle, string match, float matchrule, float startpos, float step) = #468;
4579 ========================
4582 void VM_bufstr_find(prvm_prog_t *prog)
4584 prvm_stringbuffer_t *stringbuffer;
4585 char string[VM_TEMPSTRING_MAXSIZE];
4586 int matchrule, matchlen, i, step;
4589 VM_SAFEPARMCOUNTRANGE(3, 5, VM_bufstr_find);
4591 PRVM_G_FLOAT(OFS_RETURN) = -1;
4593 // get string buffer
4594 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4597 VM_Warning(prog, "VM_bufstr_find: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4602 matchrule = (int)PRVM_G_FLOAT(OFS_PARM2);
4603 if (matchrule < 0 || matchrule > 5)
4605 VM_Warning(prog, "VM_bufstr_find: invalid match rule %i in %s\n", matchrule, prog->name);
4609 match = PRVM_G_STRING(OFS_PARM1);
4612 dp_strlcpy(string, PRVM_G_STRING(OFS_PARM1), sizeof(string));
4613 match = detect_match_rule(string, &matchrule);
4615 matchlen = (int)strlen(match);
4618 i = (prog->argc > 3) ? (int)PRVM_G_FLOAT(OFS_PARM3) : 0;
4619 step = (prog->argc > 4) ? (int)PRVM_G_FLOAT(OFS_PARM4) : 1;
4620 while(i < stringbuffer->num_strings)
4622 if (stringbuffer->strings[i] && match_rule(stringbuffer->strings[i], VM_TEMPSTRING_MAXSIZE, match, matchlen, matchrule))
4624 PRVM_G_FLOAT(OFS_RETURN) = i;
4632 ========================
4634 float matchpattern(string s, string pattern, float matchrule, float startpos) = #468;
4635 ========================
4637 void VM_matchpattern(prvm_prog_t *prog)
4639 const char *s, *match;
4640 char string[VM_TEMPSTRING_MAXSIZE];
4643 VM_SAFEPARMCOUNTRANGE(2, 4, VM_matchpattern);
4645 s = PRVM_G_STRING(OFS_PARM0);
4648 matchrule = (int)PRVM_G_FLOAT(OFS_PARM2);
4649 if (matchrule < 0 || matchrule > 5)
4651 VM_Warning(prog, "VM_matchpattern: invalid match rule %i in %s\n", matchrule, prog->name);
4655 match = PRVM_G_STRING(OFS_PARM1);
4658 dp_strlcpy(string, PRVM_G_STRING(OFS_PARM1), sizeof(string));
4659 match = detect_match_rule(string, &matchrule);
4663 l = (int)strlen(match);
4665 s += max(0, min((unsigned int)PRVM_G_FLOAT(OFS_PARM3), strlen(s)-1));
4668 PRVM_G_FLOAT(OFS_RETURN) = match_rule(s, VM_TEMPSTRING_MAXSIZE, match, l, matchrule);
4672 ========================
4674 ========================
4677 void VM_buf_cvarlist(prvm_prog_t *prog)
4680 const char *partial, *antipartial;
4681 size_t len, antilen;
4683 qbool ispattern, antiispattern;
4685 prvm_stringbuffer_t *stringbuffer;
4686 VM_SAFEPARMCOUNTRANGE(2, 3, VM_buf_cvarlist);
4688 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4691 VM_Warning(prog, "VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4695 partial = PRVM_G_STRING(OFS_PARM1);
4699 len = strlen(partial);
4702 antipartial = PRVM_G_STRING(OFS_PARM2);
4708 antilen = strlen(antipartial);
4710 for (n = 0;n < stringbuffer->num_strings;n++)
4711 if (stringbuffer->strings[n])
4712 Mem_Free(stringbuffer->strings[n]);
4713 if (stringbuffer->strings)
4714 Mem_Free(stringbuffer->strings);
4715 stringbuffer->strings = NULL;
4717 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
4718 antiispattern = antipartial && (strchr(antipartial, '*') || strchr(antipartial, '?'));
4721 for(cvar = prog->console_cmd->cvars->vars; cvar; cvar = cvar->next)
4723 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
4726 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
4732 stringbuffer->max_strings = stringbuffer->num_strings = n;
4733 if (stringbuffer->max_strings)
4734 stringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(stringbuffer->strings[0]) * stringbuffer->max_strings);
4737 for(cvar = prog->console_cmd->cvars->vars; cvar; cvar = cvar->next)
4739 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
4742 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
4745 alloclen = strlen(cvar->name) + 1;
4746 stringbuffer->strings[n] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4747 memcpy(stringbuffer->strings[n], cvar->name, alloclen);
4762 This was a major timewaster in progs, so it was converted to C
4765 void VM_changeyaw (prvm_prog_t *prog)
4768 float ideal, current, move, speed;
4770 // this is called (VERY HACKISHLY) by VM_SV_MoveToGoal, so it can not use any
4771 // parameters because they are the parameters to VM_SV_MoveToGoal, not this
4772 //VM_SAFEPARMCOUNT(0, VM_changeyaw);
4774 ent = PRVM_PROG_TO_EDICT(PRVM_gameglobaledict(self));
4775 if (ent == prog->edicts)
4777 VM_Warning(prog, "changeyaw: can not modify world entity\n");
4782 VM_Warning(prog, "changeyaw: can not modify free entity\n");
4785 current = PRVM_gameedictvector(ent, angles)[1];
4786 current = ANGLEMOD(current);
4787 ideal = PRVM_gameedictfloat(ent, ideal_yaw);
4788 speed = PRVM_gameedictfloat(ent, yaw_speed);
4790 if (current == ideal)
4792 move = ideal - current;
4793 if (ideal > current)
4815 PRVM_gameedictvector(ent, angles)[1] = ANGLEMOD(current);
4823 void VM_changepitch (prvm_prog_t *prog)
4826 float ideal, current, move, speed;
4828 VM_SAFEPARMCOUNT(1, VM_changepitch);
4830 ent = PRVM_G_EDICT(OFS_PARM0);
4831 if (ent == prog->edicts)
4833 VM_Warning(prog, "changepitch: can not modify world entity\n");
4838 VM_Warning(prog, "changepitch: can not modify free entity\n");
4841 current = PRVM_gameedictvector(ent, angles)[0];
4842 current = ANGLEMOD(current);
4843 ideal = PRVM_gameedictfloat(ent, idealpitch);
4844 speed = PRVM_gameedictfloat(ent, pitch_speed);
4846 if (current == ideal)
4848 move = ideal - current;
4849 if (ideal > current)
4871 PRVM_gameedictvector(ent, angles)[0] = ANGLEMOD(current);
4875 void VM_uncolorstring (prvm_prog_t *prog)
4877 char szNewString[VM_TEMPSTRING_MAXSIZE];
4878 size_t szNewString_len;
4879 const char *szString;
4882 VM_SAFEPARMCOUNT(1, VM_uncolorstring);
4883 szString = PRVM_G_STRING(OFS_PARM0);
4884 szNewString_len = COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), true);
4885 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
4888 // #221 float(string str, string sub[, float startpos]) strstrofs (FTE_STRINGS)
4889 //strstr, without generating a new string. Use in conjunction with FRIK_FILE's substring for more similar strstr.
4890 void VM_strstrofs (prvm_prog_t *prog)
4892 const char *instr, *match;
4894 VM_SAFEPARMCOUNTRANGE(2, 3, VM_strstrofs);
4895 instr = PRVM_G_STRING(OFS_PARM0);
4896 match = PRVM_G_STRING(OFS_PARM1);
4897 firstofs = (prog->argc > 2)?(int)PRVM_G_FLOAT(OFS_PARM2):0;
4898 firstofs = (int)u8_bytelen(instr, firstofs);
4900 if (firstofs && (firstofs < 0 || firstofs > (int)strlen(instr)))
4902 PRVM_G_FLOAT(OFS_RETURN) = -1;
4906 match = strstr(instr+firstofs, match);
4908 PRVM_G_FLOAT(OFS_RETURN) = -1;
4910 PRVM_G_FLOAT(OFS_RETURN) = u8_strnlen(instr, match-instr);
4913 //#222 string(string s, float index) str2chr (FTE_STRINGS)
4914 void VM_str2chr (prvm_prog_t *prog)
4919 VM_SAFEPARMCOUNT(2, VM_str2chr);
4920 s = PRVM_G_STRING(OFS_PARM0);
4921 index = (int)u8_bytelen(s, (int)PRVM_G_FLOAT(OFS_PARM1));
4923 if((unsigned)index < strlen(s))
4925 if (utf8_enable.integer)
4926 ch = u8_getchar_noendptr(s + index);
4928 ch = (unsigned char)s[index];
4929 PRVM_G_FLOAT(OFS_RETURN) = ch;
4932 PRVM_G_FLOAT(OFS_RETURN) = 0;
4935 //#223 string(float c, ...) chr2str (FTE_STRINGS)
4936 void VM_chr2str (prvm_prog_t *prog)
4941 VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
4942 for(i = 0;i < prog->argc && i < (int)sizeof(t) - 1;i++)
4943 t[i] = (unsigned char)PRVM_G_FLOAT(OFS_PARM0+i*3);
4945 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, t);
4951 VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
4952 for(i = 0; i < prog->argc && len < sizeof(t)-1; ++i)
4953 len += u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0+i*3), t + len, sizeof(t)-1);
4955 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, t, len);
4958 static int chrconv_number(int i, int base, int conv)
4983 static int chrconv_punct(int i, int base, int conv)
5001 static int chrchar_alpha(int i, int basec, int baset, int convc, int convt, int charnum)
5003 //convert case and colour seperatly...
5020 baset = 128*((charnum&1) == (convt-5));
5036 return i + basec + baset;
5038 // #224 string(float ccase, float calpha, float cnum, string s, ...) strconv (FTE_STRINGS)
5039 //bulk convert a string. change case or colouring.
5040 void VM_strconv (prvm_prog_t *prog)
5042 int ccase, redalpha, rednum;
5045 unsigned char resbuf[VM_TEMPSTRING_MAXSIZE];
5046 unsigned char *result = resbuf;
5048 VM_SAFEPARMCOUNTRANGE(3, 8, VM_strconv);
5050 ccase = (int) PRVM_G_FLOAT(OFS_PARM0); //0 same, 1 lower, 2 upper
5051 redalpha = (int) PRVM_G_FLOAT(OFS_PARM1); //0 same, 1 white, 2 red, 5 alternate, 6 alternate-alternate
5052 rednum = (int) PRVM_G_FLOAT(OFS_PARM2); //0 same, 1 white, 2 red, 3 redspecial, 4 whitespecial, 5 alternate, 6 alternate-alternate
5053 resbuf_len = VM_VarString(prog, 3, (char *) resbuf, sizeof(resbuf));
5055 for (i = 0; i < resbuf_len; i++, result++) //should this be done backwards?
5057 if (*result >= '0' && *result <= '9') //normal numbers...
5058 *result = chrconv_number(*result, '0', rednum);
5059 else if (*result >= '0'+128 && *result <= '9'+128)
5060 *result = chrconv_number(*result, '0'+128, rednum);
5061 else if (*result >= '0'+128-30 && *result <= '9'+128-30)
5062 *result = chrconv_number(*result, '0'+128-30, rednum);
5063 else if (*result >= '0'-30 && *result <= '9'-30)
5064 *result = chrconv_number(*result, '0'-30, rednum);
5066 else if (*result >= 'a' && *result <= 'z') //normal numbers...
5067 *result = chrchar_alpha(*result, 'a', 0, ccase, redalpha, i);
5068 else if (*result >= 'A' && *result <= 'Z') //normal numbers...
5069 *result = chrchar_alpha(*result, 'A', 0, ccase, redalpha, i);
5070 else if (*result >= 'a'+128 && *result <= 'z'+128) //normal numbers...
5071 *result = chrchar_alpha(*result, 'a', 128, ccase, redalpha, i);
5072 else if (*result >= 'A'+128 && *result <= 'Z'+128) //normal numbers...
5073 *result = chrchar_alpha(*result, 'A', 128, ccase, redalpha, i);
5075 else if ((*result & 127) < 16 || !redalpha) //special chars..
5077 else if (*result < 128)
5078 *result = chrconv_punct(*result, 0, redalpha);
5080 *result = chrconv_punct(*result, 128, redalpha);
5084 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, (char *)resbuf, result - resbuf);
5087 // #225 string(float chars, string s, ...) strpad (FTE_STRINGS)
5088 void VM_strpad (prvm_prog_t *prog)
5090 char src[VM_TEMPSTRING_MAXSIZE];
5091 char destbuf[VM_TEMPSTRING_MAXSIZE];
5095 VM_SAFEPARMCOUNTRANGE(1, 8, VM_strpad);
5096 pad = (int) PRVM_G_FLOAT(OFS_PARM0);
5097 VM_VarString(prog, 1, src, sizeof(src));
5099 // note: < 0 = left padding, > 0 = right padding,
5100 // this is reverse logic of printf!
5101 destbuf_len = dpsnprintf(destbuf, sizeof(destbuf), "%*s", -pad, src);
5103 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, destbuf, destbuf_len);
5106 // #226 string(string info, string key, string value, ...) infoadd (FTE_STRINGS)
5107 //uses qw style \key\value strings
5108 void VM_infoadd (prvm_prog_t *prog)
5110 const char *info, *key;
5111 char value[VM_TEMPSTRING_MAXSIZE];
5112 char temp[VM_TEMPSTRING_MAXSIZE];
5114 VM_SAFEPARMCOUNTRANGE(2, 8, VM_infoadd);
5115 info = PRVM_G_STRING(OFS_PARM0);
5116 key = PRVM_G_STRING(OFS_PARM1);
5117 VM_VarString(prog, 2, value, sizeof(value));
5119 dp_strlcpy(temp, info, VM_TEMPSTRING_MAXSIZE);
5121 InfoString_SetValue(temp, VM_TEMPSTRING_MAXSIZE, key, value);
5123 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, temp, strlen(temp));
5126 // #227 string(string info, string key) infoget (FTE_STRINGS)
5127 //uses qw style \key\value strings
5128 void VM_infoget (prvm_prog_t *prog)
5132 char value[VM_TEMPSTRING_MAXSIZE];
5134 VM_SAFEPARMCOUNT(2, VM_infoget);
5135 info = PRVM_G_STRING(OFS_PARM0);
5136 key = PRVM_G_STRING(OFS_PARM1);
5138 InfoString_GetValue(info, key, value, VM_TEMPSTRING_MAXSIZE);
5140 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, value, strlen(value));
5143 //#228 float(string s1, string s2, float len) strncmp (FTE_STRINGS)
5144 // also float(string s1, string s2) strcmp (FRIK_FILE)
5145 void VM_strncmp (prvm_prog_t *prog)
5147 const char *s1, *s2;
5148 VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncmp);
5149 s1 = PRVM_G_STRING(OFS_PARM0);
5150 s2 = PRVM_G_STRING(OFS_PARM1);
5153 PRVM_G_FLOAT(OFS_RETURN) = strncmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5157 PRVM_G_FLOAT(OFS_RETURN) = strcmp(s1, s2);
5161 // #229 float(string s1, string s2) strcasecmp (FTE_STRINGS)
5162 // #230 float(string s1, string s2, float len) strncasecmp (FTE_STRINGS)
5163 void VM_strncasecmp (prvm_prog_t *prog)
5165 const char *s1, *s2;
5166 VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncasecmp);
5167 s1 = PRVM_G_STRING(OFS_PARM0);
5168 s2 = PRVM_G_STRING(OFS_PARM1);
5171 PRVM_G_FLOAT(OFS_RETURN) = strncasecmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5175 PRVM_G_FLOAT(OFS_RETURN) = strcasecmp(s1, s2);
5179 // #494 float(float caseinsensitive, string s, ...) crc16
5180 void VM_crc16(prvm_prog_t *prog)
5183 char s[VM_TEMPSTRING_MAXSIZE];
5186 VM_SAFEPARMCOUNTRANGE(2, 8, VM_crc16);
5187 insensitive = PRVM_G_FLOAT(OFS_PARM0);
5188 slen = VM_VarString(prog, 1, s, sizeof(s));
5189 PRVM_G_FLOAT(OFS_RETURN) = (unsigned short) ((insensitive ? CRC_Block_CaseInsensitive : CRC_Block) ((unsigned char *) s, slen));
5192 // #639 float(string digest, string data, ...) digest_hex
5193 void VM_digest_hex(prvm_prog_t *prog)
5201 char s[VM_TEMPSTRING_MAXSIZE];
5204 VM_SAFEPARMCOUNTRANGE(2, 8, VM_digest_hex);
5205 digest = PRVM_G_STRING(OFS_PARM0);
5208 len = VM_VarString(prog, 1, s, sizeof(s));
5212 if(!strcmp(digest, "MD4"))
5215 mdfour((unsigned char *) out, (unsigned char *) s, len);
5217 else if(!strcmp(digest, "SHA256") && Crypto_Available())
5220 sha256((unsigned char *) out, (unsigned char *) s, len);
5222 // no warning needed on mismatch - we return string_null to QC
5227 static const char *hexmap = "0123456789abcdef";
5228 for(i = 0; i < outlen; ++i)
5230 outhex[2*i] = hexmap[(out[i] >> 4) & 15];
5231 outhex[2*i+1] = hexmap[(out[i] >> 0) & 15];
5234 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outhex, 2*i);
5237 PRVM_G_INT(OFS_RETURN) = 0;
5240 void VM_wasfreed (prvm_prog_t *prog)
5242 VM_SAFEPARMCOUNT(1, VM_wasfreed);
5243 PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICT(OFS_PARM0)->free;
5246 void VM_SetTraceGlobals(prvm_prog_t *prog, const trace_t *trace)
5248 PRVM_gameglobalfloat(trace_allsolid) = trace->allsolid;
5249 PRVM_gameglobalfloat(trace_startsolid) = trace->startsolid;
5250 PRVM_gameglobalfloat(trace_fraction) = trace->fraction;
5251 PRVM_gameglobalfloat(trace_inwater) = trace->inwater;
5252 PRVM_gameglobalfloat(trace_inopen) = trace->inopen;
5253 VectorCopy(trace->endpos, PRVM_gameglobalvector(trace_endpos));
5254 VectorCopy(trace->plane.normal, PRVM_gameglobalvector(trace_plane_normal));
5255 PRVM_gameglobalfloat(trace_plane_dist) = trace->plane.dist;
5256 PRVM_gameglobaledict(trace_ent) = PRVM_EDICT_TO_PROG(trace->ent ? trace->ent : prog->edicts);
5257 PRVM_gameglobalfloat(trace_dpstartcontents) = trace->startsupercontents;
5258 PRVM_gameglobalfloat(trace_dphitcontents) = trace->hitsupercontents;
5259 PRVM_gameglobalfloat(trace_dphitq3surfaceflags) = trace->hitq3surfaceflags;
5260 PRVM_gameglobalstring(trace_dphittexturename) = trace->hittexture ? PRVM_SetTempString(prog, trace->hittexture->name, strlen(trace->hittexture->name)) : 0;
5263 void VM_ClearTraceGlobals(prvm_prog_t *prog)
5265 // clean up all trace globals when leaving the VM (anti-triggerbot safeguard)
5266 PRVM_gameglobalfloat(trace_allsolid) = 0;
5267 PRVM_gameglobalfloat(trace_startsolid) = 0;
5268 PRVM_gameglobalfloat(trace_fraction) = 0;
5269 PRVM_gameglobalfloat(trace_inwater) = 0;
5270 PRVM_gameglobalfloat(trace_inopen) = 0;
5271 VectorClear(PRVM_gameglobalvector(trace_endpos));
5272 VectorClear(PRVM_gameglobalvector(trace_plane_normal));
5273 PRVM_gameglobalfloat(trace_plane_dist) = 0;
5274 PRVM_gameglobaledict(trace_ent) = PRVM_EDICT_TO_PROG(prog->edicts);
5275 PRVM_gameglobalfloat(trace_dpstartcontents) = 0;
5276 PRVM_gameglobalfloat(trace_dphitcontents) = 0;
5277 PRVM_gameglobalfloat(trace_dphitq3surfaceflags) = 0;
5278 PRVM_gameglobalstring(trace_dphittexturename) = 0;
5283 void VM_Cmd_Init(prvm_prog_t *prog)
5285 // only init the stuff for the current prog
5286 VM_Files_Init(prog);
5287 VM_Search_Init(prog);
5290 static void animatemodel_reset(prvm_prog_t *prog);
5292 void VM_Cmd_Reset(prvm_prog_t *prog)
5294 CL_PurgeOwner( MENUOWNER );
5295 VM_Search_Reset(prog);
5296 VM_Files_CloseAll(prog);
5297 animatemodel_reset(prog);
5300 // #510 string(string input, ...) uri_escape (DP_QC_URI_ESCAPE)
5301 // does URI escaping on a string (replace evil stuff by %AB escapes)
5302 void VM_uri_escape (prvm_prog_t *prog)
5304 char src[VM_TEMPSTRING_MAXSIZE];
5305 char dest[VM_TEMPSTRING_MAXSIZE];
5307 static const char *hex = "0123456789ABCDEF";
5309 VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_escape);
5310 VM_VarString(prog, 0, src, sizeof(src));
5312 for(p = src, q = dest; *p && q < dest + sizeof(dest) - 3; ++p)
5314 if((*p >= 'A' && *p <= 'Z')
5315 || (*p >= 'a' && *p <= 'z')
5316 || (*p >= '0' && *p <= '9')
5317 || (*p == '-') || (*p == '_') || (*p == '.')
5318 || (*p == '!') || (*p == '~')
5319 || (*p == '\'') || (*p == '(') || (*p == ')'))
5324 *q++ = hex[(*(unsigned char *)p >> 4) & 0xF];
5325 *q++ = hex[ *(unsigned char *)p & 0xF];
5330 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, dest, q - dest);
5333 // #510 string(string input, ...) uri_unescape (DP_QC_URI_ESCAPE)
5334 // does URI unescaping on a string (get back the evil stuff)
5335 void VM_uri_unescape (prvm_prog_t *prog)
5337 char src[VM_TEMPSTRING_MAXSIZE];
5338 char dest[VM_TEMPSTRING_MAXSIZE];
5342 VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_unescape);
5343 VM_VarString(prog, 0, src, sizeof(src));
5345 for(p = src, q = dest; *p; ) // no need to check size, because unescape can't expand
5349 if(p[1] >= '0' && p[1] <= '9')
5351 else if(p[1] >= 'a' && p[1] <= 'f')
5352 hi = p[1] - 'a' + 10;
5353 else if(p[1] >= 'A' && p[1] <= 'F')
5354 hi = p[1] - 'A' + 10;
5357 if(p[2] >= '0' && p[2] <= '9')
5359 else if(p[2] >= 'a' && p[2] <= 'f')
5360 lo = p[2] - 'a' + 10;
5361 else if(p[2] >= 'A' && p[2] <= 'F')
5362 lo = p[2] - 'A' + 10;
5365 if(hi != 0 || lo != 0) // don't unescape NUL bytes
5366 *q++ = (char) (hi * 0x10 + lo);
5377 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, dest, q - dest);
5380 // #502 string(string filename) whichpack (DP_QC_WHICHPACK)
5381 // returns the name of the pack containing a file, or "" if it is not in any pack (but local or non-existant)
5382 void VM_whichpack (prvm_prog_t *prog)
5384 const char *fn, *pack;
5386 VM_SAFEPARMCOUNT(1, VM_whichpack);
5387 fn = PRVM_G_STRING(OFS_PARM0);
5388 pack = FS_WhichPack(fn);
5390 PRVM_G_INT(OFS_RETURN) = pack ? PRVM_SetTempString(prog, pack, strlen(pack)) : 0;
5398 char buffer[MAX_INPUTLINE];
5400 unsigned char *postdata; // free when uri_to_prog_t is freed
5402 char *sigdata; // free when uri_to_prog_t is freed
5407 static void uri_to_string_callback(int status, size_t length_received, unsigned char *buffer, void *cbdata)
5410 uri_to_prog_t *handle = (uri_to_prog_t *) cbdata;
5412 prog = handle->prog;
5415 // curl reply came too late... so just drop it
5416 if(handle->postdata)
5417 Z_Free(handle->postdata);
5419 Z_Free(handle->sigdata);
5424 if((prog->starttime == handle->starttime) && (PRVM_allfunction(URI_Get_Callback)))
5426 if(length_received >= sizeof(handle->buffer))
5427 length_received = sizeof(handle->buffer) - 1;
5428 handle->buffer[length_received] = '\0';
5430 PRVM_G_FLOAT(OFS_PARM0) = handle->id;
5431 PRVM_G_FLOAT(OFS_PARM1) = status;
5432 PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(prog, handle->buffer, length_received);
5433 prog->ExecuteProgram(prog, PRVM_allfunction(URI_Get_Callback), "QC function URI_Get_Callback is missing");
5436 if(handle->postdata)
5437 Z_Free(handle->postdata);
5439 Z_Free(handle->sigdata);
5443 // uri_get() gets content from an URL and calls a callback "uri_get_callback" with it set as string; an unique ID of the transfer is returned
5444 // returns 1 on success, and then calls the callback with the ID, 0 or the HTTP status code, and the received data in a string
5445 void VM_uri_get (prvm_prog_t *prog)
5450 uri_to_prog_t *handle;
5451 const char *posttype = NULL;
5452 const char *postseparator = NULL;
5453 int poststringbuffer = -1;
5455 const char *query_string = NULL;
5458 if(!PRVM_allfunction(URI_Get_Callback))
5459 prog->error_cmd("uri_get called by %s without URI_Get_Callback defined", prog->name);
5461 VM_SAFEPARMCOUNTRANGE(2, 6, VM_uri_get);
5463 url = PRVM_G_STRING(OFS_PARM0);
5464 id = PRVM_G_FLOAT(OFS_PARM1);
5466 posttype = PRVM_G_STRING(OFS_PARM2);
5468 postseparator = PRVM_G_STRING(OFS_PARM3);
5470 poststringbuffer = PRVM_G_FLOAT(OFS_PARM4);
5472 postkeyid = PRVM_G_FLOAT(OFS_PARM5);
5473 handle = (uri_to_prog_t *) Z_Malloc(sizeof(*handle)); // this can't be the prog's mem pool, as curl may call the callback later!
5475 query_string = strchr(url, '?');
5478 lq = query_string ? strlen(query_string) : 0;
5480 handle->prog = prog;
5481 handle->starttime = prog->starttime;
5483 if(postseparator && posttype && *posttype)
5485 size_t l = strlen(postseparator);
5486 if(poststringbuffer >= 0)
5491 prvm_stringbuffer_t *stringbuffer;
5492 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, poststringbuffer);
5495 VM_Warning(prog, "uri_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
5499 for(i = 0;i < stringbuffer->num_strings;i++)
5503 if(stringbuffer->strings[i])
5504 ltotal += strlen(stringbuffer->strings[i]);
5506 handle->postdata = (unsigned char *)Z_Malloc(ltotal + 1 + lq);
5507 handle->postlen = ltotal;
5509 for(i = 0;i < stringbuffer->num_strings;i++)
5513 memcpy(handle->postdata + ltotal, postseparator, l);
5516 if(stringbuffer->strings[i])
5518 memcpy(handle->postdata + ltotal, stringbuffer->strings[i], strlen(stringbuffer->strings[i]));
5519 ltotal += strlen(stringbuffer->strings[i]);
5522 if(ltotal != handle->postlen)
5523 prog->error_cmd("%s: string buffer content size mismatch, possible overrun", prog->name);
5527 handle->postdata = (unsigned char *)Z_Malloc(l + 1 + lq);
5528 handle->postlen = l;
5529 memcpy(handle->postdata, postseparator, l);
5531 handle->postdata[handle->postlen] = 0;
5533 memcpy(handle->postdata + handle->postlen + 1, query_string, lq);
5536 // POST: we sign postdata \0 query string
5538 handle->sigdata = (char *)Z_Malloc(8192);
5539 dp_strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
5540 l = strlen(handle->sigdata);
5541 handle->siglen = Crypto_SignDataDetached(handle->postdata, handle->postlen + 1 + lq, postkeyid, handle->sigdata + l, 8192 - l);
5544 Z_Free(handle->sigdata);
5545 handle->sigdata = NULL;
5548 ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
5551 Z_Free(handle->sigdata);
5552 handle->sigdata = NULL;
5555 handle->siglen = l + ll;
5556 handle->sigdata[handle->siglen] = 0;
5559 dp_strlcpy(handle->posttype, posttype, sizeof(handle->posttype));
5560 ret = Curl_Begin_ToMemory_POST(url, handle->sigdata, 0, handle->posttype, handle->postdata, handle->postlen, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
5564 if(postkeyid >= 0 && query_string)
5566 // GET: we sign JUST the query string
5568 handle->sigdata = (char *)Z_Malloc(8192);
5569 dp_strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
5570 l = strlen(handle->sigdata);
5571 handle->siglen = Crypto_SignDataDetached(query_string, lq, postkeyid, handle->sigdata + l, 8192 - l);
5574 Z_Free(handle->sigdata);
5575 handle->sigdata = NULL;
5578 ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
5581 Z_Free(handle->sigdata);
5582 handle->sigdata = NULL;
5585 handle->siglen = l + ll;
5586 handle->sigdata[handle->siglen] = 0;
5589 handle->postdata = NULL;
5590 handle->postlen = 0;
5591 ret = Curl_Begin_ToMemory_POST(url, handle->sigdata, 0, NULL, NULL, 0, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
5595 PRVM_G_INT(OFS_RETURN) = 1;
5599 if(handle->postdata)
5600 Z_Free(handle->postdata);
5602 Z_Free(handle->sigdata);
5604 PRVM_G_INT(OFS_RETURN) = 0;
5608 void VM_netaddress_resolve (prvm_prog_t *prog)
5611 char normalized[128];
5612 size_t normalized_len;
5614 lhnetaddress_t addr;
5616 VM_SAFEPARMCOUNTRANGE(1, 2, VM_netaddress_resolve);
5618 ip = PRVM_G_STRING(OFS_PARM0);
5621 port = (int) PRVM_G_FLOAT(OFS_PARM1);
5623 if(LHNETADDRESS_FromString(&addr, ip, port) && (normalized_len = LHNETADDRESS_ToString(&addr, normalized, sizeof(normalized), prog->argc > 1)))
5624 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, normalized, normalized_len);
5626 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
5629 //string(prvm_prog_t *prog) getextresponse = #624; // returns the next extResponse packet that was sent to this client
5630 void VM_CL_getextresponse (prvm_prog_t *prog)
5632 VM_SAFEPARMCOUNT(0,VM_argv);
5634 if (cl_net_extresponse_count <= 0)
5635 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
5639 --cl_net_extresponse_count;
5640 first = (cl_net_extresponse_last + NET_EXTRESPONSE_MAX - cl_net_extresponse_count) % NET_EXTRESPONSE_MAX;
5641 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cl_net_extresponse[first], strlen(cl_net_extresponse[first]));
5645 void VM_SV_getextresponse (prvm_prog_t *prog)
5647 VM_SAFEPARMCOUNT(0,VM_argv);
5649 if (sv_net_extresponse_count <= 0)
5650 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
5654 --sv_net_extresponse_count;
5655 first = (sv_net_extresponse_last + NET_EXTRESPONSE_MAX - sv_net_extresponse_count) % NET_EXTRESPONSE_MAX;
5656 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, sv_net_extresponse[first], strlen(sv_net_extresponse[first]));
5660 // DP_QC_NUDGEOUTOFSOLID
5661 // float(entity ent) nudgeoutofsolid = #567;
5662 void VM_nudgeoutofsolid(prvm_prog_t *prog)
5666 VM_SAFEPARMCOUNTRANGE(1, 1, VM_nudgeoutofsolid);
5668 ent = PRVM_G_EDICT(OFS_PARM0);
5669 if (ent == prog->edicts)
5671 VM_Warning(prog, "nudgeoutofsolid: can not modify world entity\n");
5672 PRVM_G_FLOAT(OFS_RETURN) = 0;
5677 VM_Warning(prog, "nudgeoutofsolid: can not modify free entity\n");
5678 PRVM_G_FLOAT(OFS_RETURN) = 0;
5682 PRVM_G_FLOAT(OFS_RETURN) = PHYS_NudgeOutOfSolid(prog, ent);
5684 if (PRVM_G_FLOAT(OFS_RETURN) > 0)
5686 if (prog == SVVM_prog)
5688 else if (prog == CLVM_prog)
5691 Sys_Error("PHYS_NudgeOutOfSolid: cannot be called from %s VM\n", prog->name);
5697 Common functions between menu.dat and clsprogs
5701 //#349 float() isdemo
5702 void VM_CL_isdemo (prvm_prog_t *prog)
5704 VM_SAFEPARMCOUNT(0, VM_CL_isdemo);
5705 PRVM_G_FLOAT(OFS_RETURN) = cls.demoplayback;
5708 //#355 float() videoplaying
5709 void VM_CL_videoplaying (prvm_prog_t *prog)
5711 VM_SAFEPARMCOUNT(0, VM_CL_videoplaying);
5712 PRVM_G_FLOAT(OFS_RETURN) = cl_videoplaying;
5719 callfunction(...,string function_name)
5723 void VM_callfunction(prvm_prog_t *prog)
5728 VM_SAFEPARMCOUNTRANGE(1, 8, VM_callfunction);
5730 s = PRVM_G_STRING(OFS_PARM0+(prog->argc - 1)*3);
5732 VM_CheckEmptyString(prog, s);
5734 func = PRVM_ED_FindFunction(prog, s);
5737 prog->error_cmd("VM_callfunction: function %s not found !", s);
5738 else if (func->first_statement < 0)
5740 // negative statements are built in functions
5741 int builtinnumber = -func->first_statement;
5742 prog->xfunction->builtinsprofile++;
5743 if (builtinnumber < prog->numbuiltins && prog->builtins[builtinnumber])
5744 prog->builtins[builtinnumber](prog);
5746 prog->error_cmd("No such builtin #%i in %s; most likely cause: outdated engine build. Try updating!", builtinnumber, prog->name);
5748 else if(func - prog->functions > 0)
5751 prog->ExecuteProgram(prog, func - prog->functions,"");
5760 float isfunction(string function_name)
5763 void VM_isfunction(prvm_prog_t *prog)
5768 VM_SAFEPARMCOUNT(1, VM_isfunction);
5770 s = PRVM_G_STRING(OFS_PARM0);
5772 VM_CheckEmptyString(prog, s);
5774 func = PRVM_ED_FindFunction(prog, s);
5777 PRVM_G_FLOAT(OFS_RETURN) = false;
5779 PRVM_G_FLOAT(OFS_RETURN) = true;
5786 string sprintf(string format, ...)
5790 void VM_sprintf(prvm_prog_t *prog)
5793 char outbuf[MAX_INPUTLINE];
5794 char *o = outbuf, *end = outbuf + sizeof(outbuf), *err;
5797 int width, precision, thisarg, flags;
5801 static prvm_int_t dummyivec[3] = {0, 0, 0};
5802 static prvm_vec_t dummyvec[3] = {0, 0, 0};
5805 #define PRINTF_ALTERNATE 1
5806 #define PRINTF_ZEROPAD 2
5807 #define PRINTF_LEFT 4
5808 #define PRINTF_SPACEPOSITIVE 8
5809 #define PRINTF_SIGNPOSITIVE 16
5813 s = PRVM_G_STRING(OFS_PARM0);
5815 #define GETARG_FLOAT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_FLOAT(OFS_PARM0 + 3 * (a))) : 0)
5816 #define GETARG_VECTOR(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyvec)
5817 #define GETARG_INT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_INT(OFS_PARM0 + 3 * (a))) : 0)
5818 #define GETARG_INTVECTOR(a) (((a)>=1 && (a)<prog->argc) ? ((prvm_int_t*) PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyivec)
5819 #define GETARG_STRING(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_STRING(OFS_PARM0 + 3 * (a))) : "")
5834 // complete directive format:
5843 // is number following?
5844 if(*s >= '0' && *s <= '9')
5846 width = strtol(s, &err, 10);
5849 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5862 flags |= PRINTF_ZEROPAD;
5864 width = -1; // it was just a flag
5876 case '#': flags |= PRINTF_ALTERNATE; break;
5877 case '0': flags |= PRINTF_ZEROPAD; break;
5878 case '-': flags |= PRINTF_LEFT; break;
5879 case ' ': flags |= PRINTF_SPACEPOSITIVE; break;
5880 case '+': flags |= PRINTF_SIGNPOSITIVE; break;
5890 if(*s >= '0' && *s <= '9')
5892 width = strtol(s, &err, 10);
5893 if(!err || *err != '$')
5895 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5902 width = GETARG_FLOAT(width);
5905 flags |= PRINTF_LEFT;
5909 else if(*s >= '0' && *s <= '9')
5911 width = strtol(s, &err, 10);
5914 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5920 flags |= PRINTF_LEFT;
5924 // otherwise width stays -1
5933 if(*s >= '0' && *s <= '9')
5935 precision = strtol(s, &err, 10);
5936 if(!err || *err != '$')
5938 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5944 precision = argpos++;
5945 precision = GETARG_FLOAT(precision);
5947 else if(*s >= '0' && *s <= '9')
5949 precision = strtol(s, &err, 10);
5952 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5959 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5968 case 'h': isfloat = 1; break;
5969 case 'l': isfloat = 0; break;
5970 case 'L': isfloat = 0; break;
5981 // now s points to the final directive char and is no longer changed
5996 if(*s != 's' && *s != 'c')
5997 if(flags & PRINTF_ALTERNATE) *f++ = '#';
5998 if(flags & PRINTF_ZEROPAD) *f++ = '0';
5999 if(flags & PRINTF_LEFT) *f++ = '-';
6000 if(flags & PRINTF_SPACEPOSITIVE) *f++ = ' ';
6001 if(flags & PRINTF_SIGNPOSITIVE) *f++ = '+';
6008 if(*s == 'd' || *s == 'i' || *s == 'o' || *s == 'u' || *s == 'x' || *s == 'X')
6010 // make it use a good integer type
6011 for(p = INT_LOSSLESS_FORMAT_SIZE; *p; )
6017 if(width < 0) // not set
6023 if(precision < 0) // not set
6024 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? INT_LOSSLESS_FORMAT_CONVERT_S(GETARG_FLOAT(thisarg)) : INT_LOSSLESS_FORMAT_CONVERT_S(GETARG_INT(thisarg))));
6026 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? INT_LOSSLESS_FORMAT_CONVERT_S(GETARG_FLOAT(thisarg)) : INT_LOSSLESS_FORMAT_CONVERT_S(GETARG_INT(thisarg))));
6028 case 'o': case 'u': case 'x': case 'X':
6029 if(precision < 0) // not set
6030 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? INT_LOSSLESS_FORMAT_CONVERT_U(GETARG_FLOAT(thisarg)) : INT_LOSSLESS_FORMAT_CONVERT_U(GETARG_INT(thisarg))));
6032 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? INT_LOSSLESS_FORMAT_CONVERT_U(GETARG_FLOAT(thisarg)) : INT_LOSSLESS_FORMAT_CONVERT_U(GETARG_INT(thisarg))));
6034 case 'e': case 'E': case 'f': case 'F': case 'g': case 'G':
6035 if(precision < 0) // not set
6036 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6038 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6042 if(precision < 0) // not set
6043 o += dpsnprintf(o, end - o, va(vabuf, sizeof(vabuf), "%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6044 width, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6045 width, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6046 width, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6049 o += dpsnprintf(o, end - o, va(vabuf, sizeof(vabuf), "%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6050 width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6051 width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6052 width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6056 if(flags & PRINTF_ALTERNATE)
6058 if(precision < 0) // not set
6059 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6061 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6065 unsigned int c = (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg));
6067 const char *buf = u8_encodech(c, NULL, charbuf16);
6070 if(precision < 0) // not set
6071 precision = end - o - 1;
6072 o += u8_strpad(o, end - o, buf, (flags & PRINTF_LEFT) != 0, width, precision);
6075 //spike FIXME -- 'S' for quoted tokenize-safe-or-print escaping of strings so stuff can safely survive console commands.
6077 if(flags & PRINTF_ALTERNATE)
6079 if(precision < 0) // not set
6080 o += dpsnprintf(o, end - o, formatbuf, width, GETARG_STRING(thisarg));
6082 o += dpsnprintf(o, end - o, formatbuf, width, precision, GETARG_STRING(thisarg));
6086 if(precision < 0) // not set
6087 precision = end - o - 1;
6088 if(flags & PRINTF_SIGNPOSITIVE)
6089 o += u8_strpad(o, end - o, GETARG_STRING(thisarg), (flags & PRINTF_LEFT) != 0, width, precision);
6091 o += u8_strpad_colorcodes(o, end - o, GETARG_STRING(thisarg), (flags & PRINTF_LEFT) != 0, width, precision);
6095 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
6112 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outbuf, o - outbuf);
6118 static model_t *getmodel(prvm_prog_t *prog, prvm_edict_t *ed)
6120 if (prog == SVVM_prog)
6121 return SV_GetModelFromEdict(ed);
6122 else if (prog == CLVM_prog)
6123 return CL_GetModelFromEdict(ed);
6128 struct animatemodel_cache
6131 frameblend_t frameblend[MAX_FRAMEBLENDS];
6132 skeleton_t *skeleton_p;
6133 skeleton_t skeleton;
6134 float *data_vertex3f;
6135 float *data_svector3f;
6136 float *data_tvector3f;
6137 float *data_normal3f;
6139 float *buf_vertex3f;
6140 float *buf_svector3f;
6141 float *buf_tvector3f;
6142 float *buf_normal3f;
6145 static void animatemodel_reset(prvm_prog_t *prog)
6147 if (!prog->animatemodel_cache)
6149 if(prog->animatemodel_cache->buf_vertex3f) Mem_Free(prog->animatemodel_cache->buf_vertex3f);
6150 if(prog->animatemodel_cache->buf_svector3f) Mem_Free(prog->animatemodel_cache->buf_svector3f);
6151 if(prog->animatemodel_cache->buf_tvector3f) Mem_Free(prog->animatemodel_cache->buf_tvector3f);
6152 if(prog->animatemodel_cache->buf_normal3f) Mem_Free(prog->animatemodel_cache->buf_normal3f);
6153 Mem_Free(prog->animatemodel_cache);
6156 static void animatemodel(prvm_prog_t *prog, model_t *model, prvm_edict_t *ed)
6158 skeleton_t *skeleton;
6159 int skeletonindex = -1;
6161 struct animatemodel_cache *animatemodel_cache;
6162 if (!prog->animatemodel_cache)
6164 prog->animatemodel_cache = (struct animatemodel_cache *)Mem_Alloc(prog->progs_mempool, sizeof(struct animatemodel_cache));
6165 memset(prog->animatemodel_cache, 0, sizeof(struct animatemodel_cache));
6167 animatemodel_cache = prog->animatemodel_cache;
6168 if(!(model->surfmesh.isanimated && model->AnimateVertices))
6170 animatemodel_cache->data_vertex3f = model->surfmesh.data_vertex3f;
6171 animatemodel_cache->data_svector3f = model->surfmesh.data_svector3f;
6172 animatemodel_cache->data_tvector3f = model->surfmesh.data_tvector3f;
6173 animatemodel_cache->data_normal3f = model->surfmesh.data_normal3f;
6176 need |= (animatemodel_cache->model != model);
6177 VM_GenerateFrameGroupBlend(prog, ed->priv.server->framegroupblend, ed);
6178 VM_FrameBlendFromFrameGroupBlend(ed->priv.server->frameblend, ed->priv.server->framegroupblend, model, PRVM_serverglobalfloat(time));
6179 need |= (memcmp(&animatemodel_cache->frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend))) != 0;
6180 skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
6181 if (!(skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones))
6183 need |= (animatemodel_cache->skeleton_p != skeleton);
6185 need |= (memcmp(&animatemodel_cache->skeleton, skeleton, sizeof(ed->priv.server->skeleton))) != 0;
6188 if(model->surfmesh.num_vertices > animatemodel_cache->max_vertices)
6190 animatemodel_cache->max_vertices = model->surfmesh.num_vertices * 2;
6191 if(animatemodel_cache->buf_vertex3f) Mem_Free(animatemodel_cache->buf_vertex3f);
6192 if(animatemodel_cache->buf_svector3f) Mem_Free(animatemodel_cache->buf_svector3f);
6193 if(animatemodel_cache->buf_tvector3f) Mem_Free(animatemodel_cache->buf_tvector3f);
6194 if(animatemodel_cache->buf_normal3f) Mem_Free(animatemodel_cache->buf_normal3f);
6195 animatemodel_cache->buf_vertex3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6196 animatemodel_cache->buf_svector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6197 animatemodel_cache->buf_tvector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6198 animatemodel_cache->buf_normal3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6200 animatemodel_cache->data_vertex3f = animatemodel_cache->buf_vertex3f;
6201 animatemodel_cache->data_svector3f = animatemodel_cache->buf_svector3f;
6202 animatemodel_cache->data_tvector3f = animatemodel_cache->buf_tvector3f;
6203 animatemodel_cache->data_normal3f = animatemodel_cache->buf_normal3f;
6204 VM_UpdateEdictSkeleton(prog, ed, model, ed->priv.server->frameblend);
6205 model->AnimateVertices(model, ed->priv.server->frameblend, &ed->priv.server->skeleton, animatemodel_cache->data_vertex3f, animatemodel_cache->data_normal3f, animatemodel_cache->data_svector3f, animatemodel_cache->data_tvector3f);
6206 animatemodel_cache->model = model;
6207 memcpy(&animatemodel_cache->frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend));
6208 animatemodel_cache->skeleton_p = skeleton;
6210 memcpy(&animatemodel_cache->skeleton, skeleton, sizeof(ed->priv.server->skeleton));
6213 static void getmatrix(prvm_prog_t *prog, prvm_edict_t *ed, matrix4x4_t *out)
6215 if (prog == SVVM_prog)
6216 SV_GetEntityMatrix(prog, ed, out, false);
6217 else if (prog == CLVM_prog)
6218 CL_GetEntityMatrix(prog, ed, out, false);
6220 *out = identitymatrix;
6223 static void applytransform_forward(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6226 getmatrix(prog, ed, &m);
6227 Matrix4x4_Transform(&m, in, out);
6230 static void applytransform_forward_direction(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6233 getmatrix(prog, ed, &m);
6234 Matrix4x4_Transform3x3(&m, in, out);
6237 static void applytransform_inverted(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6240 getmatrix(prog, ed, &m);
6241 Matrix4x4_Invert_Full(&n, &m);
6242 Matrix4x4_Transform3x3(&n, in, out);
6245 static void applytransform_forward_normal(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6249 getmatrix(prog, ed, &m);
6250 Matrix4x4_TransformPositivePlane(&m, in[0], in[1], in[2], 0, p);
6254 static void clippointtosurface(prvm_prog_t *prog, prvm_edict_t *ed, model_t *model, msurface_t *surface, vec3_t p, vec3_t out)
6257 float *v[3], facenormal[3], edgenormal[3], sidenormal[3], temp[3], offsetdist, dist, bestdist;
6259 animatemodel(prog, model, ed);
6260 bestdist = 1000000000;
6262 for (i = 0, e = (model->surfmesh.data_element3i + 3 * surface->num_firsttriangle);i < surface->num_triangles;i++, e += 3)
6264 // clip original point to each triangle of the surface and find the
6265 // triangle that is closest
6266 v[0] = prog->animatemodel_cache->data_vertex3f + e[0] * 3;
6267 v[1] = prog->animatemodel_cache->data_vertex3f + e[1] * 3;
6268 v[2] = prog->animatemodel_cache->data_vertex3f + e[2] * 3;
6269 TriangleNormal(v[0], v[1], v[2], facenormal);
6270 VectorNormalize(facenormal);
6271 offsetdist = DotProduct(v[0], facenormal) - DotProduct(p, facenormal);
6272 VectorMA(p, offsetdist, facenormal, temp);
6273 for (j = 0, k = 2;j < 3;k = j, j++)
6275 VectorSubtract(v[k], v[j], edgenormal);
6276 CrossProduct(edgenormal, facenormal, sidenormal);
6277 VectorNormalize(sidenormal);
6278 offsetdist = DotProduct(v[k], sidenormal) - DotProduct(temp, sidenormal);
6280 VectorMA(temp, offsetdist, sidenormal, temp);
6282 dist = VectorDistance2(temp, p);
6283 if (bestdist > dist)
6286 VectorCopy(temp, out);
6291 static msurface_t *getsurface(model_t *model, int surfacenum)
6293 if (surfacenum < 0 || surfacenum >= model->submodelsurfaces_end - model->submodelsurfaces_start)
6295 return model->data_surfaces + surfacenum + model->submodelsurfaces_start;
6299 //PF_getsurfacenumpoints, // #434 float(entity e, float s) getsurfacenumpoints = #434;
6300 void VM_getsurfacenumpoints(prvm_prog_t *prog)
6303 msurface_t *surface;
6304 VM_SAFEPARMCOUNT(2, VM_getsurfacenumpoints);
6305 // return 0 if no such surface
6306 if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6308 PRVM_G_FLOAT(OFS_RETURN) = 0;
6312 // note: this (incorrectly) assumes it is a simple polygon
6313 PRVM_G_FLOAT(OFS_RETURN) = surface->num_vertices;
6315 //PF_getsurfacepoint, // #435 vector(entity e, float s, float n) getsurfacepoint = #435;
6316 void VM_getsurfacepoint(prvm_prog_t *prog)
6320 msurface_t *surface;
6323 VM_SAFEPARMCOUNT(3, VM_getsurfacepoint);
6324 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6325 ed = PRVM_G_EDICT(OFS_PARM0);
6326 if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6328 // note: this (incorrectly) assumes it is a simple polygon
6329 pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6330 if (pointnum < 0 || pointnum >= surface->num_vertices)
6332 animatemodel(prog, model, ed);
6333 applytransform_forward(prog, &(prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6334 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6336 //PF_getsurfacepointattribute, // #486 vector(entity e, float s, float n, float a) getsurfacepointattribute = #486;
6337 // float SPA_POSITION = 0;
6338 // float SPA_S_AXIS = 1;
6339 // float SPA_T_AXIS = 2;
6340 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6341 // float SPA_TEXCOORDS0 = 4;
6342 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6343 // float SPA_LIGHTMAP0_COLOR = 6;
6344 void VM_getsurfacepointattribute(prvm_prog_t *prog)
6348 msurface_t *surface;
6353 VM_SAFEPARMCOUNT(4, VM_getsurfacepointattribute);
6354 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6355 ed = PRVM_G_EDICT(OFS_PARM0);
6356 if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6358 pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6359 if (pointnum < 0 || pointnum >= surface->num_vertices)
6361 attributetype = (int) PRVM_G_FLOAT(OFS_PARM3);
6363 animatemodel(prog, model, ed);
6365 switch( attributetype ) {
6366 // float SPA_POSITION = 0;
6368 applytransform_forward(prog, &(prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6369 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6371 // float SPA_S_AXIS = 1;
6373 applytransform_forward_direction(prog, &(prog->animatemodel_cache->data_svector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6374 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6376 // float SPA_T_AXIS = 2;
6378 applytransform_forward_direction(prog, &(prog->animatemodel_cache->data_tvector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6379 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6381 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6383 applytransform_forward_direction(prog, &(prog->animatemodel_cache->data_normal3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6384 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6386 // float SPA_TEXCOORDS0 = 4;
6388 float *texcoord = &(model->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[pointnum * 2];
6389 result[0] = texcoord[0];
6390 result[1] = texcoord[1];
6392 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6395 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6397 float *texcoord = &(model->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[pointnum * 2];
6398 result[0] = texcoord[0];
6399 result[1] = texcoord[1];
6401 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6404 // float SPA_LIGHTMAP0_COLOR = 6;
6406 // ignore alpha for now..
6407 VectorCopy( &(model->surfmesh.data_lightmapcolor4f + 4 * surface->num_firstvertex)[pointnum * 4], PRVM_G_VECTOR(OFS_RETURN));
6410 VectorSet( PRVM_G_VECTOR(OFS_RETURN), 0.0f, 0.0f, 0.0f );
6414 //PF_getsurfacenormal, // #436 vector(entity e, float s) getsurfacenormal = #436;
6415 void VM_getsurfacenormal(prvm_prog_t *prog)
6418 msurface_t *surface;
6421 VM_SAFEPARMCOUNT(2, VM_getsurfacenormal);
6422 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6423 if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6425 // note: this only returns the first triangle, so it doesn't work very
6426 // well for curved surfaces or arbitrary meshes
6427 animatemodel(prog, model, PRVM_G_EDICT(OFS_PARM0));
6428 TriangleNormal((prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex), (prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex) + 3, (prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex) + 6, normal);
6429 applytransform_forward_normal(prog, normal, PRVM_G_EDICT(OFS_PARM0), result);
6430 VectorNormalize(result);
6431 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6433 //PF_getsurfacetexture, // #437 string(entity e, float s) getsurfacetexture = #437;
6434 void VM_getsurfacetexture(prvm_prog_t *prog)
6437 msurface_t *surface;
6439 VM_SAFEPARMCOUNT(2, VM_getsurfacetexture);
6440 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
6441 if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6443 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, surface->texture->name, strlen(surface->texture->name));
6445 //PF_getsurfacenearpoint, // #438 float(entity e, vector p) getsurfacenearpoint = #438;
6446 void VM_getsurfacenearpoint(prvm_prog_t *prog)
6448 int surfacenum, best;
6450 vec_t dist, bestdist;
6453 msurface_t *surface;
6455 VM_SAFEPARMCOUNT(2, VM_getsurfacenearpoint);
6456 PRVM_G_FLOAT(OFS_RETURN) = -1;
6457 ed = PRVM_G_EDICT(OFS_PARM0);
6458 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), point);
6460 if (!ed || ed->free)
6462 model = getmodel(prog, ed);
6463 if (!model || !model->num_surfaces)
6466 animatemodel(prog, model, ed);
6468 applytransform_inverted(prog, point, ed, p);
6470 bestdist = 1000000000;
6471 for (surfacenum = model->submodelsurfaces_start;surfacenum < model->submodelsurfaces_end;surfacenum++)
6473 surface = model->data_surfaces + surfacenum;
6474 // first see if the nearest point on the surface's box is closer than the previous match
6475 clipped[0] = bound(surface->mins[0], p[0], surface->maxs[0]) - p[0];
6476 clipped[1] = bound(surface->mins[1], p[1], surface->maxs[1]) - p[1];
6477 clipped[2] = bound(surface->mins[2], p[2], surface->maxs[2]) - p[2];
6478 dist = VectorLength2(clipped);
6479 if (dist < bestdist)
6481 // it is, check the nearest point on the actual geometry
6482 clippointtosurface(prog, ed, model, surface, p, clipped);
6483 VectorSubtract(clipped, p, clipped);
6484 dist += VectorLength2(clipped);
6485 if (dist < bestdist)
6487 // that's closer too, store it as the best match
6488 best = surfacenum - model->submodelsurfaces_start;
6493 PRVM_G_FLOAT(OFS_RETURN) = best;
6495 //PF_getsurfaceclippedpoint, // #439 vector(entity e, float s, vector p) getsurfaceclippedpoint = #439;
6496 void VM_getsurfaceclippedpoint(prvm_prog_t *prog)
6500 msurface_t *surface;
6502 VM_SAFEPARMCOUNT(3, VM_getsurfaceclippedpoint);
6503 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6504 ed = PRVM_G_EDICT(OFS_PARM0);
6505 if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6507 animatemodel(prog, model, ed);
6508 VectorCopy(PRVM_G_VECTOR(OFS_PARM2), inp);
6509 applytransform_inverted(prog, inp, ed, p);
6510 clippointtosurface(prog, ed, model, surface, p, out);
6511 VectorAdd(out, PRVM_serveredictvector(ed, origin), PRVM_G_VECTOR(OFS_RETURN));
6514 //PF_getsurfacenumtriangles, // #??? float(entity e, float s) getsurfacenumtriangles = #???;
6515 void VM_getsurfacenumtriangles(prvm_prog_t *prog)
6518 msurface_t *surface;
6519 VM_SAFEPARMCOUNT(2, VM_getsurfacenumtriangles);
6520 // return 0 if no such surface
6521 if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6523 PRVM_G_FLOAT(OFS_RETURN) = 0;
6527 PRVM_G_FLOAT(OFS_RETURN) = surface->num_triangles;
6529 //PF_getsurfacetriangle, // #??? vector(entity e, float s, float n) getsurfacetriangle = #???;
6530 void VM_getsurfacetriangle(prvm_prog_t *prog)
6532 const vec3_t d = {-1, -1, -1};
6535 msurface_t *surface;
6537 VM_SAFEPARMCOUNT(3, VM_getsurfacetriangle);
6538 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6539 ed = PRVM_G_EDICT(OFS_PARM0);
6540 if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6542 trinum = (int)PRVM_G_FLOAT(OFS_PARM2);
6543 if (trinum < 0 || trinum >= surface->num_triangles)
6545 // FIXME: implement rotation/scaling
6546 VectorMA(&(model->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[trinum * 3], surface->num_firstvertex, d, PRVM_G_VECTOR(OFS_RETURN));
6554 #define VM_physics_ApplyCmd(ed,f) if (!ed->priv.server->ode_body) VM_physics_newstackfunction(prog, ed, f); else World_Physics_ApplyCmd(ed, f)
6556 static edict_odefunc_t *VM_physics_newstackfunction(prvm_prog_t *prog, prvm_edict_t *ed, edict_odefunc_t *f)
6558 edict_odefunc_t *newfunc, *func;
6560 newfunc = (edict_odefunc_t *)Mem_Alloc(prog->progs_mempool, sizeof(edict_odefunc_t));
6561 memcpy(newfunc, f, sizeof(edict_odefunc_t));
6562 newfunc->next = NULL;
6563 if (!ed->priv.server->ode_func)
6564 ed->priv.server->ode_func = newfunc;
6567 for (func = ed->priv.server->ode_func; func->next; func = func->next);
6568 func->next = newfunc;
6574 // void(entity e, float physics_enabled) physics_enable = #;
6575 void VM_physics_enable(prvm_prog_t *prog)
6581 VM_SAFEPARMCOUNT(2, VM_physics_enable);
6583 ed = PRVM_G_EDICT(OFS_PARM0);
6586 if (developer.integer > 0)
6587 VM_Warning(prog, "VM_physics_enable: null entity!\n");
6590 // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6591 if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6593 VM_Warning(prog, "VM_physics_enable: entity is not MOVETYPE_PHYSICS!\n");
6596 f.type = PRVM_G_FLOAT(OFS_PARM1) == 0 ? ODEFUNC_DISABLE : ODEFUNC_ENABLE;
6597 VM_physics_ApplyCmd(ed, &f);
6601 // void(entity e, vector force, vector relative_ofs) physics_addforce = #;
6602 void VM_physics_addforce(prvm_prog_t *prog)
6608 VM_SAFEPARMCOUNT(3, VM_physics_addforce);
6610 ed = PRVM_G_EDICT(OFS_PARM0);
6613 if (developer.integer > 0)
6614 VM_Warning(prog, "VM_physics_addforce: null entity!\n");
6617 // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6618 if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6620 VM_Warning(prog, "VM_physics_addforce: entity is not MOVETYPE_PHYSICS!\n");
6623 f.type = ODEFUNC_FORCE;
6624 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
6625 VectorCopy(PRVM_G_VECTOR(OFS_PARM2), f.v2);
6626 VM_physics_ApplyCmd(ed, &f);
6630 // void(entity e, vector torque) physics_addtorque = #;
6631 void VM_physics_addtorque(prvm_prog_t *prog)
6637 VM_SAFEPARMCOUNT(2, VM_physics_addtorque);
6639 ed = PRVM_G_EDICT(OFS_PARM0);
6642 if (developer.integer > 0)
6643 VM_Warning(prog, "VM_physics_addtorque: null entity!\n");
6646 // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6647 if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6649 VM_Warning(prog, "VM_physics_addtorque: entity is not MOVETYPE_PHYSICS!\n");
6652 f.type = ODEFUNC_TORQUE;
6653 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
6654 VM_physics_ApplyCmd(ed, &f);
6658 extern cvar_t prvm_coverage;
6659 void VM_coverage(prvm_prog_t *prog)
6661 VM_SAFEPARMCOUNT(0, VM_coverage);
6662 if (prog->explicit_profile[prog->xstatement]++ == 0 && (prvm_coverage.integer & 2))
6663 PRVM_ExplicitCoverageEvent(prog, prog->xfunction, prog->xstatement);