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"
17 extern cvar_t prvm_backtraceforwarnings;
19 // LordHavoc: changed this to NOT use a return statement, so that it can be used in functions that must return a value
20 void VM_Warning(const char *fmt, ...)
23 char msg[MAX_INPUTLINE];
24 static double recursive = -1;
27 dpvsnprintf(msg,sizeof(msg),fmt,argptr);
32 // TODO: either add a cvar/cmd to control the state dumping or replace some of the calls with Con_Printf [9/13/2006 Black]
33 if(prvm_backtraceforwarnings.integer && recursive != realtime) // NOTE: this compares to the time, just in case if PRVM_PrintState causes a Host_Error and keeps recursive set
42 //============================================================================
45 // TODO DONE: move vm_files and vm_fssearchlist to prvm_prog_t struct
46 // TODO: move vm_files and vm_fssearchlist back [9/13/2006 Black]
47 // TODO: (move vm_files and vm_fssearchlist to prvm_prog_t struct again) [2007-01-23 LordHavoc]
48 // TODO: will this war ever end? [2007-01-23 LordHavoc]
50 void VM_CheckEmptyString (const char *s)
52 if (ISWHITESPACE(s[0]))
53 PRVM_ERROR ("%s: Bad string", PRVM_NAME);
56 void VM_GenerateFrameGroupBlend(framegroupblend_t *framegroupblend, const prvm_edict_t *ed)
59 // self.frame is the interpolation target (new frame)
60 // self.frame1time is the animation base time for the interpolation target
61 // self.frame2 is the interpolation start (previous frame)
62 // self.frame2time is the animation base time for the interpolation start
63 // self.lerpfrac is the interpolation strength for self.frame2
64 // self.lerpfrac3 is the interpolation strength for self.frame3
65 // self.lerpfrac4 is the interpolation strength for self.frame4
66 // pitch angle on a player model where the animator set up 5 sets of
67 // animations and the csqc simply lerps between sets)
68 if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame))) framegroupblend[0].frame = (int) val->_float;
69 if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame2))) framegroupblend[1].frame = (int) val->_float;
70 if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame3))) framegroupblend[2].frame = (int) val->_float;
71 if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame4))) framegroupblend[3].frame = (int) val->_float;
72 if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame1time))) framegroupblend[0].start = val->_float;
73 if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame2time))) framegroupblend[1].start = val->_float;
74 if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame3time))) framegroupblend[2].start = val->_float;
75 if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame4time))) framegroupblend[3].start = val->_float;
76 if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.lerpfrac))) framegroupblend[1].lerp = val->_float;
77 if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.lerpfrac3))) framegroupblend[2].lerp = val->_float;
78 if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.lerpfrac4))) framegroupblend[3].lerp = val->_float;
79 // assume that the (missing) lerpfrac1 is whatever remains after lerpfrac2+lerpfrac3+lerpfrac4 are summed
80 framegroupblend[0].lerp = 1 - framegroupblend[1].lerp - framegroupblend[2].lerp - framegroupblend[3].lerp;
83 // LordHavoc: quite tempting to break apart this function to reuse the
84 // duplicated code, but I suspect it is better for performance
86 void VM_FrameBlendFromFrameGroupBlend(frameblend_t *frameblend, const framegroupblend_t *framegroupblend, const dp_model_t *model)
88 int sub2, numframes, f, i, k;
89 int isfirstframegroup = true;
91 double sublerp, lerp, d;
92 const animscene_t *scene;
93 const framegroupblend_t *g;
94 frameblend_t *blend = frameblend;
96 memset(blend, 0, MAX_FRAMEBLENDS * sizeof(*blend));
98 if (!model || !model->surfmesh.isanimated)
104 nolerp = (model->type == mod_sprite) ? !r_lerpsprites.integer : !r_lerpmodels.integer;
105 numframes = model->numframes;
106 for (k = 0, g = framegroupblend;k < MAX_FRAMEGROUPBLENDS;k++, g++)
109 if ((unsigned int)f >= (unsigned int)numframes)
111 Con_DPrintf("VM_FrameBlendFromFrameGroupBlend: no such frame %d in model %s\n", f, model->name);
119 if (isfirstframegroup)
122 isfirstframegroup = false;
127 if (model->animscenes)
129 scene = model->animscenes + f;
130 f = scene->firstframe;
131 if (scene->framecount > 1)
133 // this code path is only used on .zym models and torches
134 sublerp = scene->framerate * (cl.time - g->start);
135 f = (int) floor(sublerp);
138 if (sublerp < (1.0 / 65536.0f))
140 if (sublerp > (65535.0f / 65536.0f))
146 f = (f % scene->framecount);
147 sub2 = (sub2 % scene->framecount);
149 f = bound(0, f, (scene->framecount - 1)) + scene->firstframe;
150 sub2 = bound(0, sub2, (scene->framecount - 1)) + scene->firstframe;
152 // two framelerps produced from one animation
155 for (i = 0;i < MAX_FRAMEBLENDS;i++)
157 if (blend[i].lerp <= 0 || blend[i].subframe == sub2)
159 blend[i].subframe = sub2;
165 d = (1 - sublerp) * lerp;
170 for (i = 0;i < MAX_FRAMEBLENDS;i++)
172 if (blend[i].lerp <= 0 || blend[i].subframe == f)
174 blend[i].subframe = f;
183 void VM_UpdateEdictSkeleton(prvm_edict_t *ed, const dp_model_t *edmodel, const frameblend_t *frameblend)
185 if (ed->priv.server->skeleton.model != edmodel)
187 VM_RemoveEdictSkeleton(ed);
188 ed->priv.server->skeleton.model = edmodel;
190 if (!ed->priv.server->skeleton.model || !ed->priv.server->skeleton.model->num_bones)
192 if(ed->priv.server->skeleton.relativetransforms)
193 Mem_Free(ed->priv.server->skeleton.relativetransforms);
194 ed->priv.server->skeleton.relativetransforms = NULL;
199 int skeletonindex = -1;
200 skeleton_t *skeleton;
202 if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.skeletonindex))) skeletonindex = (int)val->_float - 1;
203 if (skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones)
205 // custom skeleton controlled by the game (FTE_CSQC_SKELETONOBJECTS)
206 if (!ed->priv.server->skeleton.relativetransforms)
207 ed->priv.server->skeleton.relativetransforms = (matrix4x4_t *)Mem_Alloc(prog->progs_mempool, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
208 memcpy(ed->priv.server->skeleton.relativetransforms, skeleton->relativetransforms, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
212 if(ed->priv.server->skeleton.relativetransforms)
213 Mem_Free(ed->priv.server->skeleton.relativetransforms);
214 ed->priv.server->skeleton.relativetransforms = NULL;
219 void VM_RemoveEdictSkeleton(prvm_edict_t *ed)
221 if (ed->priv.server->skeleton.relativetransforms)
222 Mem_Free(ed->priv.server->skeleton.relativetransforms);
223 memset(&ed->priv.server->skeleton, 0, sizeof(ed->priv.server->skeleton));
229 //============================================================================
232 void VM_VarString(int first, char *out, int outlength)
238 outend = out + outlength - 1;
239 for (i = first;i < prog->argc && out < outend;i++)
241 s = PRVM_G_STRING((OFS_PARM0+i*3));
242 while (out < outend && *s)
252 returns true if the extension is supported by the server
254 checkextension(extensionname)
258 // kind of helper function
259 static qboolean checkextension(const char *name)
262 const char *e, *start;
263 len = (int)strlen(name);
265 for (e = prog->extensionstring;*e;e++)
272 while (*e && *e != ' ')
274 if ((e - start) == len && !strncasecmp(start, name, len))
276 // special sheck for ODE
277 if (!strncasecmp("DP_PHYSICS_ODE", name, 14))
280 return ode_dll ? true : false;
291 void VM_checkextension (void)
293 VM_SAFEPARMCOUNT(1,VM_checkextension);
295 PRVM_G_FLOAT(OFS_RETURN) = checkextension(PRVM_G_STRING(OFS_PARM0));
302 This is a TERMINAL error, which will kill off the entire prog.
311 char string[VM_STRINGTEMP_LENGTH];
313 VM_VarString(0, string, sizeof(string));
314 Con_Printf("======%s ERROR in %s:\n%s\n", PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string);
315 if (prog->globaloffsets.self >= 0)
317 ed = PRVM_PROG_TO_EDICT(PRVM_GLOBALFIELDVALUE(prog->globaloffsets.self)->edict);
318 PRVM_ED_Print(ed, NULL);
321 PRVM_ERROR ("%s: Program error in function %s:\n%s\nTip: read above for entity information\n", PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string);
328 Dumps out self, then an error message. The program is aborted and self is
329 removed, but the level can continue.
334 void VM_objerror (void)
337 char string[VM_STRINGTEMP_LENGTH];
339 VM_VarString(0, string, sizeof(string));
340 Con_Printf("======OBJECT ERROR======\n"); // , PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string); // or include them? FIXME
341 if (prog->globaloffsets.self >= 0)
343 ed = PRVM_PROG_TO_EDICT(PRVM_GLOBALFIELDVALUE(prog->globaloffsets.self)->edict);
344 PRVM_ED_Print(ed, NULL);
349 // objerror has to display the object fields -> else call
350 PRVM_ERROR ("VM_objecterror: self not defined !");
351 Con_Printf("%s OBJECT ERROR in %s:\n%s\nTip: read above for entity information\n", PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string);
365 char string[VM_STRINGTEMP_LENGTH];
367 VM_VarString(0, string, sizeof(string));
375 broadcast print to everyone on server
380 void VM_bprint (void)
382 char string[VM_STRINGTEMP_LENGTH];
386 VM_Warning("VM_bprint: game is not server(%s) !\n", PRVM_NAME);
390 VM_VarString(0, string, sizeof(string));
391 SV_BroadcastPrint(string);
396 VM_sprint (menu & client but only if server.active == true)
398 single print to a specific client
400 sprint(float clientnum,...[string])
403 void VM_sprint (void)
407 char string[VM_STRINGTEMP_LENGTH];
409 VM_SAFEPARMCOUNTRANGE(1, 8, VM_sprint);
411 //find client for this entity
412 clientnum = (int)PRVM_G_FLOAT(OFS_PARM0);
413 if (!sv.active || clientnum < 0 || clientnum >= svs.maxclients || !svs.clients[clientnum].active)
415 VM_Warning("VM_sprint: %s: invalid client or server is not active !\n", PRVM_NAME);
419 client = svs.clients + clientnum;
420 if (!client->netconnection)
423 VM_VarString(1, string, sizeof(string));
424 MSG_WriteChar(&client->netconnection->message,svc_print);
425 MSG_WriteString(&client->netconnection->message, string);
432 single print to the screen
437 void VM_centerprint (void)
439 char string[VM_STRINGTEMP_LENGTH];
441 VM_SAFEPARMCOUNTRANGE(1, 8, VM_centerprint);
442 VM_VarString(0, string, sizeof(string));
443 SCR_CenterPrint(string);
450 vector normalize(vector)
453 void VM_normalize (void)
459 VM_SAFEPARMCOUNT(1,VM_normalize);
461 value1 = PRVM_G_VECTOR(OFS_PARM0);
463 f = VectorLength2(value1);
467 VectorScale(value1, f, newvalue);
470 VectorClear(newvalue);
472 VectorCopy (newvalue, PRVM_G_VECTOR(OFS_RETURN));
484 VM_SAFEPARMCOUNT(1,VM_vlen);
485 PRVM_G_FLOAT(OFS_RETURN) = VectorLength(PRVM_G_VECTOR(OFS_PARM0));
492 float vectoyaw(vector)
495 void VM_vectoyaw (void)
500 VM_SAFEPARMCOUNT(1,VM_vectoyaw);
502 value1 = PRVM_G_VECTOR(OFS_PARM0);
504 if (value1[1] == 0 && value1[0] == 0)
508 yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI);
513 PRVM_G_FLOAT(OFS_RETURN) = yaw;
521 vector vectoangles(vector[, vector])
524 void VM_vectoangles (void)
526 VM_SAFEPARMCOUNTRANGE(1, 2,VM_vectoangles);
528 AnglesFromVectors(PRVM_G_VECTOR(OFS_RETURN), PRVM_G_VECTOR(OFS_PARM0), prog->argc >= 2 ? PRVM_G_VECTOR(OFS_PARM1) : NULL, true);
535 Returns a number from 0<= num < 1
540 void VM_random (void)
542 VM_SAFEPARMCOUNT(0,VM_random);
544 PRVM_G_FLOAT(OFS_RETURN) = lhrandom(0, 1);
551 localsound(string sample)
554 void VM_localsound(void)
558 VM_SAFEPARMCOUNT(1,VM_localsound);
560 s = PRVM_G_STRING(OFS_PARM0);
562 if(!S_LocalSound (s))
564 PRVM_G_FLOAT(OFS_RETURN) = -4;
565 VM_Warning("VM_localsound: Failed to play %s for %s !\n", s, PRVM_NAME);
569 PRVM_G_FLOAT(OFS_RETURN) = 1;
581 PRVM_ERROR ("%s: break statement", PRVM_NAME);
584 //============================================================================
590 Sends text over to the client's execution buffer
592 [localcmd (string, ...) or]
596 void VM_localcmd (void)
598 char string[VM_STRINGTEMP_LENGTH];
599 VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd);
600 VM_VarString(0, string, sizeof(string));
601 Cbuf_AddText(string);
604 static qboolean PRVM_Cvar_ReadOk(const char *string)
607 cvar = Cvar_FindVar(string);
608 return ((cvar) && ((cvar->flags & CVAR_PRIVATE) == 0));
620 char string[VM_STRINGTEMP_LENGTH];
621 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
622 VM_VarString(0, string, sizeof(string));
623 VM_CheckEmptyString(string);
624 PRVM_G_FLOAT(OFS_RETURN) = PRVM_Cvar_ReadOk(string) ? Cvar_VariableValue(string) : 0;
631 float cvar_type (string)
632 float CVAR_TYPEFLAG_EXISTS = 1;
633 float CVAR_TYPEFLAG_SAVED = 2;
634 float CVAR_TYPEFLAG_PRIVATE = 4;
635 float CVAR_TYPEFLAG_ENGINE = 8;
636 float CVAR_TYPEFLAG_HASDESCRIPTION = 16;
637 float CVAR_TYPEFLAG_READONLY = 32;
640 void VM_cvar_type (void)
642 char string[VM_STRINGTEMP_LENGTH];
646 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
647 VM_VarString(0, string, sizeof(string));
648 VM_CheckEmptyString(string);
649 cvar = Cvar_FindVar(string);
654 PRVM_G_FLOAT(OFS_RETURN) = 0;
655 return; // CVAR_TYPE_NONE
658 ret = 1; // CVAR_EXISTS
659 if(cvar->flags & CVAR_SAVE)
660 ret |= 2; // CVAR_TYPE_SAVED
661 if(cvar->flags & CVAR_PRIVATE)
662 ret |= 4; // CVAR_TYPE_PRIVATE
663 if(!(cvar->flags & CVAR_ALLOCATED))
664 ret |= 8; // CVAR_TYPE_ENGINE
665 if(cvar->description != cvar_dummy_description)
666 ret |= 16; // CVAR_TYPE_HASDESCRIPTION
667 if(cvar->flags & CVAR_READONLY)
668 ret |= 32; // CVAR_TYPE_READONLY
670 PRVM_G_FLOAT(OFS_RETURN) = ret;
677 const string VM_cvar_string (string, ...)
680 void VM_cvar_string(void)
682 char string[VM_STRINGTEMP_LENGTH];
683 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_string);
684 VM_VarString(0, string, sizeof(string));
685 VM_CheckEmptyString(string);
686 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(PRVM_Cvar_ReadOk(string) ? Cvar_VariableString(string) : "");
691 ========================
694 const string VM_cvar_defstring (string, ...)
695 ========================
697 void VM_cvar_defstring (void)
699 char string[VM_STRINGTEMP_LENGTH];
700 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_defstring);
701 VM_VarString(0, string, sizeof(string));
702 VM_CheckEmptyString(string);
703 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Cvar_VariableDefString(string));
707 ========================
710 const string VM_cvar_description (string, ...)
711 ========================
713 void VM_cvar_description (void)
715 char string[VM_STRINGTEMP_LENGTH];
716 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_description);
717 VM_VarString(0, string, sizeof(string));
718 VM_CheckEmptyString(string);
719 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Cvar_VariableDescription(string));
725 void cvar_set (string,string, ...)
728 void VM_cvar_set (void)
731 char string[VM_STRINGTEMP_LENGTH];
732 VM_SAFEPARMCOUNTRANGE(2,8,VM_cvar_set);
733 VM_VarString(1, string, sizeof(string));
734 name = PRVM_G_STRING(OFS_PARM0);
735 VM_CheckEmptyString(name);
736 Cvar_Set(name, string);
746 void VM_dprint (void)
748 char string[VM_STRINGTEMP_LENGTH];
749 VM_SAFEPARMCOUNTRANGE(1, 8, VM_dprint);
750 VM_VarString(0, string, sizeof(string));
752 Con_DPrintf("%s", string);
754 Con_DPrintf("%s: %s", PRVM_NAME, string);
771 VM_SAFEPARMCOUNT(1, VM_ftos);
773 v = PRVM_G_FLOAT(OFS_PARM0);
775 if ((float)((int)v) == v)
776 dpsnprintf(s, sizeof(s), "%i", (int)v);
778 dpsnprintf(s, sizeof(s), "%f", v);
779 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
794 VM_SAFEPARMCOUNT(1,VM_fabs);
796 v = PRVM_G_FLOAT(OFS_PARM0);
797 PRVM_G_FLOAT(OFS_RETURN) = fabs(v);
812 VM_SAFEPARMCOUNT(1,VM_vtos);
814 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]);
815 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
830 VM_SAFEPARMCOUNT(1, VM_etos);
832 dpsnprintf (s, sizeof(s), "entity %i", PRVM_G_EDICTNUM(OFS_PARM0));
833 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
840 float stof(...[string])
845 char string[VM_STRINGTEMP_LENGTH];
846 VM_SAFEPARMCOUNTRANGE(1, 8, VM_stof);
847 VM_VarString(0, string, sizeof(string));
848 PRVM_G_FLOAT(OFS_RETURN) = atof(string);
852 ========================
856 ========================
860 VM_SAFEPARMCOUNT(1, VM_itof);
861 PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
865 ========================
868 entity ftoe(float num)
869 ========================
874 VM_SAFEPARMCOUNT(1, VM_ftoe);
876 ent = (int)PRVM_G_FLOAT(OFS_PARM0);
877 if (ent < 0 || ent >= prog->max_edicts || PRVM_PROG_TO_EDICT(ent)->priv.required->free)
878 ent = 0; // return world instead of a free or invalid entity
880 PRVM_G_INT(OFS_RETURN) = ent;
884 ========================
887 float etof(entity ent)
888 ========================
892 VM_SAFEPARMCOUNT(1, VM_etof);
893 PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICTNUM(OFS_PARM0);
900 string strftime(float uselocaltime, string[, string ...])
903 void VM_strftime(void)
912 char fmt[VM_STRINGTEMP_LENGTH];
913 char result[VM_STRINGTEMP_LENGTH];
914 VM_SAFEPARMCOUNTRANGE(2, 8, VM_strftime);
915 VM_VarString(1, fmt, sizeof(fmt));
918 if (PRVM_G_FLOAT(OFS_PARM0))
919 tmresult = localtime_s(&tm, &t);
921 tmresult = gmtime_s(&tm, &t);
924 if (PRVM_G_FLOAT(OFS_PARM0))
931 PRVM_G_INT(OFS_RETURN) = 0;
935 strftime(result, sizeof(result), fmt, &tm);
937 strftime(result, sizeof(result), fmt, tm);
939 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(result);
953 VM_SAFEPARMCOUNT(0, VM_spawn);
954 prog->xfunction->builtinsprofile += 20;
955 ed = PRVM_ED_Alloc();
967 void VM_remove (void)
970 prog->xfunction->builtinsprofile += 20;
972 VM_SAFEPARMCOUNT(1, VM_remove);
974 ed = PRVM_G_EDICT(OFS_PARM0);
975 if( PRVM_NUM_FOR_EDICT(ed) <= prog->reserved_edicts )
977 if (developer.integer > 0)
978 VM_Warning( "VM_remove: tried to remove the null entity or a reserved entity!\n" );
980 else if( ed->priv.required->free )
982 if (developer.integer > 0)
983 VM_Warning( "VM_remove: tried to remove an already freed entity!\n" );
993 entity find(entity start, .string field, string match)
1004 VM_SAFEPARMCOUNT(3,VM_find);
1006 e = PRVM_G_EDICTNUM(OFS_PARM0);
1007 f = PRVM_G_INT(OFS_PARM1);
1008 s = PRVM_G_STRING(OFS_PARM2);
1010 // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1011 // expects it to find all the monsters, so we must be careful to support
1014 for (e++ ; e < prog->num_edicts ; e++)
1016 prog->xfunction->builtinsprofile++;
1017 ed = PRVM_EDICT_NUM(e);
1018 if (ed->priv.required->free)
1020 t = PRVM_E_STRING(ed,f);
1025 VM_RETURN_EDICT(ed);
1030 VM_RETURN_EDICT(prog->edicts);
1037 entity findfloat(entity start, .float field, float match)
1038 entity findentity(entity start, .entity field, entity match)
1041 // LordHavoc: added this for searching float, int, and entity reference fields
1042 void VM_findfloat (void)
1049 VM_SAFEPARMCOUNT(3,VM_findfloat);
1051 e = PRVM_G_EDICTNUM(OFS_PARM0);
1052 f = PRVM_G_INT(OFS_PARM1);
1053 s = PRVM_G_FLOAT(OFS_PARM2);
1055 for (e++ ; e < prog->num_edicts ; e++)
1057 prog->xfunction->builtinsprofile++;
1058 ed = PRVM_EDICT_NUM(e);
1059 if (ed->priv.required->free)
1061 if (PRVM_E_FLOAT(ed,f) == s)
1063 VM_RETURN_EDICT(ed);
1068 VM_RETURN_EDICT(prog->edicts);
1075 entity findchain(.string field, string match)
1078 // chained search for strings in entity fields
1079 // entity(.string field, string match) findchain = #402;
1080 void VM_findchain (void)
1085 prvm_edict_t *ent, *chain;
1088 VM_SAFEPARMCOUNTRANGE(2,3,VM_findchain);
1091 chainfield = PRVM_G_INT(OFS_PARM2);
1093 chainfield = prog->fieldoffsets.chain;
1095 PRVM_ERROR("VM_findchain: %s doesnt have the specified chain field !", PRVM_NAME);
1097 chain = prog->edicts;
1099 f = PRVM_G_INT(OFS_PARM0);
1100 s = PRVM_G_STRING(OFS_PARM1);
1102 // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1103 // expects it to find all the monsters, so we must be careful to support
1106 ent = PRVM_NEXT_EDICT(prog->edicts);
1107 for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1109 prog->xfunction->builtinsprofile++;
1110 if (ent->priv.required->free)
1112 t = PRVM_E_STRING(ent,f);
1118 PRVM_EDICTFIELDVALUE(ent,chainfield)->edict = PRVM_NUM_FOR_EDICT(chain);
1122 VM_RETURN_EDICT(chain);
1129 entity findchainfloat(.string field, float match)
1130 entity findchainentity(.string field, entity match)
1133 // LordHavoc: chained search for float, int, and entity reference fields
1134 // entity(.string field, float match) findchainfloat = #403;
1135 void VM_findchainfloat (void)
1140 prvm_edict_t *ent, *chain;
1143 VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainfloat);
1146 chainfield = PRVM_G_INT(OFS_PARM2);
1148 chainfield = prog->fieldoffsets.chain;
1150 PRVM_ERROR("VM_findchain: %s doesnt have the specified chain field !", PRVM_NAME);
1152 chain = (prvm_edict_t *)prog->edicts;
1154 f = PRVM_G_INT(OFS_PARM0);
1155 s = PRVM_G_FLOAT(OFS_PARM1);
1157 ent = PRVM_NEXT_EDICT(prog->edicts);
1158 for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1160 prog->xfunction->builtinsprofile++;
1161 if (ent->priv.required->free)
1163 if (PRVM_E_FLOAT(ent,f) != s)
1166 PRVM_EDICTFIELDVALUE(ent,chainfield)->edict = PRVM_EDICT_TO_PROG(chain);
1170 VM_RETURN_EDICT(chain);
1174 ========================
1177 entity findflags(entity start, .float field, float match)
1178 ========================
1180 // LordHavoc: search for flags in float fields
1181 void VM_findflags (void)
1188 VM_SAFEPARMCOUNT(3, VM_findflags);
1191 e = PRVM_G_EDICTNUM(OFS_PARM0);
1192 f = PRVM_G_INT(OFS_PARM1);
1193 s = (int)PRVM_G_FLOAT(OFS_PARM2);
1195 for (e++ ; e < prog->num_edicts ; e++)
1197 prog->xfunction->builtinsprofile++;
1198 ed = PRVM_EDICT_NUM(e);
1199 if (ed->priv.required->free)
1201 if (!PRVM_E_FLOAT(ed,f))
1203 if ((int)PRVM_E_FLOAT(ed,f) & s)
1205 VM_RETURN_EDICT(ed);
1210 VM_RETURN_EDICT(prog->edicts);
1214 ========================
1217 entity findchainflags(.float field, float match)
1218 ========================
1220 // LordHavoc: chained search for flags in float fields
1221 void VM_findchainflags (void)
1226 prvm_edict_t *ent, *chain;
1229 VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainflags);
1232 chainfield = PRVM_G_INT(OFS_PARM2);
1234 chainfield = prog->fieldoffsets.chain;
1236 PRVM_ERROR("VM_findchain: %s doesnt have the specified chain field !", PRVM_NAME);
1238 chain = (prvm_edict_t *)prog->edicts;
1240 f = PRVM_G_INT(OFS_PARM0);
1241 s = (int)PRVM_G_FLOAT(OFS_PARM1);
1243 ent = PRVM_NEXT_EDICT(prog->edicts);
1244 for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1246 prog->xfunction->builtinsprofile++;
1247 if (ent->priv.required->free)
1249 if (!PRVM_E_FLOAT(ent,f))
1251 if (!((int)PRVM_E_FLOAT(ent,f) & s))
1254 PRVM_EDICTFIELDVALUE(ent,chainfield)->edict = PRVM_EDICT_TO_PROG(chain);
1258 VM_RETURN_EDICT(chain);
1265 string precache_sound (string sample)
1268 void VM_precache_sound (void)
1272 VM_SAFEPARMCOUNT(1, VM_precache_sound);
1274 s = PRVM_G_STRING(OFS_PARM0);
1275 PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1276 //VM_CheckEmptyString(s);
1278 if(snd_initialized.integer && !S_PrecacheSound(s, true, true))
1280 VM_Warning("VM_precache_sound: Failed to load %s for %s\n", s, PRVM_NAME);
1289 returns the same string as output
1291 does nothing, only used by qcc to build .pak archives
1294 void VM_precache_file (void)
1296 VM_SAFEPARMCOUNT(1,VM_precache_file);
1297 // precache_file is only used to copy files with qcc, it does nothing
1298 PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1308 void VM_coredump (void)
1310 VM_SAFEPARMCOUNT(0,VM_coredump);
1312 Cbuf_AddText("prvm_edicts ");
1313 Cbuf_AddText(PRVM_NAME);
1324 void PRVM_StackTrace(void);
1325 void VM_stackdump (void)
1327 VM_SAFEPARMCOUNT(0, VM_stackdump);
1342 VM_SAFEPARMCOUNT(0, VM_crash);
1344 PRVM_ERROR("Crash called by %s",PRVM_NAME);
1354 void VM_traceon (void)
1356 VM_SAFEPARMCOUNT(0,VM_traceon);
1368 void VM_traceoff (void)
1370 VM_SAFEPARMCOUNT(0,VM_traceoff);
1372 prog->trace = false;
1382 void VM_eprint (void)
1384 VM_SAFEPARMCOUNT(1,VM_eprint);
1386 PRVM_ED_PrintNum (PRVM_G_EDICTNUM(OFS_PARM0), NULL);
1399 VM_SAFEPARMCOUNT(1,VM_rint);
1401 f = PRVM_G_FLOAT(OFS_PARM0);
1403 PRVM_G_FLOAT(OFS_RETURN) = floor(f + 0.5);
1405 PRVM_G_FLOAT(OFS_RETURN) = ceil(f - 0.5);
1415 void VM_floor (void)
1417 VM_SAFEPARMCOUNT(1,VM_floor);
1419 PRVM_G_FLOAT(OFS_RETURN) = floor(PRVM_G_FLOAT(OFS_PARM0));
1431 VM_SAFEPARMCOUNT(1,VM_ceil);
1433 PRVM_G_FLOAT(OFS_RETURN) = ceil(PRVM_G_FLOAT(OFS_PARM0));
1441 entity nextent(entity)
1444 void VM_nextent (void)
1449 VM_SAFEPARMCOUNT(1, VM_nextent);
1451 i = PRVM_G_EDICTNUM(OFS_PARM0);
1454 prog->xfunction->builtinsprofile++;
1456 if (i == prog->num_edicts)
1458 VM_RETURN_EDICT(prog->edicts);
1461 ent = PRVM_EDICT_NUM(i);
1462 if (!ent->priv.required->free)
1464 VM_RETURN_EDICT(ent);
1470 //=============================================================================
1477 changelevel(string map)
1480 void VM_changelevel (void)
1482 VM_SAFEPARMCOUNT(1, VM_changelevel);
1486 VM_Warning("VM_changelevel: game is not server (%s)\n", PRVM_NAME);
1490 // make sure we don't issue two changelevels
1491 if (svs.changelevel_issued)
1493 svs.changelevel_issued = true;
1495 Cbuf_AddText (va("changelevel %s\n",PRVM_G_STRING(OFS_PARM0)));
1507 VM_SAFEPARMCOUNT(1,VM_sin);
1508 PRVM_G_FLOAT(OFS_RETURN) = sin(PRVM_G_FLOAT(OFS_PARM0));
1519 VM_SAFEPARMCOUNT(1,VM_cos);
1520 PRVM_G_FLOAT(OFS_RETURN) = cos(PRVM_G_FLOAT(OFS_PARM0));
1532 VM_SAFEPARMCOUNT(1,VM_sqrt);
1533 PRVM_G_FLOAT(OFS_RETURN) = sqrt(PRVM_G_FLOAT(OFS_PARM0));
1545 VM_SAFEPARMCOUNT(1,VM_asin);
1546 PRVM_G_FLOAT(OFS_RETURN) = asin(PRVM_G_FLOAT(OFS_PARM0));
1557 VM_SAFEPARMCOUNT(1,VM_acos);
1558 PRVM_G_FLOAT(OFS_RETURN) = acos(PRVM_G_FLOAT(OFS_PARM0));
1569 VM_SAFEPARMCOUNT(1,VM_atan);
1570 PRVM_G_FLOAT(OFS_RETURN) = atan(PRVM_G_FLOAT(OFS_PARM0));
1576 float atan2(float,float)
1579 void VM_atan2 (void)
1581 VM_SAFEPARMCOUNT(2,VM_atan2);
1582 PRVM_G_FLOAT(OFS_RETURN) = atan2(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1593 VM_SAFEPARMCOUNT(1,VM_tan);
1594 PRVM_G_FLOAT(OFS_RETURN) = tan(PRVM_G_FLOAT(OFS_PARM0));
1601 Returns a vector of length < 1 and > 0
1606 void VM_randomvec (void)
1611 VM_SAFEPARMCOUNT(0, VM_randomvec);
1616 temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1617 temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1618 temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1620 while (DotProduct(temp, temp) >= 1);
1621 VectorCopy (temp, PRVM_G_VECTOR(OFS_RETURN));
1624 temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1625 temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1626 temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1627 // length returned always > 0
1628 length = (rand()&32766 + 1) * (1.0 / 32767.0) / VectorLength(temp);
1629 VectorScale(temp,length, temp);*/
1630 //VectorCopy(temp, PRVM_G_VECTOR(OFS_RETURN));
1633 //=============================================================================
1639 float registercvar (string name, string value[, float flags])
1642 void VM_registercvar (void)
1644 const char *name, *value;
1647 VM_SAFEPARMCOUNTRANGE(2, 3, VM_registercvar);
1649 name = PRVM_G_STRING(OFS_PARM0);
1650 value = PRVM_G_STRING(OFS_PARM1);
1651 flags = prog->argc >= 3 ? (int)PRVM_G_FLOAT(OFS_PARM2) : 0;
1652 PRVM_G_FLOAT(OFS_RETURN) = 0;
1654 if(flags > CVAR_MAXFLAGSVAL)
1657 // first check to see if it has already been defined
1658 if (Cvar_FindVar (name))
1661 // check for overlap with a command
1662 if (Cmd_Exists (name))
1664 VM_Warning("VM_registercvar: %s is a command\n", name);
1668 Cvar_Get(name, value, flags, NULL);
1670 PRVM_G_FLOAT(OFS_RETURN) = 1; // success
1678 returns the minimum of two supplied floats
1680 float min(float a, float b, ...[float])
1685 VM_SAFEPARMCOUNTRANGE(2, 8, VM_min);
1686 // LordHavoc: 3+ argument enhancement suggested by FrikaC
1687 if (prog->argc >= 3)
1690 float f = PRVM_G_FLOAT(OFS_PARM0);
1691 for (i = 1;i < prog->argc;i++)
1692 if (f > PRVM_G_FLOAT((OFS_PARM0+i*3)))
1693 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1694 PRVM_G_FLOAT(OFS_RETURN) = f;
1697 PRVM_G_FLOAT(OFS_RETURN) = min(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1704 returns the maximum of two supplied floats
1706 float max(float a, float b, ...[float])
1711 VM_SAFEPARMCOUNTRANGE(2, 8, VM_max);
1712 // LordHavoc: 3+ argument enhancement suggested by FrikaC
1713 if (prog->argc >= 3)
1716 float f = PRVM_G_FLOAT(OFS_PARM0);
1717 for (i = 1;i < prog->argc;i++)
1718 if (f < PRVM_G_FLOAT((OFS_PARM0+i*3)))
1719 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1720 PRVM_G_FLOAT(OFS_RETURN) = f;
1723 PRVM_G_FLOAT(OFS_RETURN) = max(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1730 returns number bounded by supplied range
1732 float bound(float min, float value, float max)
1735 void VM_bound (void)
1737 VM_SAFEPARMCOUNT(3,VM_bound);
1738 PRVM_G_FLOAT(OFS_RETURN) = bound(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1), PRVM_G_FLOAT(OFS_PARM2));
1745 returns a raised to power b
1747 float pow(float a, float b)
1752 VM_SAFEPARMCOUNT(2,VM_pow);
1753 PRVM_G_FLOAT(OFS_RETURN) = pow(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1758 VM_SAFEPARMCOUNT(1,VM_log);
1759 PRVM_G_FLOAT(OFS_RETURN) = log(PRVM_G_FLOAT(OFS_PARM0));
1762 void VM_Files_Init(void)
1765 for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1766 prog->openfiles[i] = NULL;
1769 void VM_Files_CloseAll(void)
1772 for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1774 if (prog->openfiles[i])
1775 FS_Close(prog->openfiles[i]);
1776 prog->openfiles[i] = NULL;
1780 static qfile_t *VM_GetFileHandle( int index )
1782 if (index < 0 || index >= PRVM_MAX_OPENFILES)
1784 Con_Printf("VM_GetFileHandle: invalid file handle %i used in %s\n", index, PRVM_NAME);
1787 if (prog->openfiles[index] == NULL)
1789 Con_Printf("VM_GetFileHandle: no such file handle %i (or file has been closed) in %s\n", index, PRVM_NAME);
1792 return prog->openfiles[index];
1799 float fopen(string filename, float mode)
1802 // float(string filename, float mode) fopen = #110;
1803 // opens a file inside quake/gamedir/data/ (mode is FILE_READ, FILE_APPEND, or FILE_WRITE),
1804 // returns fhandle >= 0 if successful, or fhandle < 0 if unable to open file for any reason
1808 const char *modestring, *filename;
1810 VM_SAFEPARMCOUNT(2,VM_fopen);
1812 for (filenum = 0;filenum < PRVM_MAX_OPENFILES;filenum++)
1813 if (prog->openfiles[filenum] == NULL)
1815 if (filenum >= PRVM_MAX_OPENFILES)
1817 PRVM_G_FLOAT(OFS_RETURN) = -2;
1818 VM_Warning("VM_fopen: %s ran out of file handles (%i)\n", PRVM_NAME, PRVM_MAX_OPENFILES);
1821 filename = PRVM_G_STRING(OFS_PARM0);
1822 mode = (int)PRVM_G_FLOAT(OFS_PARM1);
1825 case 0: // FILE_READ
1827 prog->openfiles[filenum] = FS_OpenVirtualFile(va("data/%s", filename), false);
1828 if (prog->openfiles[filenum] == NULL)
1829 prog->openfiles[filenum] = FS_OpenVirtualFile(va("%s", filename), false);
1831 case 1: // FILE_APPEND
1833 prog->openfiles[filenum] = FS_OpenRealFile(va("data/%s", filename), modestring, false);
1835 case 2: // FILE_WRITE
1837 prog->openfiles[filenum] = FS_OpenRealFile(va("data/%s", filename), modestring, false);
1840 PRVM_G_FLOAT(OFS_RETURN) = -3;
1841 VM_Warning("VM_fopen: %s: no such mode %i (valid: 0 = read, 1 = append, 2 = write)\n", PRVM_NAME, mode);
1845 if (prog->openfiles[filenum] == NULL)
1847 PRVM_G_FLOAT(OFS_RETURN) = -1;
1848 if (developer_extra.integer)
1849 VM_Warning("VM_fopen: %s: %s mode %s failed\n", PRVM_NAME, filename, modestring);
1853 PRVM_G_FLOAT(OFS_RETURN) = filenum;
1854 if (developer_extra.integer)
1855 Con_DPrintf("VM_fopen: %s: %s mode %s opened as #%i\n", PRVM_NAME, filename, modestring, filenum);
1856 prog->openfiles_origin[filenum] = PRVM_AllocationOrigin();
1864 fclose(float fhandle)
1867 //void(float fhandle) fclose = #111; // closes a file
1868 void VM_fclose(void)
1872 VM_SAFEPARMCOUNT(1,VM_fclose);
1874 filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1875 if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1877 VM_Warning("VM_fclose: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1880 if (prog->openfiles[filenum] == NULL)
1882 VM_Warning("VM_fclose: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1885 FS_Close(prog->openfiles[filenum]);
1886 prog->openfiles[filenum] = NULL;
1887 if(prog->openfiles_origin[filenum])
1888 PRVM_Free((char *)prog->openfiles_origin[filenum]);
1889 if (developer_extra.integer)
1890 Con_DPrintf("VM_fclose: %s: #%i closed\n", PRVM_NAME, filenum);
1897 string fgets(float fhandle)
1900 //string(float fhandle) fgets = #112; // reads a line of text from the file and returns as a tempstring
1904 char string[VM_STRINGTEMP_LENGTH];
1907 VM_SAFEPARMCOUNT(1,VM_fgets);
1909 // set the return value regardless of any possible errors
1910 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
1912 filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1913 if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1915 VM_Warning("VM_fgets: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1918 if (prog->openfiles[filenum] == NULL)
1920 VM_Warning("VM_fgets: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1926 c = FS_Getc(prog->openfiles[filenum]);
1927 if (c == '\r' || c == '\n' || c < 0)
1929 if (end < VM_STRINGTEMP_LENGTH - 1)
1933 // remove \n following \r
1936 c = FS_Getc(prog->openfiles[filenum]);
1938 FS_UnGetc(prog->openfiles[filenum], (unsigned char)c);
1940 if (developer_extra.integer)
1941 Con_DPrintf("fgets: %s: %s\n", PRVM_NAME, string);
1943 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
1950 fputs(float fhandle, string s)
1953 //void(float fhandle, string s) fputs = #113; // writes a line of text to the end of the file
1957 char string[VM_STRINGTEMP_LENGTH];
1960 VM_SAFEPARMCOUNT(2,VM_fputs);
1962 filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1963 if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1965 VM_Warning("VM_fputs: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1968 if (prog->openfiles[filenum] == NULL)
1970 VM_Warning("VM_fputs: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1973 VM_VarString(1, string, sizeof(string));
1974 if ((stringlength = (int)strlen(string)))
1975 FS_Write(prog->openfiles[filenum], string, stringlength);
1976 if (developer_extra.integer)
1977 Con_DPrintf("fputs: %s: %s\n", PRVM_NAME, string);
1984 writetofile(float fhandle, entity ent)
1987 void VM_writetofile(void)
1992 VM_SAFEPARMCOUNT(2, VM_writetofile);
1994 file = VM_GetFileHandle( (int)PRVM_G_FLOAT(OFS_PARM0) );
1997 VM_Warning("VM_writetofile: invalid or closed file handle\n");
2001 ent = PRVM_G_EDICT(OFS_PARM1);
2002 if(ent->priv.required->free)
2004 VM_Warning("VM_writetofile: %s: entity %i is free !\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2008 PRVM_ED_Write (file, ent);
2011 // KrimZon - DP_QC_ENTITYDATA
2016 float() numentityfields
2017 Return the number of entity fields - NOT offsets
2020 void VM_numentityfields(void)
2022 PRVM_G_FLOAT(OFS_RETURN) = prog->progs->numfielddefs;
2025 // KrimZon - DP_QC_ENTITYDATA
2030 string(float fieldnum) entityfieldname
2031 Return name of the specified field as a string, or empty if the field is invalid (warning)
2034 void VM_entityfieldname(void)
2037 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2039 if (i < 0 || i >= prog->progs->numfielddefs)
2041 VM_Warning("VM_entityfieldname: %s: field index out of bounds\n", PRVM_NAME);
2042 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2046 d = &prog->fielddefs[i];
2047 PRVM_G_INT(OFS_RETURN) = d->s_name; // presuming that s_name points to a string already
2050 // KrimZon - DP_QC_ENTITYDATA
2055 float(float fieldnum) entityfieldtype
2058 void VM_entityfieldtype(void)
2061 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2063 if (i < 0 || i >= prog->progs->numfielddefs)
2065 VM_Warning("VM_entityfieldtype: %s: field index out of bounds\n", PRVM_NAME);
2066 PRVM_G_FLOAT(OFS_RETURN) = -1.0;
2070 d = &prog->fielddefs[i];
2071 PRVM_G_FLOAT(OFS_RETURN) = (float)d->type;
2074 // KrimZon - DP_QC_ENTITYDATA
2077 VM_getentityfieldstring
2079 string(float fieldnum, entity ent) getentityfieldstring
2082 void VM_getentityfieldstring(void)
2084 // put the data into a string
2089 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2091 if (i < 0 || i >= prog->progs->numfielddefs)
2093 VM_Warning("VM_entityfielddata: %s: field index out of bounds\n", PRVM_NAME);
2094 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2098 d = &prog->fielddefs[i];
2101 ent = PRVM_G_EDICT(OFS_PARM1);
2102 if(ent->priv.required->free)
2104 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2105 VM_Warning("VM_entityfielddata: %s: entity %i is free !\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2108 v = (int *)((char *)ent->fields.vp + d->ofs*4);
2110 // if it's 0 or blank, return an empty string
2111 type = d->type & ~DEF_SAVEGLOBAL;
2112 for (j=0 ; j<prvm_type_size[type] ; j++)
2115 if (j == prvm_type_size[type])
2117 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2121 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(PRVM_UglyValueString((etype_t)d->type, (prvm_eval_t *)v));
2124 // KrimZon - DP_QC_ENTITYDATA
2127 VM_putentityfieldstring
2129 float(float fieldnum, entity ent, string s) putentityfieldstring
2132 void VM_putentityfieldstring(void)
2136 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2138 if (i < 0 || i >= prog->progs->numfielddefs)
2140 VM_Warning("VM_entityfielddata: %s: field index out of bounds\n", PRVM_NAME);
2141 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2145 d = &prog->fielddefs[i];
2148 ent = PRVM_G_EDICT(OFS_PARM1);
2149 if(ent->priv.required->free)
2151 VM_Warning("VM_entityfielddata: %s: entity %i is free !\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2152 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2156 // parse the string into the value
2157 PRVM_G_FLOAT(OFS_RETURN) = ( PRVM_ED_ParseEpair(ent, d, PRVM_G_STRING(OFS_PARM2), false) ) ? 1.0f : 0.0f;
2164 float strlen(string s)
2167 //float(string s) strlen = #114; // returns how many characters are in a string
2168 void VM_strlen(void)
2170 VM_SAFEPARMCOUNT(1,VM_strlen);
2172 //PRVM_G_FLOAT(OFS_RETURN) = strlen(PRVM_G_STRING(OFS_PARM0));
2173 PRVM_G_FLOAT(OFS_RETURN) = u8_strlen(PRVM_G_STRING(OFS_PARM0));
2176 // DRESK - Decolorized String
2181 string strdecolorize(string s)
2184 // string (string s) strdecolorize = #472; // returns the passed in string with color codes stripped
2185 void VM_strdecolorize(void)
2187 char szNewString[VM_STRINGTEMP_LENGTH];
2188 const char *szString;
2191 VM_SAFEPARMCOUNT(1,VM_strdecolorize);
2192 szString = PRVM_G_STRING(OFS_PARM0);
2193 COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), TRUE);
2194 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
2197 // DRESK - String Length (not counting color codes)
2202 float strlennocol(string s)
2205 // float(string s) strlennocol = #471; // returns how many characters are in a string not including color codes
2206 // For example, ^2Dresk returns a length of 5
2207 void VM_strlennocol(void)
2209 const char *szString;
2212 VM_SAFEPARMCOUNT(1,VM_strlennocol);
2214 szString = PRVM_G_STRING(OFS_PARM0);
2216 //nCnt = COM_StringLengthNoColors(szString, 0, NULL);
2217 nCnt = u8_COM_StringLengthNoColors(szString, 0, NULL);
2219 PRVM_G_FLOAT(OFS_RETURN) = nCnt;
2222 // DRESK - String to Uppercase and Lowercase
2227 string strtolower(string s)
2230 // string (string s) strtolower = #480; // returns passed in string in lowercase form
2231 void VM_strtolower(void)
2233 char szNewString[VM_STRINGTEMP_LENGTH];
2234 const char *szString;
2237 VM_SAFEPARMCOUNT(1,VM_strtolower);
2238 szString = PRVM_G_STRING(OFS_PARM0);
2240 COM_ToLowerString(szString, szNewString, sizeof(szNewString) );
2242 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
2249 string strtoupper(string s)
2252 // string (string s) strtoupper = #481; // returns passed in string in uppercase form
2253 void VM_strtoupper(void)
2255 char szNewString[VM_STRINGTEMP_LENGTH];
2256 const char *szString;
2259 VM_SAFEPARMCOUNT(1,VM_strtoupper);
2260 szString = PRVM_G_STRING(OFS_PARM0);
2262 COM_ToUpperString(szString, szNewString, sizeof(szNewString) );
2264 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
2271 string strcat(string,string,...[string])
2274 //string(string s1, string s2) strcat = #115;
2275 // concatenates two strings (for example "abc", "def" would return "abcdef")
2276 // and returns as a tempstring
2277 void VM_strcat(void)
2279 char s[VM_STRINGTEMP_LENGTH];
2280 VM_SAFEPARMCOUNTRANGE(1, 8, VM_strcat);
2282 VM_VarString(0, s, sizeof(s));
2283 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
2290 string substring(string s, float start, float length)
2293 // string(string s, float start, float length) substring = #116;
2294 // returns a section of a string as a tempstring
2295 void VM_substring(void)
2298 int u_slength = 0, u_start;
2301 char string[VM_STRINGTEMP_LENGTH];
2303 VM_SAFEPARMCOUNT(3,VM_substring);
2306 s = PRVM_G_STRING(OFS_PARM0);
2307 start = (int)PRVM_G_FLOAT(OFS_PARM1);
2308 length = (int)PRVM_G_FLOAT(OFS_PARM2);
2309 slength = strlen(s);
2311 if (start < 0) // FTE_STRINGS feature
2313 start = bound(0, start, slength);
2315 if (length < 0) // FTE_STRINGS feature
2316 length += slength - start + 1;
2317 maxlen = min((int)sizeof(string) - 1, slength - start);
2318 length = bound(0, length, maxlen);
2320 memcpy(string, s + start, length);
2322 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2325 s = PRVM_G_STRING(OFS_PARM0);
2326 start = (int)PRVM_G_FLOAT(OFS_PARM1);
2327 length = (int)PRVM_G_FLOAT(OFS_PARM2);
2329 if (start < 0) // FTE_STRINGS feature
2331 u_slength = u8_strlen(s);
2333 start = bound(0, start, u_slength);
2336 if (length < 0) // FTE_STRINGS feature
2338 if (!u_slength) // it's not calculated when it's not needed above
2339 u_slength = u8_strlen(s);
2340 length += u_slength - start + 1;
2343 // positive start, positive length
2344 u_start = u8_byteofs(s, start, NULL);
2347 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2350 u_length = u8_bytelen(s + u_start, length);
2351 if (u_length >= sizeof(string)-1)
2352 u_length = sizeof(string)-1;
2354 memcpy(string, s + u_start, u_length);
2355 string[u_length] = 0;
2356 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2363 string(string search, string replace, string subject) strreplace = #484;
2366 // replaces all occurrences of search with replace in the string subject, and returns the result
2367 void VM_strreplace(void)
2370 const char *search, *replace, *subject;
2371 char string[VM_STRINGTEMP_LENGTH];
2372 int search_len, replace_len, subject_len;
2374 VM_SAFEPARMCOUNT(3,VM_strreplace);
2376 search = PRVM_G_STRING(OFS_PARM0);
2377 replace = PRVM_G_STRING(OFS_PARM1);
2378 subject = PRVM_G_STRING(OFS_PARM2);
2380 search_len = (int)strlen(search);
2381 replace_len = (int)strlen(replace);
2382 subject_len = (int)strlen(subject);
2385 for (i = 0; i <= subject_len - search_len; i++)
2387 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2388 if (subject[i+j] != search[j])
2390 if (j == search_len)
2392 // NOTE: if search_len == 0, we always hit THIS case, and never the other
2393 // found it at offset 'i'
2394 for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2395 string[si++] = replace[j];
2398 i += search_len - 1;
2402 // the above would subtract 1 from i... so we
2403 // don't do that, but instead output the next
2405 if (si < (int)sizeof(string) - 1)
2406 string[si++] = subject[i];
2411 // in THIS case, we know search_len > 0, thus i < subject_len
2413 if (si < (int)sizeof(string) - 1)
2414 string[si++] = subject[i];
2417 // remaining chars (these cannot match)
2418 for (; i < subject_len; i++)
2419 if (si < (int)sizeof(string) - 1)
2420 string[si++] = subject[i];
2423 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2430 string(string search, string replace, string subject) strireplace = #485;
2433 // case-insensitive version of strreplace
2434 void VM_strireplace(void)
2437 const char *search, *replace, *subject;
2438 char string[VM_STRINGTEMP_LENGTH];
2439 int search_len, replace_len, subject_len;
2441 VM_SAFEPARMCOUNT(3,VM_strreplace);
2443 search = PRVM_G_STRING(OFS_PARM0);
2444 replace = PRVM_G_STRING(OFS_PARM1);
2445 subject = PRVM_G_STRING(OFS_PARM2);
2447 search_len = (int)strlen(search);
2448 replace_len = (int)strlen(replace);
2449 subject_len = (int)strlen(subject);
2452 for (i = 0; i <= subject_len - search_len; i++)
2454 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2455 if (tolower(subject[i+j]) != tolower(search[j]))
2457 if (j == search_len)
2459 // NOTE: if search_len == 0, we always hit THIS case, and never the other
2460 // found it at offset 'i'
2461 for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2462 string[si++] = replace[j];
2465 i += search_len - 1;
2469 // the above would subtract 1 from i... so we
2470 // don't do that, but instead output the next
2472 if (si < (int)sizeof(string) - 1)
2473 string[si++] = subject[i];
2478 // in THIS case, we know search_len > 0, thus i < subject_len
2480 if (si < (int)sizeof(string) - 1)
2481 string[si++] = subject[i];
2484 // remaining chars (these cannot match)
2485 for (; i < subject_len; i++)
2486 if (si < (int)sizeof(string) - 1)
2487 string[si++] = subject[i];
2490 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2497 vector stov(string s)
2500 //vector(string s) stov = #117; // returns vector value from a string
2503 char string[VM_STRINGTEMP_LENGTH];
2505 VM_SAFEPARMCOUNT(1,VM_stov);
2507 VM_VarString(0, string, sizeof(string));
2508 Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
2515 string strzone(string s)
2518 //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)
2519 void VM_strzone(void)
2522 char string[VM_STRINGTEMP_LENGTH];
2525 VM_SAFEPARMCOUNT(1,VM_strzone);
2527 VM_VarString(0, string, sizeof(string));
2528 alloclen = strlen(string) + 1;
2529 PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(alloclen, &out);
2530 memcpy(out, string, alloclen);
2540 //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!!!)
2541 void VM_strunzone(void)
2543 VM_SAFEPARMCOUNT(1,VM_strunzone);
2544 PRVM_FreeString(PRVM_G_INT(OFS_PARM0));
2549 VM_command (used by client and menu)
2551 clientcommand(float client, string s) (for client and menu)
2554 //void(entity e, string s) clientcommand = #440; // executes a command string as if it came from the specified client
2555 //this function originally written by KrimZon, made shorter by LordHavoc
2556 void VM_clcommand (void)
2558 client_t *temp_client;
2561 VM_SAFEPARMCOUNT(2,VM_clcommand);
2563 i = (int)PRVM_G_FLOAT(OFS_PARM0);
2564 if (!sv.active || i < 0 || i >= svs.maxclients || !svs.clients[i].active)
2566 VM_Warning("VM_clientcommand: %s: invalid client/server is not active !\n", PRVM_NAME);
2570 temp_client = host_client;
2571 host_client = svs.clients + i;
2572 Cmd_ExecuteString (PRVM_G_STRING(OFS_PARM1), src_client);
2573 host_client = temp_client;
2581 float tokenize(string s)
2584 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
2585 //this function originally written by KrimZon, made shorter by LordHavoc
2586 //20040203: rewritten by LordHavoc (no longer uses allocations)
2587 static int num_tokens = 0;
2588 static int tokens[VM_STRINGTEMP_LENGTH / 2];
2589 static int tokens_startpos[VM_STRINGTEMP_LENGTH / 2];
2590 static int tokens_endpos[VM_STRINGTEMP_LENGTH / 2];
2591 static char tokenize_string[VM_STRINGTEMP_LENGTH];
2592 void VM_tokenize (void)
2596 VM_SAFEPARMCOUNT(1,VM_tokenize);
2598 strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2599 p = tokenize_string;
2604 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2607 // skip whitespace here to find token start pos
2608 while(*p && ISWHITESPACE(*p))
2611 tokens_startpos[num_tokens] = p - tokenize_string;
2612 if(!COM_ParseToken_VM_Tokenize(&p, false))
2614 tokens_endpos[num_tokens] = p - tokenize_string;
2615 tokens[num_tokens] = PRVM_SetTempString(com_token);
2619 PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2622 //float(string s) tokenize = #514; // takes apart a string into individal words (access them with argv), returns how many
2623 void VM_tokenize_console (void)
2627 VM_SAFEPARMCOUNT(1,VM_tokenize);
2629 strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2630 p = tokenize_string;
2635 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2638 // skip whitespace here to find token start pos
2639 while(*p && ISWHITESPACE(*p))
2642 tokens_startpos[num_tokens] = p - tokenize_string;
2643 if(!COM_ParseToken_Console(&p))
2645 tokens_endpos[num_tokens] = p - tokenize_string;
2646 tokens[num_tokens] = PRVM_SetTempString(com_token);
2650 PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2655 VM_tokenizebyseparator
2657 float tokenizebyseparator(string s, string separator1, ...)
2660 //float(string s, string separator1, ...) tokenizebyseparator = #479; // takes apart a string into individal words (access them with argv), returns how many
2661 //this function returns the token preceding each instance of a separator (of
2662 //which there can be multiple), and the text following the last separator
2663 //useful for parsing certain kinds of data like IP addresses
2665 //numnumbers = tokenizebyseparator("10.1.2.3", ".");
2666 //returns 4 and the tokens "10" "1" "2" "3".
2667 void VM_tokenizebyseparator (void)
2671 int separatorlen[7];
2672 const char *separators[7];
2675 char tokentext[MAX_INPUTLINE];
2677 VM_SAFEPARMCOUNTRANGE(2, 8,VM_tokenizebyseparator);
2679 strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2680 p = tokenize_string;
2683 for (j = 1;j < prog->argc;j++)
2685 // skip any blank separator strings
2686 const char *s = PRVM_G_STRING(OFS_PARM0+j*3);
2689 separators[numseparators] = s;
2690 separatorlen[numseparators] = strlen(s);
2697 while (num_tokens < (int)(sizeof(tokens)/sizeof(tokens[0])))
2699 token = tokentext + j;
2700 tokens_startpos[num_tokens] = p - tokenize_string;
2704 for (k = 0;k < numseparators;k++)
2706 if (!strncmp(p, separators[k], separatorlen[k]))
2708 p += separatorlen[k];
2712 if (k < numseparators)
2714 if (j < (int)sizeof(tokentext)-1)
2715 tokentext[j++] = *p;
2719 tokens_endpos[num_tokens] = p0 - tokenize_string;
2720 if (j >= (int)sizeof(tokentext))
2723 tokens[num_tokens++] = PRVM_SetTempString(token);
2728 PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2731 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
2732 //this function originally written by KrimZon, made shorter by LordHavoc
2737 VM_SAFEPARMCOUNT(1,VM_argv);
2739 token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2742 token_num += num_tokens;
2744 if (token_num >= 0 && token_num < num_tokens)
2745 PRVM_G_INT(OFS_RETURN) = tokens[token_num];
2747 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2750 //float(float n) argv_start_index = #515; // returns the start index of a token
2751 void VM_argv_start_index (void)
2755 VM_SAFEPARMCOUNT(1,VM_argv);
2757 token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2760 token_num += num_tokens;
2762 if (token_num >= 0 && token_num < num_tokens)
2763 PRVM_G_FLOAT(OFS_RETURN) = tokens_startpos[token_num];
2765 PRVM_G_FLOAT(OFS_RETURN) = -1;
2768 //float(float n) argv_end_index = #516; // returns the end index of a token
2769 void VM_argv_end_index (void)
2773 VM_SAFEPARMCOUNT(1,VM_argv);
2775 token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2778 token_num += num_tokens;
2780 if (token_num >= 0 && token_num < num_tokens)
2781 PRVM_G_FLOAT(OFS_RETURN) = tokens_endpos[token_num];
2783 PRVM_G_FLOAT(OFS_RETURN) = -1;
2793 void VM_isserver(void)
2795 VM_SAFEPARMCOUNT(0,VM_serverstate);
2797 PRVM_G_FLOAT(OFS_RETURN) = sv.active && (svs.maxclients > 1 || cls.state == ca_dedicated);
2807 void VM_clientcount(void)
2809 VM_SAFEPARMCOUNT(0,VM_clientcount);
2811 PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
2821 void VM_clientstate(void)
2823 VM_SAFEPARMCOUNT(0,VM_clientstate);
2826 switch( cls.state ) {
2827 case ca_uninitialized:
2829 PRVM_G_FLOAT(OFS_RETURN) = 0;
2831 case ca_disconnected:
2832 PRVM_G_FLOAT(OFS_RETURN) = 1;
2835 PRVM_G_FLOAT(OFS_RETURN) = 2;
2838 // should never be reached!
2847 float getostype(void)
2849 */ // not used at the moment -> not included in the common list
2850 void VM_getostype(void)
2852 VM_SAFEPARMCOUNT(0,VM_getostype);
2857 OS_MAC - not supported
2861 PRVM_G_FLOAT(OFS_RETURN) = 0;
2862 #elif defined(MACOSX)
2863 PRVM_G_FLOAT(OFS_RETURN) = 2;
2865 PRVM_G_FLOAT(OFS_RETURN) = 1;
2876 extern double host_starttime;
2877 float CDAudio_GetPosition(void);
2878 void VM_gettime(void)
2882 VM_SAFEPARMCOUNTRANGE(0,1,VM_gettime);
2886 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2890 timer_index = (int) PRVM_G_FLOAT(OFS_PARM0);
2893 case 0: // GETTIME_FRAMESTART
2894 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2896 case 1: // GETTIME_REALTIME
2897 PRVM_G_FLOAT(OFS_RETURN) = (float) Sys_DoubleTime();
2899 case 2: // GETTIME_HIRES
2900 PRVM_G_FLOAT(OFS_RETURN) = (float) (Sys_DoubleTime() - realtime);
2902 case 3: // GETTIME_UPTIME
2903 PRVM_G_FLOAT(OFS_RETURN) = (float) (Sys_DoubleTime() - host_starttime);
2905 case 4: // GETTIME_CDTRACK
2906 PRVM_G_FLOAT(OFS_RETURN) = (float) CDAudio_GetPosition();
2909 VM_Warning("VM_gettime: %s: unsupported timer specified, returning realtime\n", PRVM_NAME);
2910 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2920 float getsoundtime(void)
2924 void VM_getsoundtime (void)
2926 int entnum, entchannel, pnum;
2927 VM_SAFEPARMCOUNT(2,VM_getsoundtime);
2929 pnum = PRVM_GetProgNr();
2930 if (pnum == PRVM_MENUPROG)
2932 VM_Warning("VM_getsoundtime: %s: not supported on this progs\n", PRVM_NAME);
2933 PRVM_G_FLOAT(OFS_RETURN) = -1;
2936 entnum = ((pnum == PRVM_CLIENTPROG) ? MAX_EDICTS : 0) + PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
2937 entchannel = (int)PRVM_G_FLOAT(OFS_PARM1);
2938 if (entchannel <= 0 || entchannel > 8)
2939 VM_Warning("VM_getsoundtime: %s: bad channel %i\n", PRVM_NAME, entchannel);
2940 PRVM_G_FLOAT(OFS_RETURN) = (float)S_GetEntChannelPosition(entnum, entchannel);
2947 string soundlength (string sample)
2950 void VM_soundlength (void)
2954 VM_SAFEPARMCOUNT(1, VM_soundlength);
2956 s = PRVM_G_STRING(OFS_PARM0);
2957 PRVM_G_FLOAT(OFS_RETURN) = S_SoundLength(s);
2964 loadfromdata(string data)
2967 void VM_loadfromdata(void)
2969 VM_SAFEPARMCOUNT(1,VM_loadentsfromfile);
2971 PRVM_ED_LoadFromFile(PRVM_G_STRING(OFS_PARM0));
2975 ========================
2978 parseentitydata(entity ent, string data)
2979 ========================
2981 void VM_parseentitydata(void)
2986 VM_SAFEPARMCOUNT(2, VM_parseentitydata);
2988 // get edict and test it
2989 ent = PRVM_G_EDICT(OFS_PARM0);
2990 if (ent->priv.required->free)
2991 PRVM_ERROR ("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2993 data = PRVM_G_STRING(OFS_PARM1);
2995 // parse the opening brace
2996 if (!COM_ParseToken_Simple(&data, false, false) || com_token[0] != '{' )
2997 PRVM_ERROR ("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", PRVM_NAME, data );
2999 PRVM_ED_ParseEdict (data, ent);
3006 loadfromfile(string file)
3009 void VM_loadfromfile(void)
3011 const char *filename;
3014 VM_SAFEPARMCOUNT(1,VM_loadfromfile);
3016 filename = PRVM_G_STRING(OFS_PARM0);
3017 if (FS_CheckNastyPath(filename, false))
3019 PRVM_G_FLOAT(OFS_RETURN) = -4;
3020 VM_Warning("VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", PRVM_NAME, filename);
3024 // not conform with VM_fopen
3025 data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
3027 PRVM_G_FLOAT(OFS_RETURN) = -1;
3029 PRVM_ED_LoadFromFile(data);
3040 float mod(float val, float m)
3043 void VM_modulo(void)
3046 VM_SAFEPARMCOUNT(2,VM_module);
3048 val = (int) PRVM_G_FLOAT(OFS_PARM0);
3049 m = (int) PRVM_G_FLOAT(OFS_PARM1);
3051 PRVM_G_FLOAT(OFS_RETURN) = (float) (val % m);
3054 void VM_Search_Init(void)
3057 for (i = 0;i < PRVM_MAX_OPENSEARCHES;i++)
3058 prog->opensearches[i] = NULL;
3061 void VM_Search_Reset(void)
3064 // reset the fssearch list
3065 for(i = 0; i < PRVM_MAX_OPENSEARCHES; i++)
3067 if(prog->opensearches[i])
3068 FS_FreeSearch(prog->opensearches[i]);
3069 prog->opensearches[i] = NULL;
3077 float search_begin(string pattern, float caseinsensitive, float quiet)
3080 void VM_search_begin(void)
3083 const char *pattern;
3084 int caseinsens, quiet;
3086 VM_SAFEPARMCOUNT(3, VM_search_begin);
3088 pattern = PRVM_G_STRING(OFS_PARM0);
3090 VM_CheckEmptyString(pattern);
3092 caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
3093 quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
3095 for(handle = 0; handle < PRVM_MAX_OPENSEARCHES; handle++)
3096 if(!prog->opensearches[handle])
3099 if(handle >= PRVM_MAX_OPENSEARCHES)
3101 PRVM_G_FLOAT(OFS_RETURN) = -2;
3102 VM_Warning("VM_search_begin: %s ran out of search handles (%i)\n", PRVM_NAME, PRVM_MAX_OPENSEARCHES);
3106 if(!(prog->opensearches[handle] = FS_Search(pattern,caseinsens, quiet)))
3107 PRVM_G_FLOAT(OFS_RETURN) = -1;
3110 prog->opensearches_origin[handle] = PRVM_AllocationOrigin();
3111 PRVM_G_FLOAT(OFS_RETURN) = handle;
3119 void search_end(float handle)
3122 void VM_search_end(void)
3125 VM_SAFEPARMCOUNT(1, VM_search_end);
3127 handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3129 if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3131 VM_Warning("VM_search_end: invalid handle %i used in %s\n", handle, PRVM_NAME);
3134 if(prog->opensearches[handle] == NULL)
3136 VM_Warning("VM_search_end: no such handle %i in %s\n", handle, PRVM_NAME);
3140 FS_FreeSearch(prog->opensearches[handle]);
3141 prog->opensearches[handle] = NULL;
3142 if(prog->opensearches_origin[handle])
3143 PRVM_Free((char *)prog->opensearches_origin[handle]);
3150 float search_getsize(float handle)
3153 void VM_search_getsize(void)
3156 VM_SAFEPARMCOUNT(1, VM_M_search_getsize);
3158 handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3160 if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3162 VM_Warning("VM_search_getsize: invalid handle %i used in %s\n", handle, PRVM_NAME);
3165 if(prog->opensearches[handle] == NULL)
3167 VM_Warning("VM_search_getsize: no such handle %i in %s\n", handle, PRVM_NAME);
3171 PRVM_G_FLOAT(OFS_RETURN) = prog->opensearches[handle]->numfilenames;
3176 VM_search_getfilename
3178 string search_getfilename(float handle, float num)
3181 void VM_search_getfilename(void)
3183 int handle, filenum;
3184 VM_SAFEPARMCOUNT(2, VM_search_getfilename);
3186 handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3187 filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
3189 if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3191 VM_Warning("VM_search_getfilename: invalid handle %i used in %s\n", handle, PRVM_NAME);
3194 if(prog->opensearches[handle] == NULL)
3196 VM_Warning("VM_search_getfilename: no such handle %i in %s\n", handle, PRVM_NAME);
3199 if(filenum < 0 || filenum >= prog->opensearches[handle]->numfilenames)
3201 VM_Warning("VM_search_getfilename: invalid filenum %i in %s\n", filenum, PRVM_NAME);
3205 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog->opensearches[handle]->filenames[filenum]);
3212 string chr(float ascii)
3219 VM_SAFEPARMCOUNT(1, VM_chr);
3221 tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
3224 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(tmp);
3229 VM_SAFEPARMCOUNT(1, VM_chr);
3231 len = u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0), tmp, sizeof(tmp));
3233 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(tmp);
3236 //=============================================================================
3237 // Draw builtins (client & menu)
3243 float iscachedpic(string pic)
3246 void VM_iscachedpic(void)
3248 VM_SAFEPARMCOUNT(1,VM_iscachedpic);
3250 // drawq hasnt such a function, thus always return true
3251 PRVM_G_FLOAT(OFS_RETURN) = false;
3258 string precache_pic(string pic)
3261 void VM_precache_pic(void)
3265 VM_SAFEPARMCOUNT(1, VM_precache_pic);
3267 s = PRVM_G_STRING(OFS_PARM0);
3268 PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
3269 VM_CheckEmptyString (s);
3271 // AK Draw_CachePic is supposed to always return a valid pointer
3272 if( Draw_CachePic_Flags(s, 0)->tex == r_texture_notexture )
3273 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
3283 void VM_freepic(void)
3287 VM_SAFEPARMCOUNT(1,VM_freepic);
3289 s = PRVM_G_STRING(OFS_PARM0);
3290 VM_CheckEmptyString (s);
3295 void getdrawfontscale(float *sx, float *sy)
3299 if(prog->globaloffsets.drawfontscale >= 0)
3301 VectorCopy(PRVM_G_VECTOR(prog->globaloffsets.drawfontscale), v);
3302 if(VectorLength2(v) > 0)
3310 dp_font_t *getdrawfont(void)
3312 if(prog->globaloffsets.drawfont >= 0)
3314 int f = (int) PRVM_G_FLOAT(prog->globaloffsets.drawfont);
3315 if(f < 0 || f >= dp_fonts.maxsize)
3316 return FONT_DEFAULT;
3317 return &dp_fonts.f[f];
3320 return FONT_DEFAULT;
3327 float drawcharacter(vector position, float character, vector scale, vector rgb, float alpha, float flag)
3330 void VM_drawcharacter(void)
3332 float *pos,*scale,*rgb;
3336 VM_SAFEPARMCOUNT(6,VM_drawcharacter);
3338 character = (char) PRVM_G_FLOAT(OFS_PARM1);
3341 PRVM_G_FLOAT(OFS_RETURN) = -1;
3342 VM_Warning("VM_drawcharacter: %s passed null character !\n",PRVM_NAME);
3346 pos = PRVM_G_VECTOR(OFS_PARM0);
3347 scale = PRVM_G_VECTOR(OFS_PARM2);
3348 rgb = PRVM_G_VECTOR(OFS_PARM3);
3349 flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3351 if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3353 PRVM_G_FLOAT(OFS_RETURN) = -2;
3354 VM_Warning("VM_drawcharacter: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3358 if(pos[2] || scale[2])
3359 Con_Printf("VM_drawcharacter: z value%c from %s discarded\n",(pos[2] && scale[2]) ? 's' : 0,((pos[2] && scale[2]) ? "pos and scale" : (pos[2] ? "pos" : "scale")));
3361 if(!scale[0] || !scale[1])
3363 PRVM_G_FLOAT(OFS_RETURN) = -3;
3364 VM_Warning("VM_drawcharacter: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3368 getdrawfontscale(&sx, &sy);
3369 DrawQ_String_Scale(pos[0], pos[1], &character, 1, scale[0], scale[1], sx, sy, rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag, NULL, true, getdrawfont());
3370 PRVM_G_FLOAT(OFS_RETURN) = 1;
3377 float drawstring(vector position, string text, vector scale, vector rgb, float alpha, float flag)
3380 void VM_drawstring(void)
3382 float *pos,*scale,*rgb;
3386 VM_SAFEPARMCOUNT(6,VM_drawstring);
3388 string = PRVM_G_STRING(OFS_PARM1);
3389 pos = PRVM_G_VECTOR(OFS_PARM0);
3390 scale = PRVM_G_VECTOR(OFS_PARM2);
3391 rgb = PRVM_G_VECTOR(OFS_PARM3);
3392 flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3394 if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3396 PRVM_G_FLOAT(OFS_RETURN) = -2;
3397 VM_Warning("VM_drawstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3401 if(!scale[0] || !scale[1])
3403 PRVM_G_FLOAT(OFS_RETURN) = -3;
3404 VM_Warning("VM_drawstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3408 if(pos[2] || scale[2])
3409 Con_Printf("VM_drawstring: z value%s from %s discarded\n",(pos[2] && scale[2]) ? "s" : " ",((pos[2] && scale[2]) ? "pos and scale" : (pos[2] ? "pos" : "scale")));
3411 getdrawfontscale(&sx, &sy);
3412 DrawQ_String_Scale(pos[0], pos[1], string, 0, scale[0], scale[1], sx, sy, rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag, NULL, true, getdrawfont());
3413 //Font_DrawString(pos[0], pos[1], string, 0, scale[0], scale[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag, NULL, true);
3414 PRVM_G_FLOAT(OFS_RETURN) = 1;
3419 VM_drawcolorcodedstring
3421 float drawcolorcodedstring(vector position, string text, vector scale, float alpha, float flag)
3423 float drawcolorcodedstring(vector position, string text, vector scale, vector rgb, float alpha, float flag)
3426 void VM_drawcolorcodedstring(void)
3432 float sx, sy, alpha;
3434 VM_SAFEPARMCOUNTRANGE(5,6,VM_drawcolorcodedstring);
3436 if (prog->argc == 6) // full 6 parms, like normal drawstring
3438 pos = PRVM_G_VECTOR(OFS_PARM0);
3439 string = PRVM_G_STRING(OFS_PARM1);
3440 scale = PRVM_G_VECTOR(OFS_PARM2);
3441 VectorCopy(PRVM_G_VECTOR(OFS_PARM3), rgb);
3442 alpha = PRVM_G_FLOAT(OFS_PARM4);
3443 flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3447 pos = PRVM_G_VECTOR(OFS_PARM0);
3448 string = PRVM_G_STRING(OFS_PARM1);
3449 scale = PRVM_G_VECTOR(OFS_PARM2);
3453 alpha = PRVM_G_FLOAT(OFS_PARM3);
3454 flag = (int)PRVM_G_FLOAT(OFS_PARM4);
3457 if(flag < DRAWFLAG_NORMAL || flag >= DRAWFLAG_NUMFLAGS)
3459 PRVM_G_FLOAT(OFS_RETURN) = -2;
3460 VM_Warning("VM_drawcolorcodedstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3464 if(!scale[0] || !scale[1])
3466 PRVM_G_FLOAT(OFS_RETURN) = -3;
3467 VM_Warning("VM_drawcolorcodedstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3471 if(pos[2] || scale[2])
3472 Con_Printf("VM_drawcolorcodedstring: z value%s from %s discarded\n",(pos[2] && scale[2]) ? "s" : " ",((pos[2] && scale[2]) ? "pos and scale" : (pos[2] ? "pos" : "scale")));
3474 getdrawfontscale(&sx, &sy);
3475 DrawQ_String_Scale(pos[0], pos[1], string, 0, scale[0], scale[1], sx, sy, rgb[0], rgb[1], rgb[2], alpha, flag, NULL, false, getdrawfont());
3476 if (prog->argc == 6) // also return vector of last color
3477 VectorCopy(DrawQ_Color, PRVM_G_VECTOR(OFS_RETURN));
3479 PRVM_G_FLOAT(OFS_RETURN) = 1;
3485 float stringwidth(string text, float allowColorCodes, float size)
3488 void VM_stringwidth(void)
3492 float mult; // sz is intended font size so we can later add freetype support, mult is font size multiplier in pixels per character cell
3496 VM_SAFEPARMCOUNTRANGE(2,3,VM_drawstring);
3498 getdrawfontscale(&sx, &sy);
3501 szv = PRVM_G_VECTOR(OFS_PARM2);
3506 // we want the width for 8x8 font size, divided by 8
3507 static float defsize[] = {8, 8};
3510 // to make sure snapping is turned off, ALWAYS use a nontrivial scale in this case
3511 if(sx >= 0.9 && sx <= 1.1)
3519 string = PRVM_G_STRING(OFS_PARM0);
3520 colors = (int)PRVM_G_FLOAT(OFS_PARM1);
3522 PRVM_G_FLOAT(OFS_RETURN) = DrawQ_TextWidth_UntilWidth_TrackColors_Scale(string, &maxlen, szv[0], szv[1], sx, sy, NULL, !colors, getdrawfont(), 1000000000) * mult;
3526 mult = sz = PRVM_G_FLOAT(OFS_PARM2);
3534 string = PRVM_G_STRING(OFS_PARM0);
3535 colors = (int)PRVM_G_FLOAT(OFS_PARM1);
3537 PRVM_G_FLOAT(OFS_RETURN) = DrawQ_TextWidth(string, 0, !colors, getdrawfont()) * mult; // 1x1 characters, don't actually draw
3545 float findfont(string s)
3549 float getdrawfontnum(const char *fontname)
3553 for(i = 0; i < dp_fonts.maxsize; ++i)
3554 if(!strcmp(dp_fonts.f[i].title, fontname))
3559 void VM_findfont(void)
3561 VM_SAFEPARMCOUNT(1,VM_findfont);
3562 PRVM_G_FLOAT(OFS_RETURN) = getdrawfontnum(PRVM_G_STRING(OFS_PARM0));
3569 float loadfont(string fontname, string fontmaps, string sizes, float slot)
3573 dp_font_t *FindFont(const char *title, qboolean allocate_new);
3574 void LoadFont(qboolean override, const char *name, dp_font_t *fnt, float scale, float voffset);
3575 void VM_loadfont(void)
3577 const char *fontname, *filelist, *sizes, *c, *cm;
3578 char mainfont[MAX_QPATH];
3580 float sz, scale, voffset;
3583 VM_SAFEPARMCOUNTRANGE(3,6,VM_loadfont);
3585 fontname = PRVM_G_STRING(OFS_PARM0);
3587 fontname = "default";
3589 filelist = PRVM_G_STRING(OFS_PARM1);
3591 filelist = "gfx/conchars";
3593 sizes = PRVM_G_STRING(OFS_PARM2);
3599 if (prog->argc >= 4)
3601 i = PRVM_G_FLOAT(OFS_PARM3);
3602 if (i >= 0 && i < dp_fonts.maxsize)
3605 strlcpy(f->title, fontname, sizeof(f->title)); // replace name
3609 f = FindFont(fontname, true);
3612 PRVM_G_FLOAT(OFS_RETURN) = -1;
3613 return; // something go wrong
3616 memset(f->fallbacks, 0, sizeof(f->fallbacks));
3617 memset(f->fallback_faces, 0, sizeof(f->fallback_faces));
3619 // first font is handled "normally"
3620 c = strchr(filelist, ':');
3621 cm = strchr(filelist, ',');
3622 if(c && (!cm || c < cm))
3623 f->req_face = atoi(c+1);
3629 if(!c || (c - filelist) > MAX_QPATH)
3630 strlcpy(mainfont, filelist, sizeof(mainfont));
3633 memcpy(mainfont, filelist, c - filelist);
3634 mainfont[c - filelist] = 0;
3638 for(i = 0; i < MAX_FONT_FALLBACKS; ++i)
3640 c = strchr(filelist, ',');
3646 c = strchr(filelist, ':');
3647 cm = strchr(filelist, ',');
3648 if(c && (!cm || c < cm))
3649 f->fallback_faces[i] = atoi(c+1);
3652 f->fallback_faces[i] = 0; // f->req_face; could make it stick to the default-font's face index
3655 if(!c || (c-filelist) > MAX_QPATH)
3657 strlcpy(f->fallbacks[i], filelist, sizeof(mainfont));
3661 memcpy(f->fallbacks[i], filelist, c - filelist);
3662 f->fallbacks[i][c - filelist] = 0;
3667 for(i = 0; i < MAX_FONT_SIZES; ++i)
3668 f->req_sizes[i] = -1;
3669 for (numsizes = 0,c = sizes;;)
3671 if (!COM_ParseToken_VM_Tokenize(&c, 0))
3673 sz = atof(com_token);
3675 if (sz < 0.001f || sz > 1000.0f)
3677 VM_Warning("VM_loadfont: crap size %s", com_token);
3681 if (numsizes == MAX_FONT_SIZES)
3683 VM_Warning("VM_loadfont: MAX_FONT_SIZES = %i exceeded", MAX_FONT_SIZES);
3686 f->req_sizes[numsizes] = sz;
3690 // additional scale/hoffset parms
3693 if (prog->argc >= 5)
3695 scale = PRVM_G_FLOAT(OFS_PARM4);
3699 if (prog->argc >= 6)
3700 voffset = PRVM_G_FLOAT(OFS_PARM5);
3703 LoadFont(true, mainfont, f, scale, voffset);
3705 // return index of loaded font
3706 PRVM_G_FLOAT(OFS_RETURN) = (f - dp_fonts.f);
3713 float drawpic(vector position, string pic, vector size, vector rgb, float alpha, float flag)
3716 void VM_drawpic(void)
3718 const char *picname;
3719 float *size, *pos, *rgb;
3722 VM_SAFEPARMCOUNT(6,VM_drawpic);
3724 picname = PRVM_G_STRING(OFS_PARM1);
3725 VM_CheckEmptyString (picname);
3727 // is pic cached ? no function yet for that
3730 PRVM_G_FLOAT(OFS_RETURN) = -4;
3731 VM_Warning("VM_drawpic: %s: %s not cached !\n", PRVM_NAME, picname);
3735 pos = PRVM_G_VECTOR(OFS_PARM0);
3736 size = PRVM_G_VECTOR(OFS_PARM2);
3737 rgb = PRVM_G_VECTOR(OFS_PARM3);
3738 flag = (int) PRVM_G_FLOAT(OFS_PARM5);
3740 if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3742 PRVM_G_FLOAT(OFS_RETURN) = -2;
3743 VM_Warning("VM_drawpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3747 if(pos[2] || size[2])
3748 Con_Printf("VM_drawpic: z value%s from %s discarded\n",(pos[2] && size[2]) ? "s" : " ",((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
3750 DrawQ_Pic(pos[0], pos[1], Draw_CachePic_Flags (picname, CACHEPICFLAG_NOTPERSISTENT), size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag);
3751 PRVM_G_FLOAT(OFS_RETURN) = 1;
3757 float drawrotpic(vector position, string pic, vector size, vector org, float angle, vector rgb, float alpha, float flag)
3760 void VM_drawrotpic(void)
3762 const char *picname;
3763 float *size, *pos, *org, *rgb;
3766 VM_SAFEPARMCOUNT(8,VM_drawrotpic);
3768 picname = PRVM_G_STRING(OFS_PARM1);
3769 VM_CheckEmptyString (picname);
3771 // is pic cached ? no function yet for that
3774 PRVM_G_FLOAT(OFS_RETURN) = -4;
3775 VM_Warning("VM_drawrotpic: %s: %s not cached !\n", PRVM_NAME, picname);
3779 pos = PRVM_G_VECTOR(OFS_PARM0);
3780 size = PRVM_G_VECTOR(OFS_PARM2);
3781 org = PRVM_G_VECTOR(OFS_PARM3);
3782 rgb = PRVM_G_VECTOR(OFS_PARM5);
3783 flag = (int) PRVM_G_FLOAT(OFS_PARM7);
3785 if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3787 PRVM_G_FLOAT(OFS_RETURN) = -2;
3788 VM_Warning("VM_drawrotpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3792 if(pos[2] || size[2] || org[2])
3793 Con_Printf("VM_drawrotpic: z value from pos/size/org discarded\n");
3795 DrawQ_RotPic(pos[0], pos[1], Draw_CachePic_Flags(picname, CACHEPICFLAG_NOTPERSISTENT), size[0], size[1], org[0], org[1], PRVM_G_FLOAT(OFS_PARM4), rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM6), flag);
3796 PRVM_G_FLOAT(OFS_RETURN) = 1;
3802 float drawsubpic(vector position, vector size, string pic, vector srcPos, vector srcSize, vector rgb, float alpha, float flag)
3806 void VM_drawsubpic(void)
3808 const char *picname;
3809 float *size, *pos, *rgb, *srcPos, *srcSize, alpha;
3812 VM_SAFEPARMCOUNT(8,VM_drawsubpic);
3814 picname = PRVM_G_STRING(OFS_PARM2);
3815 VM_CheckEmptyString (picname);
3817 // is pic cached ? no function yet for that
3820 PRVM_G_FLOAT(OFS_RETURN) = -4;
3821 VM_Warning("VM_drawsubpic: %s: %s not cached !\n", PRVM_NAME, picname);
3825 pos = PRVM_G_VECTOR(OFS_PARM0);
3826 size = PRVM_G_VECTOR(OFS_PARM1);
3827 srcPos = PRVM_G_VECTOR(OFS_PARM3);
3828 srcSize = PRVM_G_VECTOR(OFS_PARM4);
3829 rgb = PRVM_G_VECTOR(OFS_PARM5);
3830 alpha = PRVM_G_FLOAT(OFS_PARM6);
3831 flag = (int) PRVM_G_FLOAT(OFS_PARM7);
3833 if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3835 PRVM_G_FLOAT(OFS_RETURN) = -2;
3836 VM_Warning("VM_drawsubpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3840 if(pos[2] || size[2])
3841 Con_Printf("VM_drawsubpic: z value%s from %s discarded\n",(pos[2] && size[2]) ? "s" : " ",((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
3843 DrawQ_SuperPic(pos[0], pos[1], Draw_CachePic_Flags (picname, CACHEPICFLAG_NOTPERSISTENT),
3845 srcPos[0], srcPos[1], rgb[0], rgb[1], rgb[2], alpha,
3846 srcPos[0] + srcSize[0], srcPos[1], rgb[0], rgb[1], rgb[2], alpha,
3847 srcPos[0], srcPos[1] + srcSize[1], rgb[0], rgb[1], rgb[2], alpha,
3848 srcPos[0] + srcSize[0], srcPos[1] + srcSize[1], rgb[0], rgb[1], rgb[2], alpha,
3850 PRVM_G_FLOAT(OFS_RETURN) = 1;
3857 float drawfill(vector position, vector size, vector rgb, float alpha, float flag)
3860 void VM_drawfill(void)
3862 float *size, *pos, *rgb;
3865 VM_SAFEPARMCOUNT(5,VM_drawfill);
3868 pos = PRVM_G_VECTOR(OFS_PARM0);
3869 size = PRVM_G_VECTOR(OFS_PARM1);
3870 rgb = PRVM_G_VECTOR(OFS_PARM2);
3871 flag = (int) PRVM_G_FLOAT(OFS_PARM4);
3873 if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3875 PRVM_G_FLOAT(OFS_RETURN) = -2;
3876 VM_Warning("VM_drawfill: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3880 if(pos[2] || size[2])
3881 Con_Printf("VM_drawfill: z value%s from %s discarded\n",(pos[2] && size[2]) ? "s" : " ",((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
3883 DrawQ_Fill(pos[0], pos[1], size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM3), flag);
3884 PRVM_G_FLOAT(OFS_RETURN) = 1;
3891 drawsetcliparea(float x, float y, float width, float height)
3894 void VM_drawsetcliparea(void)
3897 VM_SAFEPARMCOUNT(4,VM_drawsetcliparea);
3899 x = bound(0, PRVM_G_FLOAT(OFS_PARM0), vid_conwidth.integer);
3900 y = bound(0, PRVM_G_FLOAT(OFS_PARM1), vid_conheight.integer);
3901 w = bound(0, PRVM_G_FLOAT(OFS_PARM2) + PRVM_G_FLOAT(OFS_PARM0) - x, (vid_conwidth.integer - x));
3902 h = bound(0, PRVM_G_FLOAT(OFS_PARM3) + PRVM_G_FLOAT(OFS_PARM1) - y, (vid_conheight.integer - y));
3904 DrawQ_SetClipArea(x, y, w, h);
3909 VM_drawresetcliparea
3914 void VM_drawresetcliparea(void)
3916 VM_SAFEPARMCOUNT(0,VM_drawresetcliparea);
3918 DrawQ_ResetClipArea();
3925 vector getimagesize(string pic)
3928 void VM_getimagesize(void)
3933 VM_SAFEPARMCOUNT(1,VM_getimagesize);
3935 p = PRVM_G_STRING(OFS_PARM0);
3936 VM_CheckEmptyString (p);
3938 pic = Draw_CachePic_Flags (p, CACHEPICFLAG_NOTPERSISTENT);
3940 PRVM_G_VECTOR(OFS_RETURN)[0] = pic->width;
3941 PRVM_G_VECTOR(OFS_RETURN)[1] = pic->height;
3942 PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
3949 string keynumtostring(float keynum)
3952 void VM_keynumtostring (void)
3954 VM_SAFEPARMCOUNT(1, VM_keynumtostring);
3956 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Key_KeynumToString((int)PRVM_G_FLOAT(OFS_PARM0)));
3961 VM_findkeysforcommand
3963 string findkeysforcommand(string command, float bindmap)
3965 the returned string is an altstring
3968 #define FKFC_NUMKEYS 5
3969 void M_FindKeysForCommand(const char *command, int *keys);
3970 void VM_findkeysforcommand(void)
3973 char ret[VM_STRINGTEMP_LENGTH];
3974 int keys[FKFC_NUMKEYS];
3978 VM_SAFEPARMCOUNTRANGE(1, 2, VM_findkeysforcommand);
3980 cmd = PRVM_G_STRING(OFS_PARM0);
3982 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3984 bindmap = 0; // consistent to "bind"
3986 VM_CheckEmptyString(cmd);
3988 Key_FindKeysForCommand(cmd, keys, FKFC_NUMKEYS, bindmap);
3991 for(i = 0; i < FKFC_NUMKEYS; i++)
3992 strlcat(ret, va(" \'%i\'", keys[i]), sizeof(ret));
3994 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(ret);
4001 float stringtokeynum(string key)
4004 void VM_stringtokeynum (void)
4006 VM_SAFEPARMCOUNT( 1, VM_keynumtostring );
4008 PRVM_G_FLOAT(OFS_RETURN) = Key_StringToKeynum(PRVM_G_STRING(OFS_PARM0));
4015 string getkeybind(float key, float bindmap)
4018 void VM_getkeybind (void)
4021 VM_SAFEPARMCOUNTRANGE(1, 2, VM_CL_getkeybind);
4023 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
4025 bindmap = 0; // consistent to "bind"
4027 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Key_GetBind((int)PRVM_G_FLOAT(OFS_PARM0), bindmap));
4034 float setkeybind(float key, string cmd, float bindmap)
4037 void VM_setkeybind (void)
4040 VM_SAFEPARMCOUNTRANGE(2, 3, VM_CL_setkeybind);
4042 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM2), MAX_BINDMAPS-1);
4044 bindmap = 0; // consistent to "bind"
4046 PRVM_G_FLOAT(OFS_RETURN) = 0;
4047 if(Key_SetBinding((int)PRVM_G_FLOAT(OFS_PARM0), bindmap, PRVM_G_STRING(OFS_PARM1)))
4048 PRVM_G_FLOAT(OFS_RETURN) = 1;
4055 vector getbindmaps()
4058 void VM_getbindmaps (void)
4061 VM_SAFEPARMCOUNT(0, VM_CL_getbindmap);
4062 Key_GetBindMap(&fg, &bg);
4063 PRVM_G_VECTOR(OFS_RETURN)[0] = fg;
4064 PRVM_G_VECTOR(OFS_RETURN)[1] = bg;
4065 PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
4072 float setbindmaps(vector bindmap)
4075 void VM_setbindmaps (void)
4077 VM_SAFEPARMCOUNT(1, VM_CL_setbindmap);
4078 PRVM_G_FLOAT(OFS_RETURN) = 0;
4079 if(PRVM_G_VECTOR(OFS_PARM0)[2] == 0)
4080 if(Key_SetBindMap((int)PRVM_G_VECTOR(OFS_PARM0)[0], (int)PRVM_G_VECTOR(OFS_PARM0)[1]))
4081 PRVM_G_FLOAT(OFS_RETURN) = 1;
4084 // CL_Video interface functions
4087 ========================
4090 float cin_open(string file, string name)
4091 ========================
4093 void VM_cin_open( void )
4098 VM_SAFEPARMCOUNT( 2, VM_cin_open );
4100 file = PRVM_G_STRING( OFS_PARM0 );
4101 name = PRVM_G_STRING( OFS_PARM1 );
4103 VM_CheckEmptyString( file );
4104 VM_CheckEmptyString( name );
4106 if( CL_OpenVideo( file, name, MENUOWNER, "" ) )
4107 PRVM_G_FLOAT( OFS_RETURN ) = 1;
4109 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4113 ========================
4116 void cin_close(string name)
4117 ========================
4119 void VM_cin_close( void )
4123 VM_SAFEPARMCOUNT( 1, VM_cin_close );
4125 name = PRVM_G_STRING( OFS_PARM0 );
4126 VM_CheckEmptyString( name );
4128 CL_CloseVideo( CL_GetVideoByName( name ) );
4132 ========================
4134 void cin_setstate(string name, float type)
4135 ========================
4137 void VM_cin_setstate( void )
4140 clvideostate_t state;
4143 VM_SAFEPARMCOUNT( 2, VM_cin_netstate );
4145 name = PRVM_G_STRING( OFS_PARM0 );
4146 VM_CheckEmptyString( name );
4148 state = (clvideostate_t)((int)PRVM_G_FLOAT( OFS_PARM1 ));
4150 video = CL_GetVideoByName( name );
4151 if( video && state > CLVIDEO_UNUSED && state < CLVIDEO_STATECOUNT )
4152 CL_SetVideoState( video, state );
4156 ========================
4159 float cin_getstate(string name)
4160 ========================
4162 void VM_cin_getstate( void )
4167 VM_SAFEPARMCOUNT( 1, VM_cin_getstate );
4169 name = PRVM_G_STRING( OFS_PARM0 );
4170 VM_CheckEmptyString( name );
4172 video = CL_GetVideoByName( name );
4174 PRVM_G_FLOAT( OFS_RETURN ) = (int)video->state;
4176 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4180 ========================
4183 void cin_restart(string name)
4184 ========================
4186 void VM_cin_restart( void )
4191 VM_SAFEPARMCOUNT( 1, VM_cin_restart );
4193 name = PRVM_G_STRING( OFS_PARM0 );
4194 VM_CheckEmptyString( name );
4196 video = CL_GetVideoByName( name );
4198 CL_RestartVideo( video );
4202 ========================
4204 ========================
4206 void VM_Gecko_Init( void ) {
4207 // the prog struct is memset to 0 by Initprog? [12/6/2007 Black]
4208 // FIXME: remove the other _Init functions then, too? [12/6/2007 Black]
4212 ========================
4214 ========================
4216 void VM_Gecko_Destroy( void ) {
4218 for( i = 0 ; i < PRVM_MAX_GECKOINSTANCES ; i++ ) {
4219 clgecko_t **instance = &prog->opengeckoinstances[ i ];
4221 CL_Gecko_DestroyBrowser( *instance );
4228 ========================
4231 float[bool] gecko_create( string name )
4232 ========================
4234 void VM_gecko_create( void ) {
4237 clgecko_t *instance;
4239 VM_SAFEPARMCOUNT( 1, VM_gecko_create );
4241 name = PRVM_G_STRING( OFS_PARM0 );
4242 VM_CheckEmptyString( name );
4244 // find an empty slot for this gecko browser..
4245 for( i = 0 ; i < PRVM_MAX_GECKOINSTANCES ; i++ ) {
4246 if( prog->opengeckoinstances[ i ] == NULL ) {
4250 if( i == PRVM_MAX_GECKOINSTANCES ) {
4251 VM_Warning("VM_gecko_create: %s ran out of gecko handles (%i)\n", PRVM_NAME, PRVM_MAX_GECKOINSTANCES);
4252 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4256 instance = prog->opengeckoinstances[ i ] = CL_Gecko_CreateBrowser( name, PRVM_GetProgNr() );
4258 // TODO: error handling [12/3/2007 Black]
4259 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4262 PRVM_G_FLOAT( OFS_RETURN ) = 1;
4266 ========================
4269 void gecko_destroy( string name )
4270 ========================
4272 void VM_gecko_destroy( void ) {
4274 clgecko_t *instance;
4276 VM_SAFEPARMCOUNT( 1, VM_gecko_destroy );
4278 name = PRVM_G_STRING( OFS_PARM0 );
4279 VM_CheckEmptyString( name );
4280 instance = CL_Gecko_FindBrowser( name );
4284 CL_Gecko_DestroyBrowser( instance );
4288 ========================
4291 void gecko_navigate( string name, string URI )
4292 ========================
4294 void VM_gecko_navigate( void ) {
4297 clgecko_t *instance;
4299 VM_SAFEPARMCOUNT( 2, VM_gecko_navigate );
4301 name = PRVM_G_STRING( OFS_PARM0 );
4302 URI = PRVM_G_STRING( OFS_PARM1 );
4303 VM_CheckEmptyString( name );
4304 VM_CheckEmptyString( URI );
4306 instance = CL_Gecko_FindBrowser( name );
4310 CL_Gecko_NavigateToURI( instance, URI );
4314 ========================
4317 float[bool] gecko_keyevent( string name, float key, float eventtype )
4318 ========================
4320 void VM_gecko_keyevent( void ) {
4323 clgecko_buttoneventtype_t eventtype;
4324 clgecko_t *instance;
4326 VM_SAFEPARMCOUNT( 3, VM_gecko_keyevent );
4328 name = PRVM_G_STRING( OFS_PARM0 );
4329 VM_CheckEmptyString( name );
4330 key = (unsigned int) PRVM_G_FLOAT( OFS_PARM1 );
4331 switch( (unsigned int) PRVM_G_FLOAT( OFS_PARM2 ) ) {
4333 eventtype = CLG_BET_DOWN;
4336 eventtype = CLG_BET_UP;
4339 eventtype = CLG_BET_PRESS;
4342 eventtype = CLG_BET_DOUBLECLICK;
4345 // TODO: console printf? [12/3/2007 Black]
4346 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4350 instance = CL_Gecko_FindBrowser( name );
4352 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4356 PRVM_G_FLOAT( OFS_RETURN ) = (CL_Gecko_Event_Key( instance, (keynum_t) key, eventtype ) == true);
4360 ========================
4363 void gecko_mousemove( string name, float x, float y )
4364 ========================
4366 void VM_gecko_movemouse( void ) {
4369 clgecko_t *instance;
4371 VM_SAFEPARMCOUNT( 3, VM_gecko_movemouse );
4373 name = PRVM_G_STRING( OFS_PARM0 );
4374 VM_CheckEmptyString( name );
4375 x = PRVM_G_FLOAT( OFS_PARM1 );
4376 y = PRVM_G_FLOAT( OFS_PARM2 );
4378 instance = CL_Gecko_FindBrowser( name );
4382 CL_Gecko_Event_CursorMove( instance, x, y );
4387 ========================
4390 void gecko_resize( string name, float w, float h )
4391 ========================
4393 void VM_gecko_resize( void ) {
4396 clgecko_t *instance;
4398 VM_SAFEPARMCOUNT( 3, VM_gecko_movemouse );
4400 name = PRVM_G_STRING( OFS_PARM0 );
4401 VM_CheckEmptyString( name );
4402 w = PRVM_G_FLOAT( OFS_PARM1 );
4403 h = PRVM_G_FLOAT( OFS_PARM2 );
4405 instance = CL_Gecko_FindBrowser( name );
4409 CL_Gecko_Resize( instance, (int) w, (int) h );
4414 ========================
4415 VM_gecko_get_texture_extent
4417 vector gecko_get_texture_extent( string name )
4418 ========================
4420 void VM_gecko_get_texture_extent( void ) {
4422 clgecko_t *instance;
4424 VM_SAFEPARMCOUNT( 1, VM_gecko_movemouse );
4426 name = PRVM_G_STRING( OFS_PARM0 );
4427 VM_CheckEmptyString( name );
4429 PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
4430 instance = CL_Gecko_FindBrowser( name );
4432 PRVM_G_VECTOR(OFS_RETURN)[0] = 0;
4433 PRVM_G_VECTOR(OFS_RETURN)[1] = 0;
4436 CL_Gecko_GetTextureExtent( instance,
4437 PRVM_G_VECTOR(OFS_RETURN), PRVM_G_VECTOR(OFS_RETURN)+1 );
4446 Writes new values for v_forward, v_up, and v_right based on angles
4447 void makevectors(vector angle)
4450 void VM_makevectors (void)
4452 prvm_eval_t *valforward, *valright, *valup;
4453 valforward = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.v_forward);
4454 valright = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.v_right);
4455 valup = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.v_up);
4456 if (!valforward || !valright || !valup)
4458 VM_Warning("makevectors: could not find v_forward, v_right, or v_up global variables\n");
4461 VM_SAFEPARMCOUNT(1, VM_makevectors);
4462 AngleVectors (PRVM_G_VECTOR(OFS_PARM0), valforward->vector, valright->vector, valup->vector);
4469 Writes new values for v_forward, v_up, and v_right based on the given forward vector
4470 vectorvectors(vector)
4473 void VM_vectorvectors (void)
4475 prvm_eval_t *valforward, *valright, *valup;
4476 valforward = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.v_forward);
4477 valright = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.v_right);
4478 valup = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.v_up);
4479 if (!valforward || !valright || !valup)
4481 VM_Warning("vectorvectors: could not find v_forward, v_right, or v_up global variables\n");
4484 VM_SAFEPARMCOUNT(1, VM_vectorvectors);
4485 VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), valforward->vector);
4486 VectorVectors(valforward->vector, valright->vector, valup->vector);
4490 ========================
4493 void drawline(float width, vector pos1, vector pos2, vector rgb, float alpha, float flags)
4494 ========================
4496 void VM_drawline (void)
4498 float *c1, *c2, *rgb;
4500 unsigned char flags;
4502 VM_SAFEPARMCOUNT(6, VM_drawline);
4503 width = PRVM_G_FLOAT(OFS_PARM0);
4504 c1 = PRVM_G_VECTOR(OFS_PARM1);
4505 c2 = PRVM_G_VECTOR(OFS_PARM2);
4506 rgb = PRVM_G_VECTOR(OFS_PARM3);
4507 alpha = PRVM_G_FLOAT(OFS_PARM4);
4508 flags = (int)PRVM_G_FLOAT(OFS_PARM5);
4509 DrawQ_Line(width, c1[0], c1[1], c2[0], c2[1], rgb[0], rgb[1], rgb[2], alpha, flags);
4512 // float(float number, float quantity) bitshift (EXT_BITSHIFT)
4513 void VM_bitshift (void)
4516 VM_SAFEPARMCOUNT(2, VM_bitshift);
4518 n1 = (int)fabs((float)((int)PRVM_G_FLOAT(OFS_PARM0)));
4519 n2 = (int)PRVM_G_FLOAT(OFS_PARM1);
4521 PRVM_G_FLOAT(OFS_RETURN) = n1;
4524 PRVM_G_FLOAT(OFS_RETURN) = (n1 >> -n2);
4526 PRVM_G_FLOAT(OFS_RETURN) = (n1 << n2);
4529 ////////////////////////////////////////
4530 // AltString functions
4531 ////////////////////////////////////////
4534 ========================
4537 float altstr_count(string)
4538 ========================
4540 void VM_altstr_count( void )
4542 const char *altstr, *pos;
4545 VM_SAFEPARMCOUNT( 1, VM_altstr_count );
4547 altstr = PRVM_G_STRING( OFS_PARM0 );
4548 //VM_CheckEmptyString( altstr );
4550 for( count = 0, pos = altstr ; *pos ; pos++ ) {
4551 if( *pos == '\\' ) {
4555 } else if( *pos == '\'' ) {
4560 PRVM_G_FLOAT( OFS_RETURN ) = (float) (count / 2);
4564 ========================
4567 string altstr_prepare(string)
4568 ========================
4570 void VM_altstr_prepare( void )
4573 const char *instr, *in;
4575 char outstr[VM_STRINGTEMP_LENGTH];
4577 VM_SAFEPARMCOUNT( 1, VM_altstr_prepare );
4579 instr = PRVM_G_STRING( OFS_PARM0 );
4581 for( out = outstr, in = instr, size = sizeof(outstr) - 1 ; size && *in ; size--, in++, out++ )
4590 PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
4594 ========================
4597 string altstr_get(string, float)
4598 ========================
4600 void VM_altstr_get( void )
4602 const char *altstr, *pos;
4605 char outstr[VM_STRINGTEMP_LENGTH];
4607 VM_SAFEPARMCOUNT( 2, VM_altstr_get );
4609 altstr = PRVM_G_STRING( OFS_PARM0 );
4611 count = (int)PRVM_G_FLOAT( OFS_PARM1 );
4612 count = count * 2 + 1;
4614 for( pos = altstr ; *pos && count ; pos++ )
4615 if( *pos == '\\' ) {
4618 } else if( *pos == '\'' )
4622 PRVM_G_INT( OFS_RETURN ) = 0;
4626 for( out = outstr, size = sizeof(outstr) - 1 ; size && *pos ; size--, pos++, out++ )
4627 if( *pos == '\\' ) {
4632 } else if( *pos == '\'' )
4638 PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
4642 ========================
4645 string altstr_set(string altstr, float num, string set)
4646 ========================
4648 void VM_altstr_set( void )
4651 const char *altstr, *str;
4654 char outstr[VM_STRINGTEMP_LENGTH];
4656 VM_SAFEPARMCOUNT( 3, VM_altstr_set );
4658 altstr = PRVM_G_STRING( OFS_PARM0 );
4660 num = (int)PRVM_G_FLOAT( OFS_PARM1 );
4662 str = PRVM_G_STRING( OFS_PARM2 );
4665 for( num = num * 2 + 1, in = altstr; *in && num; *out++ = *in++ )
4670 } else if( *in == '\'' ) {
4675 for( ; *str; *out++ = *str++ );
4676 // now jump over the old content
4678 if( *in == '\'' || (*in == '\\' && !*++in) )
4681 strlcpy(out, in, outstr + sizeof(outstr) - out);
4682 PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
4686 ========================
4689 string altstr_ins(string altstr, float num, string set)
4690 ========================
4692 void VM_altstr_ins(void)
4698 char outstr[VM_STRINGTEMP_LENGTH];
4700 VM_SAFEPARMCOUNT(3, VM_altstr_ins);
4702 in = PRVM_G_STRING( OFS_PARM0 );
4703 num = (int)PRVM_G_FLOAT( OFS_PARM1 );
4704 set = PRVM_G_STRING( OFS_PARM2 );
4707 for( num = num * 2 + 2 ; *in && num > 0 ; *out++ = *in++ )
4712 } else if( *in == '\'' ) {
4717 for( ; *set ; *out++ = *set++ );
4720 strlcpy(out, in, outstr + sizeof(outstr) - out);
4721 PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
4725 ////////////////////////////////////////
4726 // BufString functions
4727 ////////////////////////////////////////
4728 //[515]: string buffers support
4730 static size_t stringbuffers_sortlength;
4732 static void BufStr_Expand(prvm_stringbuffer_t *stringbuffer, int strindex)
4734 if (stringbuffer->max_strings <= strindex)
4736 char **oldstrings = stringbuffer->strings;
4737 stringbuffer->max_strings = max(stringbuffer->max_strings * 2, 128);
4738 while (stringbuffer->max_strings <= strindex)
4739 stringbuffer->max_strings *= 2;
4740 stringbuffer->strings = (char **) Mem_Alloc(prog->progs_mempool, stringbuffer->max_strings * sizeof(stringbuffer->strings[0]));
4741 if (stringbuffer->num_strings > 0)
4742 memcpy(stringbuffer->strings, oldstrings, stringbuffer->num_strings * sizeof(stringbuffer->strings[0]));
4744 Mem_Free(oldstrings);
4748 static void BufStr_Shrink(prvm_stringbuffer_t *stringbuffer)
4750 // reduce num_strings if there are empty string slots at the end
4751 while (stringbuffer->num_strings > 0 && stringbuffer->strings[stringbuffer->num_strings - 1] == NULL)
4752 stringbuffer->num_strings--;
4754 // if empty, free the string pointer array
4755 if (stringbuffer->num_strings == 0)
4757 stringbuffer->max_strings = 0;
4758 if (stringbuffer->strings)
4759 Mem_Free(stringbuffer->strings);
4760 stringbuffer->strings = NULL;
4764 static int BufStr_SortStringsUP (const void *in1, const void *in2)
4767 a = *((const char **) in1);
4768 b = *((const char **) in2);
4769 if(!a || !a[0]) return 1;
4770 if(!b || !b[0]) return -1;
4771 return strncmp(a, b, stringbuffers_sortlength);
4774 static int BufStr_SortStringsDOWN (const void *in1, const void *in2)
4777 a = *((const char **) in1);
4778 b = *((const char **) in2);
4779 if(!a || !a[0]) return 1;
4780 if(!b || !b[0]) return -1;
4781 return strncmp(b, a, stringbuffers_sortlength);
4785 ========================
4787 creates new buffer, and returns it's index, returns -1 if failed
4788 float buf_create(void) = #460;
4789 float newbuf(string format, float flags) = #460;
4790 ========================
4793 void VM_buf_create (void)
4795 prvm_stringbuffer_t *stringbuffer;
4798 VM_SAFEPARMCOUNTRANGE(0, 2, VM_buf_create);
4800 // VorteX: optional parm1 (buffer format) is unfinished, to keep intact with future databuffers extension must be set to "string"
4801 if(prog->argc >= 1 && strcmp(PRVM_G_STRING(OFS_PARM0), "string"))
4803 PRVM_G_FLOAT(OFS_RETURN) = -1;
4806 stringbuffer = (prvm_stringbuffer_t *) Mem_ExpandableArray_AllocRecord(&prog->stringbuffersarray);
4807 for (i = 0;stringbuffer != Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);i++);
4808 stringbuffer->origin = PRVM_AllocationOrigin();
4809 // optional flags parm
4810 if (prog->argc >= 2)
4811 stringbuffer->flags = (int)PRVM_G_FLOAT(OFS_PARM1) & 0xFF;
4812 PRVM_G_FLOAT(OFS_RETURN) = i;
4818 ========================
4820 deletes buffer and all strings in it
4821 void buf_del(float bufhandle) = #461;
4822 ========================
4824 void VM_buf_del (void)
4826 prvm_stringbuffer_t *stringbuffer;
4827 VM_SAFEPARMCOUNT(1, VM_buf_del);
4828 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4832 for (i = 0;i < stringbuffer->num_strings;i++)
4833 if (stringbuffer->strings[i])
4834 Mem_Free(stringbuffer->strings[i]);
4835 if (stringbuffer->strings)
4836 Mem_Free(stringbuffer->strings);
4837 if(stringbuffer->origin)
4838 PRVM_Free((char *)stringbuffer->origin);
4839 Mem_ExpandableArray_FreeRecord(&prog->stringbuffersarray, stringbuffer);
4843 VM_Warning("VM_buf_del: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4849 ========================
4851 how many strings are stored in buffer
4852 float buf_getsize(float bufhandle) = #462;
4853 ========================
4855 void VM_buf_getsize (void)
4857 prvm_stringbuffer_t *stringbuffer;
4858 VM_SAFEPARMCOUNT(1, VM_buf_getsize);
4860 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4863 PRVM_G_FLOAT(OFS_RETURN) = -1;
4864 VM_Warning("VM_buf_getsize: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4868 PRVM_G_FLOAT(OFS_RETURN) = stringbuffer->num_strings;
4872 ========================
4874 copy all content from one buffer to another, make sure it exists
4875 void buf_copy(float bufhandle_from, float bufhandle_to) = #463;
4876 ========================
4878 void VM_buf_copy (void)
4880 prvm_stringbuffer_t *srcstringbuffer, *dststringbuffer;
4882 VM_SAFEPARMCOUNT(2, VM_buf_copy);
4884 srcstringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4885 if(!srcstringbuffer)
4887 VM_Warning("VM_buf_copy: invalid source buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4890 i = (int)PRVM_G_FLOAT(OFS_PARM1);
4891 if(i == (int)PRVM_G_FLOAT(OFS_PARM0))
4893 VM_Warning("VM_buf_copy: source == destination (%i) in %s\n", i, PRVM_NAME);
4896 dststringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4897 if(!dststringbuffer)
4899 VM_Warning("VM_buf_copy: invalid destination buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), PRVM_NAME);
4903 for (i = 0;i < dststringbuffer->num_strings;i++)
4904 if (dststringbuffer->strings[i])
4905 Mem_Free(dststringbuffer->strings[i]);
4906 if (dststringbuffer->strings)
4907 Mem_Free(dststringbuffer->strings);
4908 *dststringbuffer = *srcstringbuffer;
4909 if (dststringbuffer->max_strings)
4910 dststringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(dststringbuffer->strings[0]) * dststringbuffer->max_strings);
4912 for (i = 0;i < dststringbuffer->num_strings;i++)
4914 if (srcstringbuffer->strings[i])
4917 stringlen = strlen(srcstringbuffer->strings[i]) + 1;
4918 dststringbuffer->strings[i] = (char *)Mem_Alloc(prog->progs_mempool, stringlen);
4919 memcpy(dststringbuffer->strings[i], srcstringbuffer->strings[i], stringlen);
4925 ========================
4927 sort buffer by beginnings of strings (cmplength defaults it's length)
4928 "backward == TRUE" means that sorting goes upside-down
4929 void buf_sort(float bufhandle, float cmplength, float backward) = #464;
4930 ========================
4932 void VM_buf_sort (void)
4934 prvm_stringbuffer_t *stringbuffer;
4935 VM_SAFEPARMCOUNT(3, VM_buf_sort);
4937 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4940 VM_Warning("VM_buf_sort: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4943 if(stringbuffer->num_strings <= 0)
4945 VM_Warning("VM_buf_sort: tried to sort empty buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4948 stringbuffers_sortlength = (int)PRVM_G_FLOAT(OFS_PARM1);
4949 if(stringbuffers_sortlength <= 0)
4950 stringbuffers_sortlength = 0x7FFFFFFF;
4952 if(!PRVM_G_FLOAT(OFS_PARM2))
4953 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsUP);
4955 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsDOWN);
4957 BufStr_Shrink(stringbuffer);
4961 ========================
4963 concantenates all buffer string into one with "glue" separator and returns it as tempstring
4964 string buf_implode(float bufhandle, string glue) = #465;
4965 ========================
4967 void VM_buf_implode (void)
4969 prvm_stringbuffer_t *stringbuffer;
4970 char k[VM_STRINGTEMP_LENGTH];
4974 VM_SAFEPARMCOUNT(2, VM_buf_implode);
4976 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4977 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4980 VM_Warning("VM_buf_implode: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4983 if(!stringbuffer->num_strings)
4985 sep = PRVM_G_STRING(OFS_PARM1);
4987 for(l = i = 0;i < stringbuffer->num_strings;i++)
4989 if(stringbuffer->strings[i])
4991 l += (i > 0 ? strlen(sep) : 0) + strlen(stringbuffer->strings[i]);
4992 if (l >= sizeof(k) - 1)
4994 strlcat(k, sep, sizeof(k));
4995 strlcat(k, stringbuffer->strings[i], sizeof(k));
4998 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(k);
5002 ========================
5004 get a string from buffer, returns tempstring, dont str_unzone it!
5005 string bufstr_get(float bufhandle, float string_index) = #465;
5006 ========================
5008 void VM_bufstr_get (void)
5010 prvm_stringbuffer_t *stringbuffer;
5012 VM_SAFEPARMCOUNT(2, VM_bufstr_get);
5014 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
5015 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
5018 VM_Warning("VM_bufstr_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
5021 strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
5024 // VM_Warning("VM_bufstr_get: invalid string index %i used in %s\n", strindex, PRVM_NAME);
5027 if (strindex < stringbuffer->num_strings && stringbuffer->strings[strindex])
5028 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(stringbuffer->strings[strindex]);
5032 ========================
5034 copies a string into selected slot of buffer
5035 void bufstr_set(float bufhandle, float string_index, string str) = #466;
5036 ========================
5038 void VM_bufstr_set (void)
5042 prvm_stringbuffer_t *stringbuffer;
5045 VM_SAFEPARMCOUNT(3, VM_bufstr_set);
5047 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
5050 VM_Warning("VM_bufstr_set: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
5053 strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
5054 if(strindex < 0 || strindex >= 1000000) // huge number of strings
5056 VM_Warning("VM_bufstr_set: invalid string index %i used in %s\n", strindex, PRVM_NAME);
5060 BufStr_Expand(stringbuffer, strindex);
5061 stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
5063 if(stringbuffer->strings[strindex])
5064 Mem_Free(stringbuffer->strings[strindex]);
5065 stringbuffer->strings[strindex] = NULL;
5067 if(PRVM_G_INT(OFS_PARM2))
5069 // not the NULL string!
5070 news = PRVM_G_STRING(OFS_PARM2);
5071 alloclen = strlen(news) + 1;
5072 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
5073 memcpy(stringbuffer->strings[strindex], news, alloclen);
5076 BufStr_Shrink(stringbuffer);
5080 ========================
5082 adds string to buffer in first free slot and returns its index
5083 "order == TRUE" means that string will be added after last "full" slot
5084 float bufstr_add(float bufhandle, string str, float order) = #467;
5085 ========================
5087 void VM_bufstr_add (void)
5089 int order, strindex;
5090 prvm_stringbuffer_t *stringbuffer;
5094 VM_SAFEPARMCOUNT(3, VM_bufstr_add);
5096 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
5097 PRVM_G_FLOAT(OFS_RETURN) = -1;
5100 VM_Warning("VM_bufstr_add: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
5103 if(!PRVM_G_INT(OFS_PARM1)) // NULL string
5105 VM_Warning("VM_bufstr_add: can not add an empty string to buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
5108 string = PRVM_G_STRING(OFS_PARM1);
5109 order = (int)PRVM_G_FLOAT(OFS_PARM2);
5111 strindex = stringbuffer->num_strings;
5113 for (strindex = 0;strindex < stringbuffer->num_strings;strindex++)
5114 if (stringbuffer->strings[strindex] == NULL)
5117 BufStr_Expand(stringbuffer, strindex);
5119 stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
5120 alloclen = strlen(string) + 1;
5121 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
5122 memcpy(stringbuffer->strings[strindex], string, alloclen);
5124 PRVM_G_FLOAT(OFS_RETURN) = strindex;
5128 ========================
5130 delete string from buffer
5131 void bufstr_free(float bufhandle, float string_index) = #468;
5132 ========================
5134 void VM_bufstr_free (void)
5137 prvm_stringbuffer_t *stringbuffer;
5138 VM_SAFEPARMCOUNT(2, VM_bufstr_free);
5140 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
5143 VM_Warning("VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
5146 i = (int)PRVM_G_FLOAT(OFS_PARM1);
5149 VM_Warning("VM_bufstr_free: invalid string index %i used in %s\n", i, PRVM_NAME);
5153 if (i < stringbuffer->num_strings)
5155 if(stringbuffer->strings[i])
5156 Mem_Free(stringbuffer->strings[i]);
5157 stringbuffer->strings[i] = NULL;
5160 BufStr_Shrink(stringbuffer);
5169 void VM_buf_cvarlist(void)
5172 const char *partial, *antipartial;
5173 size_t len, antilen;
5175 qboolean ispattern, antiispattern;
5177 prvm_stringbuffer_t *stringbuffer;
5178 VM_SAFEPARMCOUNTRANGE(2, 3, VM_buf_cvarlist);
5180 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
5183 VM_Warning("VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
5187 partial = PRVM_G_STRING(OFS_PARM1);
5191 len = strlen(partial);
5194 antipartial = PRVM_G_STRING(OFS_PARM2);
5200 antilen = strlen(antipartial);
5202 for (n = 0;n < stringbuffer->num_strings;n++)
5203 if (stringbuffer->strings[n])
5204 Mem_Free(stringbuffer->strings[n]);
5205 if (stringbuffer->strings)
5206 Mem_Free(stringbuffer->strings);
5207 stringbuffer->strings = NULL;
5209 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
5210 antiispattern = antipartial && (strchr(antipartial, '*') || strchr(antipartial, '?'));
5213 for(cvar = cvar_vars; cvar; cvar = cvar->next)
5215 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
5218 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
5224 stringbuffer->max_strings = stringbuffer->num_strings = n;
5225 if (stringbuffer->max_strings)
5226 stringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(stringbuffer->strings[0]) * stringbuffer->max_strings);
5229 for(cvar = cvar_vars; cvar; cvar = cvar->next)
5231 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
5234 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
5237 alloclen = strlen(cvar->name) + 1;
5238 stringbuffer->strings[n] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
5239 memcpy(stringbuffer->strings[n], cvar->name, alloclen);
5254 This was a major timewaster in progs, so it was converted to C
5257 void VM_changeyaw (void)
5260 float ideal, current, move, speed;
5262 // this is called (VERY HACKISHLY) by SV_MoveToGoal, so it can not use any
5263 // parameters because they are the parameters to SV_MoveToGoal, not this
5264 //VM_SAFEPARMCOUNT(0, VM_changeyaw);
5266 ent = PRVM_PROG_TO_EDICT(PRVM_GLOBALFIELDVALUE(prog->globaloffsets.self)->edict);
5267 if (ent == prog->edicts)
5269 VM_Warning("changeyaw: can not modify world entity\n");
5272 if (ent->priv.server->free)
5274 VM_Warning("changeyaw: can not modify free entity\n");
5277 if (prog->fieldoffsets.angles < 0 || prog->fieldoffsets.ideal_yaw < 0 || prog->fieldoffsets.yaw_speed < 0)
5279 VM_Warning("changeyaw: angles, ideal_yaw, or yaw_speed field(s) not found\n");
5282 current = ANGLEMOD(PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.angles)->vector[1]);
5283 ideal = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.ideal_yaw)->_float;
5284 speed = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.yaw_speed)->_float;
5286 if (current == ideal)
5288 move = ideal - current;
5289 if (ideal > current)
5310 PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.angles)->vector[1] = ANGLEMOD (current + move);
5318 void VM_changepitch (void)
5321 float ideal, current, move, speed;
5323 VM_SAFEPARMCOUNT(1, VM_changepitch);
5325 ent = PRVM_G_EDICT(OFS_PARM0);
5326 if (ent == prog->edicts)
5328 VM_Warning("changepitch: can not modify world entity\n");
5331 if (ent->priv.server->free)
5333 VM_Warning("changepitch: can not modify free entity\n");
5336 if (prog->fieldoffsets.angles < 0 || prog->fieldoffsets.idealpitch < 0 || prog->fieldoffsets.pitch_speed < 0)
5338 VM_Warning("changepitch: angles, idealpitch, or pitch_speed field(s) not found\n");
5341 current = ANGLEMOD(PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.angles)->vector[0]);
5342 ideal = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.idealpitch)->_float;
5343 speed = PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.pitch_speed)->_float;
5345 if (current == ideal)
5347 move = ideal - current;
5348 if (ideal > current)
5369 PRVM_EDICTFIELDVALUE(ent, prog->fieldoffsets.angles)->vector[0] = ANGLEMOD (current + move);
5373 void VM_uncolorstring (void)
5375 char szNewString[VM_STRINGTEMP_LENGTH];
5376 const char *szString;
5379 VM_SAFEPARMCOUNT(1, VM_uncolorstring);
5380 szString = PRVM_G_STRING(OFS_PARM0);
5381 COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), TRUE);
5382 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
5386 // #221 float(string str, string sub[, float startpos]) strstrofs (FTE_STRINGS)
5387 //strstr, without generating a new string. Use in conjunction with FRIK_FILE's substring for more similar strstr.
5388 void VM_strstrofs (void)
5390 const char *instr, *match;
5392 VM_SAFEPARMCOUNTRANGE(2, 3, VM_strstrofs);
5393 instr = PRVM_G_STRING(OFS_PARM0);
5394 match = PRVM_G_STRING(OFS_PARM1);
5395 firstofs = (prog->argc > 2)?(int)PRVM_G_FLOAT(OFS_PARM2):0;
5396 firstofs = u8_bytelen(instr, firstofs);
5398 if (firstofs && (firstofs < 0 || firstofs > (int)strlen(instr)))
5400 PRVM_G_FLOAT(OFS_RETURN) = -1;
5404 match = strstr(instr+firstofs, match);
5406 PRVM_G_FLOAT(OFS_RETURN) = -1;
5408 PRVM_G_FLOAT(OFS_RETURN) = u8_strnlen(instr, match-instr);
5411 //#222 string(string s, float index) str2chr (FTE_STRINGS)
5412 void VM_str2chr (void)
5417 VM_SAFEPARMCOUNT(2, VM_str2chr);
5418 s = PRVM_G_STRING(OFS_PARM0);
5419 index = u8_bytelen(s, (int)PRVM_G_FLOAT(OFS_PARM1));
5421 if((unsigned)index < strlen(s))
5423 if (utf8_enable.integer)
5424 ch = u8_getchar_noendptr(s + index);
5426 ch = (unsigned char)s[index];
5427 PRVM_G_FLOAT(OFS_RETURN) = ch;
5430 PRVM_G_FLOAT(OFS_RETURN) = 0;
5433 //#223 string(float c, ...) chr2str (FTE_STRINGS)
5434 void VM_chr2str (void)
5439 VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
5440 for(i = 0;i < prog->argc && i < (int)sizeof(t) - 1;i++)
5441 t[i] = (unsigned char)PRVM_G_FLOAT(OFS_PARM0+i*3);
5443 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(t);
5448 VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
5449 for(i = 0; i < prog->argc && len < sizeof(t)-1; ++i)
5450 len += u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0+i*3), t + len, sizeof(t)-1);
5452 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(t);
5455 static int chrconv_number(int i, int base, int conv)
5480 static int chrconv_punct(int i, int base, int conv)
5498 static int chrchar_alpha(int i, int basec, int baset, int convc, int convt, int charnum)
5500 //convert case and colour seperatly...
5517 baset = 128*((charnum&1) == (convt-5));
5533 return i + basec + baset;
5535 // #224 string(float ccase, float calpha, float cnum, string s, ...) strconv (FTE_STRINGS)
5536 //bulk convert a string. change case or colouring.
5537 void VM_strconv (void)
5539 int ccase, redalpha, rednum, len, i;
5540 unsigned char resbuf[VM_STRINGTEMP_LENGTH];
5541 unsigned char *result = resbuf;
5543 VM_SAFEPARMCOUNTRANGE(3, 8, VM_strconv);
5545 ccase = (int) PRVM_G_FLOAT(OFS_PARM0); //0 same, 1 lower, 2 upper
5546 redalpha = (int) PRVM_G_FLOAT(OFS_PARM1); //0 same, 1 white, 2 red, 5 alternate, 6 alternate-alternate
5547 rednum = (int) PRVM_G_FLOAT(OFS_PARM2); //0 same, 1 white, 2 red, 3 redspecial, 4 whitespecial, 5 alternate, 6 alternate-alternate
5548 VM_VarString(3, (char *) resbuf, sizeof(resbuf));
5549 len = strlen((char *) resbuf);
5551 for (i = 0; i < len; i++, result++) //should this be done backwards?
5553 if (*result >= '0' && *result <= '9') //normal numbers...
5554 *result = chrconv_number(*result, '0', rednum);
5555 else if (*result >= '0'+128 && *result <= '9'+128)
5556 *result = chrconv_number(*result, '0'+128, rednum);
5557 else if (*result >= '0'+128-30 && *result <= '9'+128-30)
5558 *result = chrconv_number(*result, '0'+128-30, rednum);
5559 else if (*result >= '0'-30 && *result <= '9'-30)
5560 *result = chrconv_number(*result, '0'-30, rednum);
5562 else if (*result >= 'a' && *result <= 'z') //normal numbers...
5563 *result = chrchar_alpha(*result, 'a', 0, ccase, redalpha, i);
5564 else if (*result >= 'A' && *result <= 'Z') //normal numbers...
5565 *result = chrchar_alpha(*result, 'A', 0, ccase, redalpha, i);
5566 else if (*result >= 'a'+128 && *result <= 'z'+128) //normal numbers...
5567 *result = chrchar_alpha(*result, 'a', 128, ccase, redalpha, i);
5568 else if (*result >= 'A'+128 && *result <= 'Z'+128) //normal numbers...
5569 *result = chrchar_alpha(*result, 'A', 128, ccase, redalpha, i);
5571 else if ((*result & 127) < 16 || !redalpha) //special chars..
5573 else if (*result < 128)
5574 *result = chrconv_punct(*result, 0, redalpha);
5576 *result = chrconv_punct(*result, 128, redalpha);
5580 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString((char *) resbuf);
5583 // #225 string(float chars, string s, ...) strpad (FTE_STRINGS)
5584 void VM_strpad (void)
5586 char src[VM_STRINGTEMP_LENGTH];
5587 char destbuf[VM_STRINGTEMP_LENGTH];
5589 VM_SAFEPARMCOUNTRANGE(1, 8, VM_strpad);
5590 pad = (int) PRVM_G_FLOAT(OFS_PARM0);
5591 VM_VarString(1, src, sizeof(src));
5593 // note: < 0 = left padding, > 0 = right padding,
5594 // this is reverse logic of printf!
5595 dpsnprintf(destbuf, sizeof(destbuf), "%*s", -pad, src);
5597 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(destbuf);
5600 // #226 string(string info, string key, string value, ...) infoadd (FTE_STRINGS)
5601 //uses qw style \key\value strings
5602 void VM_infoadd (void)
5604 const char *info, *key;
5605 char value[VM_STRINGTEMP_LENGTH];
5606 char temp[VM_STRINGTEMP_LENGTH];
5608 VM_SAFEPARMCOUNTRANGE(2, 8, VM_infoadd);
5609 info = PRVM_G_STRING(OFS_PARM0);
5610 key = PRVM_G_STRING(OFS_PARM1);
5611 VM_VarString(2, value, sizeof(value));
5613 strlcpy(temp, info, VM_STRINGTEMP_LENGTH);
5615 InfoString_SetValue(temp, VM_STRINGTEMP_LENGTH, key, value);
5617 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(temp);
5620 // #227 string(string info, string key) infoget (FTE_STRINGS)
5621 //uses qw style \key\value strings
5622 void VM_infoget (void)
5626 char value[VM_STRINGTEMP_LENGTH];
5628 VM_SAFEPARMCOUNT(2, VM_infoget);
5629 info = PRVM_G_STRING(OFS_PARM0);
5630 key = PRVM_G_STRING(OFS_PARM1);
5632 InfoString_GetValue(info, key, value, VM_STRINGTEMP_LENGTH);
5634 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(value);
5637 //#228 float(string s1, string s2, float len) strncmp (FTE_STRINGS)
5638 // also float(string s1, string s2) strcmp (FRIK_FILE)
5639 void VM_strncmp (void)
5641 const char *s1, *s2;
5642 VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncmp);
5643 s1 = PRVM_G_STRING(OFS_PARM0);
5644 s2 = PRVM_G_STRING(OFS_PARM1);
5647 PRVM_G_FLOAT(OFS_RETURN) = strncmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5651 PRVM_G_FLOAT(OFS_RETURN) = strcmp(s1, s2);
5655 // #229 float(string s1, string s2) strcasecmp (FTE_STRINGS)
5656 // #230 float(string s1, string s2, float len) strncasecmp (FTE_STRINGS)
5657 void VM_strncasecmp (void)
5659 const char *s1, *s2;
5660 VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncasecmp);
5661 s1 = PRVM_G_STRING(OFS_PARM0);
5662 s2 = PRVM_G_STRING(OFS_PARM1);
5665 PRVM_G_FLOAT(OFS_RETURN) = strncasecmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5669 PRVM_G_FLOAT(OFS_RETURN) = strcasecmp(s1, s2);
5673 // #494 float(float caseinsensitive, string s, ...) crc16
5677 static char s[VM_STRINGTEMP_LENGTH];
5678 VM_SAFEPARMCOUNTRANGE(2, 8, VM_hash);
5679 insensitive = PRVM_G_FLOAT(OFS_PARM0);
5680 VM_VarString(1, s, sizeof(s));
5681 PRVM_G_FLOAT(OFS_RETURN) = (unsigned short) ((insensitive ? CRC_Block_CaseInsensitive : CRC_Block) ((unsigned char *) s, strlen(s)));
5684 void VM_wasfreed (void)
5686 VM_SAFEPARMCOUNT(1, VM_wasfreed);
5687 PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICT(OFS_PARM0)->priv.required->free;
5690 void VM_SetTraceGlobals(const trace_t *trace)
5693 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_allsolid)))
5694 val->_float = trace->allsolid;
5695 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_startsolid)))
5696 val->_float = trace->startsolid;
5697 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_fraction)))
5698 val->_float = trace->fraction;
5699 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_inwater)))
5700 val->_float = trace->inwater;
5701 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_inopen)))
5702 val->_float = trace->inopen;
5703 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_endpos)))
5704 VectorCopy(trace->endpos, val->vector);
5705 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_plane_normal)))
5706 VectorCopy(trace->plane.normal, val->vector);
5707 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_plane_dist)))
5708 val->_float = trace->plane.dist;
5709 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_ent)))
5710 val->edict = PRVM_EDICT_TO_PROG(trace->ent ? trace->ent : prog->edicts);
5711 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dpstartcontents)))
5712 val->_float = trace->startsupercontents;
5713 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dphitcontents)))
5714 val->_float = trace->hitsupercontents;
5715 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dphitq3surfaceflags)))
5716 val->_float = trace->hitq3surfaceflags;
5717 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dphittexturename)))
5718 val->string = trace->hittexture ? PRVM_SetTempString(trace->hittexture->name) : 0;
5721 void VM_ClearTraceGlobals(void)
5723 // clean up all trace globals when leaving the VM (anti-triggerbot safeguard)
5725 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_allsolid)))
5727 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_startsolid)))
5729 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_fraction)))
5731 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_inwater)))
5733 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_inopen)))
5735 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_endpos)))
5736 VectorClear(val->vector);
5737 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_plane_normal)))
5738 VectorClear(val->vector);
5739 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_plane_dist)))
5741 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_ent)))
5742 val->edict = PRVM_EDICT_TO_PROG(prog->edicts);
5743 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dpstartcontents)))
5745 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dphitcontents)))
5747 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dphitq3surfaceflags)))
5749 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_dphittexturename)))
5755 void VM_Cmd_Init(void)
5757 // only init the stuff for the current prog
5761 // VM_BufStr_Init();
5764 void VM_Cmd_Reset(void)
5766 CL_PurgeOwner( MENUOWNER );
5768 VM_Files_CloseAll();
5770 // VM_BufStr_ShutDown();
5773 // #510 string(string input, ...) uri_escape (DP_QC_URI_ESCAPE)
5774 // does URI escaping on a string (replace evil stuff by %AB escapes)
5775 void VM_uri_escape (void)
5777 char src[VM_STRINGTEMP_LENGTH];
5778 char dest[VM_STRINGTEMP_LENGTH];
5780 static const char *hex = "0123456789ABCDEF";
5782 VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_escape);
5783 VM_VarString(0, src, sizeof(src));
5785 for(p = src, q = dest; *p && q < dest + sizeof(dest) - 3; ++p)
5787 if((*p >= 'A' && *p <= 'Z')
5788 || (*p >= 'a' && *p <= 'z')
5789 || (*p >= '0' && *p <= '9')
5790 || (*p == '-') || (*p == '_') || (*p == '.')
5791 || (*p == '!') || (*p == '~')
5792 || (*p == '\'') || (*p == '(') || (*p == ')'))
5797 *q++ = hex[(*(unsigned char *)p >> 4) & 0xF];
5798 *q++ = hex[ *(unsigned char *)p & 0xF];
5803 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(dest);
5806 // #510 string(string input, ...) uri_unescape (DP_QC_URI_ESCAPE)
5807 // does URI unescaping on a string (get back the evil stuff)
5808 void VM_uri_unescape (void)
5810 char src[VM_STRINGTEMP_LENGTH];
5811 char dest[VM_STRINGTEMP_LENGTH];
5815 VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_unescape);
5816 VM_VarString(0, src, sizeof(src));
5818 for(p = src, q = dest; *p; ) // no need to check size, because unescape can't expand
5822 if(p[1] >= '0' && p[1] <= '9')
5824 else if(p[1] >= 'a' && p[1] <= 'f')
5825 hi = p[1] - 'a' + 10;
5826 else if(p[1] >= 'A' && p[1] <= 'F')
5827 hi = p[1] - 'A' + 10;
5830 if(p[2] >= '0' && p[2] <= '9')
5832 else if(p[2] >= 'a' && p[2] <= 'f')
5833 lo = p[2] - 'a' + 10;
5834 else if(p[2] >= 'A' && p[2] <= 'F')
5835 lo = p[2] - 'A' + 10;
5838 if(hi != 0 || lo != 0) // don't unescape NUL bytes
5839 *q++ = (char) (hi * 0x10 + lo);
5850 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(dest);
5853 // #502 string(string filename) whichpack (DP_QC_WHICHPACK)
5854 // returns the name of the pack containing a file, or "" if it is not in any pack (but local or non-existant)
5855 void VM_whichpack (void)
5857 const char *fn, *pack;
5859 VM_SAFEPARMCOUNT(1, VM_whichpack);
5860 fn = PRVM_G_STRING(OFS_PARM0);
5861 pack = FS_WhichPack(fn);
5863 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(pack ? pack : "");
5871 char buffer[MAX_INPUTLINE];
5872 unsigned char *postdata; // free when uri_to_prog_t is freed
5874 char *sigdata; // free when uri_to_prog_t is freed
5879 static void uri_to_string_callback(int status, size_t length_received, unsigned char *buffer, void *cbdata)
5881 uri_to_prog_t *handle = (uri_to_prog_t *) cbdata;
5883 if(!PRVM_ProgLoaded(handle->prognr))
5885 // curl reply came too late... so just drop it
5886 if(handle->postdata)
5887 Z_Free(handle->postdata);
5889 Z_Free(handle->sigdata);
5894 PRVM_SetProg(handle->prognr);
5896 if((prog->starttime == handle->starttime) && (prog->funcoffsets.URI_Get_Callback))
5898 if(length_received >= sizeof(handle->buffer))
5899 length_received = sizeof(handle->buffer) - 1;
5900 handle->buffer[length_received] = 0;
5902 PRVM_G_FLOAT(OFS_PARM0) = handle->id;
5903 PRVM_G_FLOAT(OFS_PARM1) = status;
5904 PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(handle->buffer);
5905 PRVM_ExecuteProgram(prog->funcoffsets.URI_Get_Callback, "QC function URI_Get_Callback is missing");
5909 if(handle->postdata)
5910 Z_Free(handle->postdata);
5912 Z_Free(handle->sigdata);
5916 // 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
5917 // 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
5918 void VM_uri_get (void)
5923 uri_to_prog_t *handle;
5924 const char *posttype = NULL;
5925 const char *postseparator = NULL;
5926 int poststringbuffer = -1;
5928 const char *query_string = NULL;
5931 if(!prog->funcoffsets.URI_Get_Callback)
5932 PRVM_ERROR("uri_get called by %s without URI_Get_Callback defined", PRVM_NAME);
5934 VM_SAFEPARMCOUNTRANGE(2, 6, VM_uri_get);
5936 url = PRVM_G_STRING(OFS_PARM0);
5937 id = PRVM_G_FLOAT(OFS_PARM1);
5939 posttype = PRVM_G_STRING(OFS_PARM2);
5941 postseparator = PRVM_G_STRING(OFS_PARM3);
5943 poststringbuffer = PRVM_G_FLOAT(OFS_PARM4);
5945 postkeyid = PRVM_G_FLOAT(OFS_PARM5);
5946 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!
5948 query_string = strchr(url, '?');
5951 lq = query_string ? strlen(query_string) : 0;
5953 handle->prognr = PRVM_GetProgNr();
5954 handle->starttime = prog->starttime;
5958 size_t l = strlen(postseparator);
5959 if(poststringbuffer >= 0)
5964 prvm_stringbuffer_t *stringbuffer;
5965 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, poststringbuffer);
5968 VM_Warning("uri_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
5972 for(i = 0;i < stringbuffer->num_strings;i++)
5976 if(stringbuffer->strings[i])
5977 ltotal += strlen(stringbuffer->strings[i]);
5979 handle->postdata = (unsigned char *)Z_Malloc(ltotal + 1 + lq);
5980 handle->postlen = ltotal;
5982 for(i = 0;i < stringbuffer->num_strings;i++)
5986 memcpy(handle->postdata + ltotal, postseparator, l);
5989 if(stringbuffer->strings[i])
5991 memcpy(handle->postdata + ltotal, stringbuffer->strings[i], strlen(stringbuffer->strings[i]));
5992 ltotal += strlen(stringbuffer->strings[i]);
5995 if(ltotal != handle->postlen)
5996 PRVM_ERROR ("%s: string buffer content size mismatch, possible overrun", PRVM_NAME);
6000 handle->postdata = (unsigned char *)Z_Malloc(l + 1 + lq);
6001 handle->postlen = l;
6002 memcpy(handle->postdata, postseparator, l);
6004 handle->postdata[handle->postlen] = 0;
6006 memcpy(handle->postdata + handle->postlen + 1, query_string, lq);
6009 // POST: we sign postdata \0 query string
6011 handle->sigdata = (char *)Z_Malloc(8192);
6012 strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
6013 l = strlen(handle->sigdata);
6014 handle->siglen = Crypto_SignDataDetached(handle->postdata, handle->postlen + 1 + lq, postkeyid, handle->sigdata + l, 8192 - l);
6017 Z_Free(handle->sigdata);
6018 handle->sigdata = NULL;
6021 ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
6024 Z_Free(handle->sigdata);
6025 handle->sigdata = NULL;
6028 handle->siglen = l + ll;
6029 handle->sigdata[handle->siglen] = 0;
6032 ret = Curl_Begin_ToMemory_POST(url, handle->sigdata, 0, posttype, handle->postdata, handle->postlen, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
6036 if(postkeyid >= 0 && query_string)
6038 // GET: we sign JUST the query string
6040 handle->sigdata = (char *)Z_Malloc(8192);
6041 strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
6042 l = strlen(handle->sigdata);
6043 handle->siglen = Crypto_SignDataDetached(query_string, lq, postkeyid, handle->sigdata + l, 8192 - l);
6046 Z_Free(handle->sigdata);
6047 handle->sigdata = NULL;
6050 ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
6053 Z_Free(handle->sigdata);
6054 handle->sigdata = NULL;
6057 handle->siglen = l + ll;
6058 handle->sigdata[handle->siglen] = 0;
6061 handle->postdata = NULL;
6062 handle->postlen = 0;
6063 ret = Curl_Begin_ToMemory(url, 0, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
6067 PRVM_G_INT(OFS_RETURN) = 1;
6071 if(handle->postdata)
6072 Z_Free(handle->postdata);
6074 Z_Free(handle->sigdata);
6076 PRVM_G_INT(OFS_RETURN) = 0;
6080 void VM_netaddress_resolve (void)
6083 char normalized[128];
6085 lhnetaddress_t addr;
6087 VM_SAFEPARMCOUNTRANGE(1, 2, VM_netaddress_resolve);
6089 ip = PRVM_G_STRING(OFS_PARM0);
6092 port = (int) PRVM_G_FLOAT(OFS_PARM1);
6094 if(LHNETADDRESS_FromString(&addr, ip, port) && LHNETADDRESS_ToString(&addr, normalized, sizeof(normalized), prog->argc > 1))
6095 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(normalized);
6097 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
6100 //string(void) getextresponse = #624; // returns the next extResponse packet that was sent to this client
6101 void VM_CL_getextresponse (void)
6103 VM_SAFEPARMCOUNT(0,VM_argv);
6105 if (cl_net_extresponse_count <= 0)
6106 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
6110 --cl_net_extresponse_count;
6111 first = (cl_net_extresponse_last + NET_EXTRESPONSE_MAX - cl_net_extresponse_count) % NET_EXTRESPONSE_MAX;
6112 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(cl_net_extresponse[first]);
6116 void VM_SV_getextresponse (void)
6118 VM_SAFEPARMCOUNT(0,VM_argv);
6120 if (sv_net_extresponse_count <= 0)
6121 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
6125 --sv_net_extresponse_count;
6126 first = (sv_net_extresponse_last + NET_EXTRESPONSE_MAX - sv_net_extresponse_count) % NET_EXTRESPONSE_MAX;
6127 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(sv_net_extresponse[first]);
6133 Common functions between menu.dat and clsprogs
6137 //#349 float() isdemo
6138 void VM_CL_isdemo (void)
6140 VM_SAFEPARMCOUNT(0, VM_CL_isdemo);
6141 PRVM_G_FLOAT(OFS_RETURN) = cls.demoplayback;
6144 //#355 float() videoplaying
6145 void VM_CL_videoplaying (void)
6147 VM_SAFEPARMCOUNT(0, VM_CL_videoplaying);
6148 PRVM_G_FLOAT(OFS_RETURN) = cl_videoplaying;
6155 callfunction(...,string function_name)
6159 mfunction_t *PRVM_ED_FindFunction (const char *name);
6160 void VM_callfunction(void)
6165 VM_SAFEPARMCOUNTRANGE(1, 8, VM_callfunction);
6167 s = PRVM_G_STRING(OFS_PARM0+(prog->argc - 1)*3);
6169 VM_CheckEmptyString(s);
6171 func = PRVM_ED_FindFunction(s);
6174 PRVM_ERROR("VM_callfunciton: function %s not found !", s);
6175 else if (func->first_statement < 0)
6177 // negative statements are built in functions
6178 int builtinnumber = -func->first_statement;
6179 prog->xfunction->builtinsprofile++;
6180 if (builtinnumber < prog->numbuiltins && prog->builtins[builtinnumber])
6181 prog->builtins[builtinnumber]();
6183 PRVM_ERROR("No such builtin #%i in %s; most likely cause: outdated engine build. Try updating!", builtinnumber, PRVM_NAME);
6185 else if(func - prog->functions > 0)
6188 PRVM_ExecuteProgram(func - prog->functions,"");
6197 float isfunction(string function_name)
6200 mfunction_t *PRVM_ED_FindFunction (const char *name);
6201 void VM_isfunction(void)
6206 VM_SAFEPARMCOUNT(1, VM_isfunction);
6208 s = PRVM_G_STRING(OFS_PARM0);
6210 VM_CheckEmptyString(s);
6212 func = PRVM_ED_FindFunction(s);
6215 PRVM_G_FLOAT(OFS_RETURN) = false;
6217 PRVM_G_FLOAT(OFS_RETURN) = true;
6224 string sprintf(string format, ...)
6228 void VM_sprintf(void)
6231 char outbuf[MAX_INPUTLINE];
6232 char *o = outbuf, *end = outbuf + sizeof(outbuf), *err;
6234 int width, precision, thisarg, flags;
6238 static int dummyivec[3] = {0, 0, 0};
6239 static float dummyvec[3] = {0, 0, 0};
6241 #define PRINTF_ALTERNATE 1
6242 #define PRINTF_ZEROPAD 2
6243 #define PRINTF_LEFT 4
6244 #define PRINTF_SPACEPOSITIVE 8
6245 #define PRINTF_SIGNPOSITIVE 16
6249 s = PRVM_G_STRING(OFS_PARM0);
6251 #define GETARG_FLOAT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_FLOAT(OFS_PARM0 + 3 * (a))) : 0)
6252 #define GETARG_VECTOR(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyvec)
6253 #define GETARG_INT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_INT(OFS_PARM0 + 3 * (a))) : 0)
6254 #define GETARG_INTVECTOR(a) (((a)>=1 && (a)<prog->argc) ? ((int*) PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyivec)
6255 #define GETARG_STRING(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_STRING(OFS_PARM0 + 3 * (a))) : "")
6270 // complete directive format:
6279 // is number following?
6280 if(*s >= '0' && *s <= '9')
6282 width = strtol(s, &err, 10);
6285 VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6298 flags |= PRINTF_ZEROPAD;
6300 width = -1; // it was just a flag
6312 case '#': flags |= PRINTF_ALTERNATE; break;
6313 case '0': flags |= PRINTF_ZEROPAD; break;
6314 case '-': flags |= PRINTF_LEFT; break;
6315 case ' ': flags |= PRINTF_SPACEPOSITIVE; break;
6316 case '+': flags |= PRINTF_SIGNPOSITIVE; break;
6326 if(*s >= '0' && *s <= '9')
6328 width = strtol(s, &err, 10);
6329 if(!err || *err != '$')
6331 VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6338 width = GETARG_FLOAT(width);
6341 flags |= PRINTF_LEFT;
6345 else if(*s >= '0' && *s <= '9')
6347 width = strtol(s, &err, 10);
6350 VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6356 flags |= PRINTF_LEFT;
6360 // otherwise width stays -1
6369 if(*s >= '0' && *s <= '9')
6371 precision = strtol(s, &err, 10);
6372 if(!err || *err != '$')
6374 VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6380 precision = argpos++;
6381 precision = GETARG_FLOAT(precision);
6383 else if(*s >= '0' && *s <= '9')
6385 precision = strtol(s, &err, 10);
6388 VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6395 VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6404 case 'h': isfloat = 1; break;
6405 case 'l': isfloat = 0; break;
6406 case 'L': isfloat = 0; break;
6417 // now s points to the final directive char and is no longer changed
6432 if(*s != 's' && *s != 'c')
6433 if(flags & PRINTF_ALTERNATE) *f++ = '#';
6434 if(flags & PRINTF_ZEROPAD) *f++ = '0';
6435 if(flags & PRINTF_LEFT) *f++ = '-';
6436 if(flags & PRINTF_SPACEPOSITIVE) *f++ = ' ';
6437 if(flags & PRINTF_SIGNPOSITIVE) *f++ = '+';
6447 if(width < 0) // not set
6453 if(precision < 0) // not set
6454 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (int) GETARG_FLOAT(thisarg) : (int) GETARG_INT(thisarg)));
6456 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (int) GETARG_FLOAT(thisarg) : (int) GETARG_INT(thisarg)));
6458 case 'o': case 'u': case 'x': case 'X':
6459 if(precision < 0) // not set
6460 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6462 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6464 case 'e': case 'E': case 'f': case 'F': case 'g': case 'G':
6465 if(precision < 0) // not set
6466 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6468 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6472 if(precision < 0) // not set
6473 o += dpsnprintf(o, end - o, va("%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6474 width, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6475 width, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6476 width, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6479 o += dpsnprintf(o, end - o, va("%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6480 width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6481 width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6482 width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6486 if(flags & PRINTF_ALTERNATE)
6488 if(precision < 0) // not set
6489 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6491 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6495 unsigned int c = (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg));
6496 const char *buf = u8_encodech(c, NULL);
6499 if(precision < 0) // not set
6500 precision = end - o - 1;
6501 o += u8_strpad(o, end - o, buf, (flags & PRINTF_LEFT) != 0, width, precision);
6505 if(flags & PRINTF_ALTERNATE)
6507 if(precision < 0) // not set
6508 o += dpsnprintf(o, end - o, formatbuf, width, GETARG_STRING(thisarg));
6510 o += dpsnprintf(o, end - o, formatbuf, width, precision, GETARG_STRING(thisarg));
6514 if(precision < 0) // not set
6515 precision = end - o - 1;
6516 o += u8_strpad(o, end - o, GETARG_STRING(thisarg), (flags & PRINTF_LEFT) != 0, width, precision);
6520 VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6535 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(outbuf);
6541 static dp_model_t *getmodel(prvm_edict_t *ed)
6543 switch(PRVM_GetProgNr())
6545 case PRVM_SERVERPROG:
6546 return SV_GetModelFromEdict(ed);
6547 case PRVM_CLIENTPROG:
6548 return CL_GetModelFromEdict(ed);
6556 unsigned int progid;
6558 frameblend_t frameblend[MAX_FRAMEBLENDS];
6559 skeleton_t *skeleton_p;
6560 skeleton_t skeleton;
6561 float *data_vertex3f;
6562 float *data_svector3f;
6563 float *data_tvector3f;
6564 float *data_normal3f;
6566 float *buf_vertex3f;
6567 float *buf_svector3f;
6568 float *buf_tvector3f;
6569 float *buf_normal3f;
6571 animatemodel_cache_t;
6572 static animatemodel_cache_t animatemodel_cache;
6574 void animatemodel(dp_model_t *model, prvm_edict_t *ed)
6577 skeleton_t *skeleton;
6578 int skeletonindex = -1;
6579 qboolean need = false;
6580 if(!(model->surfmesh.isanimated && model->AnimateVertices))
6582 animatemodel_cache.data_vertex3f = model->surfmesh.data_vertex3f;
6583 animatemodel_cache.data_svector3f = model->surfmesh.data_svector3f;
6584 animatemodel_cache.data_tvector3f = model->surfmesh.data_tvector3f;
6585 animatemodel_cache.data_normal3f = model->surfmesh.data_normal3f;
6588 if(animatemodel_cache.progid != prog->id)
6589 memset(&animatemodel_cache, 0, sizeof(animatemodel_cache));
6590 need |= (animatemodel_cache.model != model);
6591 VM_GenerateFrameGroupBlend(ed->priv.server->framegroupblend, ed);
6592 VM_FrameBlendFromFrameGroupBlend(ed->priv.server->frameblend, ed->priv.server->framegroupblend, model);
6593 need |= (memcmp(&animatemodel_cache.frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend))) != 0;
6594 if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.skeletonindex))) skeletonindex = (int)val->_float - 1;
6595 if (!(skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones))
6597 need |= (animatemodel_cache.skeleton_p != skeleton);
6599 need |= (memcmp(&animatemodel_cache.skeleton, skeleton, sizeof(ed->priv.server->skeleton))) != 0;
6602 if(model->surfmesh.num_vertices > animatemodel_cache.max_vertices)
6604 animatemodel_cache.max_vertices = model->surfmesh.num_vertices * 2;
6605 if(animatemodel_cache.buf_vertex3f) Mem_Free(animatemodel_cache.buf_vertex3f);
6606 if(animatemodel_cache.buf_svector3f) Mem_Free(animatemodel_cache.buf_svector3f);
6607 if(animatemodel_cache.buf_tvector3f) Mem_Free(animatemodel_cache.buf_tvector3f);
6608 if(animatemodel_cache.buf_normal3f) Mem_Free(animatemodel_cache.buf_normal3f);
6609 animatemodel_cache.buf_vertex3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6610 animatemodel_cache.buf_svector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6611 animatemodel_cache.buf_tvector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6612 animatemodel_cache.buf_normal3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6614 animatemodel_cache.data_vertex3f = animatemodel_cache.buf_vertex3f;
6615 animatemodel_cache.data_svector3f = animatemodel_cache.buf_svector3f;
6616 animatemodel_cache.data_tvector3f = animatemodel_cache.buf_tvector3f;
6617 animatemodel_cache.data_normal3f = animatemodel_cache.buf_normal3f;
6618 VM_UpdateEdictSkeleton(ed, model, ed->priv.server->frameblend);
6619 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);
6620 animatemodel_cache.progid = prog->id;
6621 animatemodel_cache.model = model;
6622 memcpy(&animatemodel_cache.frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend));
6623 animatemodel_cache.skeleton_p = skeleton;
6625 memcpy(&animatemodel_cache.skeleton, skeleton, sizeof(ed->priv.server->skeleton));
6628 static void getmatrix(prvm_edict_t *ed, matrix4x4_t *out)
6630 switch(PRVM_GetProgNr())
6632 case PRVM_SERVERPROG:
6633 SV_GetEntityMatrix(ed, out, false);
6635 case PRVM_CLIENTPROG:
6636 CL_GetEntityMatrix(ed, out, false);
6639 *out = identitymatrix;
6644 static void applytransform_forward(const vec3_t in, prvm_edict_t *ed, vec3_t out)
6648 Matrix4x4_Transform(&m, in, out);
6651 static void applytransform_forward_direction(const vec3_t in, prvm_edict_t *ed, vec3_t out)
6655 Matrix4x4_Transform3x3(&m, in, out);
6658 static void applytransform_inverted(const vec3_t in, prvm_edict_t *ed, vec3_t out)
6662 Matrix4x4_Invert_Full(&n, &m);
6663 Matrix4x4_Transform3x3(&n, in, out);
6666 static void applytransform_forward_normal(const vec3_t in, prvm_edict_t *ed, vec3_t out)
6671 Matrix4x4_TransformPositivePlane(&m, in[0], in[1], in[2], 0, p);
6675 static void clippointtosurface(prvm_edict_t *ed, dp_model_t *model, msurface_t *surface, vec3_t p, vec3_t out)
6678 float *v[3], facenormal[3], edgenormal[3], sidenormal[3], temp[3], offsetdist, dist, bestdist;
6680 animatemodel(model, ed);
6681 bestdist = 1000000000;
6683 for (i = 0, e = (model->surfmesh.data_element3i + 3 * surface->num_firsttriangle);i < surface->num_triangles;i++, e += 3)
6685 // clip original point to each triangle of the surface and find the
6686 // triangle that is closest
6687 v[0] = animatemodel_cache.data_vertex3f + e[0] * 3;
6688 v[1] = animatemodel_cache.data_vertex3f + e[1] * 3;
6689 v[2] = animatemodel_cache.data_vertex3f + e[2] * 3;
6690 TriangleNormal(v[0], v[1], v[2], facenormal);
6691 VectorNormalize(facenormal);
6692 offsetdist = DotProduct(v[0], facenormal) - DotProduct(p, facenormal);
6693 VectorMA(p, offsetdist, facenormal, temp);
6694 for (j = 0, k = 2;j < 3;k = j, j++)
6696 VectorSubtract(v[k], v[j], edgenormal);
6697 CrossProduct(edgenormal, facenormal, sidenormal);
6698 VectorNormalize(sidenormal);
6699 offsetdist = DotProduct(v[k], sidenormal) - DotProduct(temp, sidenormal);
6701 VectorMA(temp, offsetdist, sidenormal, temp);
6703 dist = VectorDistance2(temp, p);
6704 if (bestdist > dist)
6707 VectorCopy(temp, out);
6712 static msurface_t *getsurface(dp_model_t *model, int surfacenum)
6714 if (surfacenum < 0 || surfacenum >= model->nummodelsurfaces)
6716 return model->data_surfaces + surfacenum + model->firstmodelsurface;
6720 //PF_getsurfacenumpoints, // #434 float(entity e, float s) getsurfacenumpoints = #434;
6721 void VM_getsurfacenumpoints(void)
6724 msurface_t *surface;
6725 VM_SAFEPARMCOUNT(2, VM_getsurfacenumpoints);
6726 // return 0 if no such surface
6727 if (!(model = getmodel(PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6729 PRVM_G_FLOAT(OFS_RETURN) = 0;
6733 // note: this (incorrectly) assumes it is a simple polygon
6734 PRVM_G_FLOAT(OFS_RETURN) = surface->num_vertices;
6736 //PF_getsurfacepoint, // #435 vector(entity e, float s, float n) getsurfacepoint = #435;
6737 void VM_getsurfacepoint(void)
6741 msurface_t *surface;
6743 VM_SAFEPARMCOUNT(3, VM_getsurfacepoint);
6744 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6745 ed = PRVM_G_EDICT(OFS_PARM0);
6746 if (!(model = getmodel(ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6748 // note: this (incorrectly) assumes it is a simple polygon
6749 pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6750 if (pointnum < 0 || pointnum >= surface->num_vertices)
6752 animatemodel(model, ed);
6753 applytransform_forward(&(animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6755 //PF_getsurfacepointattribute, // #486 vector(entity e, float s, float n, float a) getsurfacepointattribute = #486;
6756 // float SPA_POSITION = 0;
6757 // float SPA_S_AXIS = 1;
6758 // float SPA_T_AXIS = 2;
6759 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6760 // float SPA_TEXCOORDS0 = 4;
6761 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6762 // float SPA_LIGHTMAP0_COLOR = 6;
6763 void VM_getsurfacepointattribute(void)
6767 msurface_t *surface;
6771 VM_SAFEPARMCOUNT(4, VM_getsurfacepoint);
6772 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6773 ed = PRVM_G_EDICT(OFS_PARM0);
6774 if (!(model = getmodel(ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6776 pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6777 if (pointnum < 0 || pointnum >= surface->num_vertices)
6779 attributetype = (int) PRVM_G_FLOAT(OFS_PARM3);
6781 animatemodel(model, ed);
6783 switch( attributetype ) {
6784 // float SPA_POSITION = 0;
6786 applytransform_forward(&(animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6788 // float SPA_S_AXIS = 1;
6790 applytransform_forward_direction(&(animatemodel_cache.data_svector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6792 // float SPA_T_AXIS = 2;
6794 applytransform_forward_direction(&(animatemodel_cache.data_tvector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6796 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6798 applytransform_forward_direction(&(animatemodel_cache.data_normal3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6800 // float SPA_TEXCOORDS0 = 4;
6802 float *ret = PRVM_G_VECTOR(OFS_RETURN);
6803 float *texcoord = &(model->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[pointnum * 2];
6804 ret[0] = texcoord[0];
6805 ret[1] = texcoord[1];
6809 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6811 float *ret = PRVM_G_VECTOR(OFS_RETURN);
6812 float *texcoord = &(model->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[pointnum * 2];
6813 ret[0] = texcoord[0];
6814 ret[1] = texcoord[1];
6818 // float SPA_LIGHTMAP0_COLOR = 6;
6820 // ignore alpha for now..
6821 VectorCopy( &(model->surfmesh.data_lightmapcolor4f + 4 * surface->num_firstvertex)[pointnum * 4], PRVM_G_VECTOR(OFS_RETURN));
6824 VectorSet( PRVM_G_VECTOR(OFS_RETURN), 0.0f, 0.0f, 0.0f );
6828 //PF_getsurfacenormal, // #436 vector(entity e, float s) getsurfacenormal = #436;
6829 void VM_getsurfacenormal(void)
6832 msurface_t *surface;
6834 VM_SAFEPARMCOUNT(2, VM_getsurfacenormal);
6835 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6836 if (!(model = getmodel(PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6838 // note: this only returns the first triangle, so it doesn't work very
6839 // well for curved surfaces or arbitrary meshes
6840 animatemodel(model, PRVM_G_EDICT(OFS_PARM0));
6841 TriangleNormal((animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex), (animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex) + 3, (animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex) + 6, normal);
6842 applytransform_forward_normal(normal, PRVM_G_EDICT(OFS_PARM0), PRVM_G_VECTOR(OFS_RETURN));
6843 VectorNormalize(PRVM_G_VECTOR(OFS_RETURN));
6845 //PF_getsurfacetexture, // #437 string(entity e, float s) getsurfacetexture = #437;
6846 void VM_getsurfacetexture(void)
6849 msurface_t *surface;
6850 VM_SAFEPARMCOUNT(2, VM_getsurfacetexture);
6851 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
6852 if (!(model = getmodel(PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6854 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(surface->texture->name);
6856 //PF_getsurfacenearpoint, // #438 float(entity e, vector p) getsurfacenearpoint = #438;
6857 void VM_getsurfacenearpoint(void)
6859 int surfacenum, best;
6861 vec_t dist, bestdist;
6864 msurface_t *surface;
6866 VM_SAFEPARMCOUNT(2, VM_getsurfacenearpoint);
6867 PRVM_G_FLOAT(OFS_RETURN) = -1;
6868 ed = PRVM_G_EDICT(OFS_PARM0);
6869 point = PRVM_G_VECTOR(OFS_PARM1);
6871 if (!ed || ed->priv.server->free)
6873 model = getmodel(ed);
6874 if (!model || !model->num_surfaces)
6877 animatemodel(model, ed);
6879 applytransform_inverted(point, ed, p);
6881 bestdist = 1000000000;
6882 for (surfacenum = 0;surfacenum < model->nummodelsurfaces;surfacenum++)
6884 surface = model->data_surfaces + surfacenum + model->firstmodelsurface;
6885 // first see if the nearest point on the surface's box is closer than the previous match
6886 clipped[0] = bound(surface->mins[0], p[0], surface->maxs[0]) - p[0];
6887 clipped[1] = bound(surface->mins[1], p[1], surface->maxs[1]) - p[1];
6888 clipped[2] = bound(surface->mins[2], p[2], surface->maxs[2]) - p[2];
6889 dist = VectorLength2(clipped);
6890 if (dist < bestdist)
6892 // it is, check the nearest point on the actual geometry
6893 clippointtosurface(ed, model, surface, p, clipped);
6894 VectorSubtract(clipped, p, clipped);
6895 dist += VectorLength2(clipped);
6896 if (dist < bestdist)
6898 // that's closer too, store it as the best match
6904 PRVM_G_FLOAT(OFS_RETURN) = best;
6906 //PF_getsurfaceclippedpoint, // #439 vector(entity e, float s, vector p) getsurfaceclippedpoint = #439;
6907 void VM_getsurfaceclippedpoint(void)
6911 msurface_t *surface;
6913 VM_SAFEPARMCOUNT(3, VM_te_getsurfaceclippedpoint);
6914 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6915 ed = PRVM_G_EDICT(OFS_PARM0);
6916 if (!(model = getmodel(ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6918 animatemodel(model, ed);
6919 applytransform_inverted(PRVM_G_VECTOR(OFS_PARM2), ed, p);
6920 clippointtosurface(ed, model, surface, p, out);
6921 VectorAdd(out, ed->fields.server->origin, PRVM_G_VECTOR(OFS_RETURN));
6924 //PF_getsurfacenumtriangles, // #??? float(entity e, float s) getsurfacenumtriangles = #???;
6925 void VM_getsurfacenumtriangles(void)
6928 msurface_t *surface;
6929 VM_SAFEPARMCOUNT(2, VM_SV_getsurfacenumtriangles);
6930 // return 0 if no such surface
6931 if (!(model = getmodel(PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6933 PRVM_G_FLOAT(OFS_RETURN) = 0;
6937 // note: this (incorrectly) assumes it is a simple polygon
6938 PRVM_G_FLOAT(OFS_RETURN) = surface->num_triangles;
6940 //PF_getsurfacetriangle, // #??? vector(entity e, float s, float n) getsurfacetriangle = #???;
6941 void VM_getsurfacetriangle(void)
6943 const vec3_t d = {-1, -1, -1};
6946 msurface_t *surface;
6948 VM_SAFEPARMCOUNT(3, VM_SV_getsurfacetriangle);
6949 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6950 ed = PRVM_G_EDICT(OFS_PARM0);
6951 if (!(model = getmodel(ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6953 trinum = (int)PRVM_G_FLOAT(OFS_PARM2);
6954 if (trinum < 0 || trinum >= surface->num_triangles)
6956 // FIXME: implement rotation/scaling
6957 VectorMA(&(model->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[trinum * 3], surface->num_firstvertex, d, PRVM_G_VECTOR(OFS_RETURN));
6964 void World_Physics_ApplyCmd(prvm_edict_t *ed, edict_odefunc_t *f);
6966 #define VM_physics_ApplyCmd(ed,f) if (!ed->priv.server->ode_body) VM_physics_newstackfunction(ed, f); else World_Physics_ApplyCmd(ed, f)
6968 edict_odefunc_t *VM_physics_newstackfunction(prvm_edict_t *ed, edict_odefunc_t *f)
6970 edict_odefunc_t *newfunc, *func;
6972 newfunc = (edict_odefunc_t *)Mem_Alloc(prog->progs_mempool, sizeof(edict_odefunc_t));
6973 memcpy(newfunc, f, sizeof(edict_odefunc_t));
6974 newfunc->next = NULL;
6975 if (!ed->priv.server->ode_func)
6976 ed->priv.server->ode_func = newfunc;
6979 for (func = ed->priv.server->ode_func; func->next; func = func->next);
6980 func->next = newfunc;
6985 // void(entity e, float physics_enabled) physics_enable = #;
6986 void VM_physics_enable(void)
6991 VM_SAFEPARMCOUNT(2, VM_physics_enable);
6992 ed = PRVM_G_EDICT(OFS_PARM0);
6995 if (developer.integer > 0)
6996 VM_Warning("VM_physics_enable: null entity!\n");
6999 // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
7000 if (ed->fields.server->movetype != MOVETYPE_PHYSICS)
7002 VM_Warning("VM_physics_enable: entity is not MOVETYPE_PHYSICS!\n");
7005 f.type = PRVM_G_FLOAT(OFS_PARM1) == 0 ? ODEFUNC_DISABLE : ODEFUNC_ENABLE;
7006 VM_physics_ApplyCmd(ed, &f);
7009 // void(entity e, vector force, vector relative_ofs) physics_addforce = #;
7010 void VM_physics_addforce(void)
7015 VM_SAFEPARMCOUNT(3, VM_physics_addforce);
7016 ed = PRVM_G_EDICT(OFS_PARM0);
7019 if (developer.integer > 0)
7020 VM_Warning("VM_physics_addforce: null entity!\n");
7023 // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
7024 if (ed->fields.server->movetype != MOVETYPE_PHYSICS)
7026 VM_Warning("VM_physics_addforce: entity is not MOVETYPE_PHYSICS!\n");
7029 f.type = ODEFUNC_RELFORCEATPOS;
7030 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
7031 VectorSubtract(ed->fields.server->origin, PRVM_G_VECTOR(OFS_PARM2), f.v2);
7032 VM_physics_ApplyCmd(ed, &f);
7035 // void(entity e, vector torque) physics_addtorque = #;
7036 void VM_physics_addtorque(void)
7041 VM_SAFEPARMCOUNT(2, VM_physics_addtorque);
7042 ed = PRVM_G_EDICT(OFS_PARM0);
7045 if (developer.integer > 0)
7046 VM_Warning("VM_physics_addtorque: null entity!\n");
7049 // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
7050 if (ed->fields.server->movetype != MOVETYPE_PHYSICS)
7052 VM_Warning("VM_physics_addtorque: entity is not MOVETYPE_PHYSICS!\n");
7055 f.type = ODEFUNC_RELTORQUE;
7056 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
7057 VM_physics_ApplyCmd(ed, &f);