]> git.xonotic.org Git - xonotic/darkplaces.git/blob - csprogs.c
physics: fix and refactor unsticking
[xonotic/darkplaces.git] / csprogs.c
1 /*
2 Copyright (C) 2006-2021 DarkPlaces contributors
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20
21 #include "quakedef.h"
22 #include "progsvm.h"
23 #include "clprogdefs.h"
24 #include "csprogs.h"
25 #include "cl_collision.h"
26 #include "snd_main.h"
27 #include "clvm_cmds.h"
28 #include "prvm_cmds.h"
29
30 //============================================================================
31 // Client prog handling
32 //[515]: omg !!! optimize it ! a lot of hacks here and there also :P
33
34 #define CSQC_RETURNVAL  prog->globals.fp[OFS_RETURN]
35
36 void CL_VM_PreventInformationLeaks(void)
37 {
38         prvm_prog_t *prog = CLVM_prog;
39
40         if(!prog->loaded)
41                 return;
42
43         VM_ClearTraceGlobals(prog);
44         PRVM_clientglobalfloat(trace_networkentity) = 0;
45 }
46
47 //[515]: these are required funcs
48 static const char *cl_required_func[] =
49 {
50         "CSQC_Init",
51         "CSQC_InputEvent",
52         "CSQC_UpdateView",
53         "CSQC_ConsoleCommand",
54 };
55
56 static int cl_numrequiredfunc = sizeof(cl_required_func) / sizeof(char*);
57
58 #define CL_REQFIELDS (sizeof(cl_reqfields) / sizeof(prvm_required_field_t))
59
60 prvm_required_field_t cl_reqfields[] =
61 {
62 #define PRVM_DECLARE_serverglobalfloat(x)
63 #define PRVM_DECLARE_serverglobalvector(x)
64 #define PRVM_DECLARE_serverglobalstring(x)
65 #define PRVM_DECLARE_serverglobaledict(x)
66 #define PRVM_DECLARE_serverglobalfunction(x)
67 #define PRVM_DECLARE_clientglobalfloat(x)
68 #define PRVM_DECLARE_clientglobalvector(x)
69 #define PRVM_DECLARE_clientglobalstring(x)
70 #define PRVM_DECLARE_clientglobaledict(x)
71 #define PRVM_DECLARE_clientglobalfunction(x)
72 #define PRVM_DECLARE_menuglobalfloat(x)
73 #define PRVM_DECLARE_menuglobalvector(x)
74 #define PRVM_DECLARE_menuglobalstring(x)
75 #define PRVM_DECLARE_menuglobaledict(x)
76 #define PRVM_DECLARE_menuglobalfunction(x)
77 #define PRVM_DECLARE_serverfieldfloat(x)
78 #define PRVM_DECLARE_serverfieldvector(x)
79 #define PRVM_DECLARE_serverfieldstring(x)
80 #define PRVM_DECLARE_serverfieldedict(x)
81 #define PRVM_DECLARE_serverfieldfunction(x)
82 #define PRVM_DECLARE_clientfieldfloat(x) {ev_float, #x },
83 #define PRVM_DECLARE_clientfieldvector(x) {ev_vector, #x },
84 #define PRVM_DECLARE_clientfieldstring(x) {ev_string, #x },
85 #define PRVM_DECLARE_clientfieldedict(x) {ev_entity, #x },
86 #define PRVM_DECLARE_clientfieldfunction(x) {ev_function, #x },
87 #define PRVM_DECLARE_menufieldfloat(x)
88 #define PRVM_DECLARE_menufieldvector(x)
89 #define PRVM_DECLARE_menufieldstring(x)
90 #define PRVM_DECLARE_menufieldedict(x)
91 #define PRVM_DECLARE_menufieldfunction(x)
92 #define PRVM_DECLARE_serverfunction(x)
93 #define PRVM_DECLARE_clientfunction(x)
94 #define PRVM_DECLARE_menufunction(x)
95 #define PRVM_DECLARE_field(x)
96 #define PRVM_DECLARE_global(x)
97 #define PRVM_DECLARE_function(x)
98 #include "prvm_offsets.h"
99 #undef PRVM_DECLARE_serverglobalfloat
100 #undef PRVM_DECLARE_serverglobalvector
101 #undef PRVM_DECLARE_serverglobalstring
102 #undef PRVM_DECLARE_serverglobaledict
103 #undef PRVM_DECLARE_serverglobalfunction
104 #undef PRVM_DECLARE_clientglobalfloat
105 #undef PRVM_DECLARE_clientglobalvector
106 #undef PRVM_DECLARE_clientglobalstring
107 #undef PRVM_DECLARE_clientglobaledict
108 #undef PRVM_DECLARE_clientglobalfunction
109 #undef PRVM_DECLARE_menuglobalfloat
110 #undef PRVM_DECLARE_menuglobalvector
111 #undef PRVM_DECLARE_menuglobalstring
112 #undef PRVM_DECLARE_menuglobaledict
113 #undef PRVM_DECLARE_menuglobalfunction
114 #undef PRVM_DECLARE_serverfieldfloat
115 #undef PRVM_DECLARE_serverfieldvector
116 #undef PRVM_DECLARE_serverfieldstring
117 #undef PRVM_DECLARE_serverfieldedict
118 #undef PRVM_DECLARE_serverfieldfunction
119 #undef PRVM_DECLARE_clientfieldfloat
120 #undef PRVM_DECLARE_clientfieldvector
121 #undef PRVM_DECLARE_clientfieldstring
122 #undef PRVM_DECLARE_clientfieldedict
123 #undef PRVM_DECLARE_clientfieldfunction
124 #undef PRVM_DECLARE_menufieldfloat
125 #undef PRVM_DECLARE_menufieldvector
126 #undef PRVM_DECLARE_menufieldstring
127 #undef PRVM_DECLARE_menufieldedict
128 #undef PRVM_DECLARE_menufieldfunction
129 #undef PRVM_DECLARE_serverfunction
130 #undef PRVM_DECLARE_clientfunction
131 #undef PRVM_DECLARE_menufunction
132 #undef PRVM_DECLARE_field
133 #undef PRVM_DECLARE_global
134 #undef PRVM_DECLARE_function
135 };
136
137 #define CL_REQGLOBALS (sizeof(cl_reqglobals) / sizeof(prvm_required_field_t))
138
139 prvm_required_field_t cl_reqglobals[] =
140 {
141 #define PRVM_DECLARE_serverglobalfloat(x)
142 #define PRVM_DECLARE_serverglobalvector(x)
143 #define PRVM_DECLARE_serverglobalstring(x)
144 #define PRVM_DECLARE_serverglobaledict(x)
145 #define PRVM_DECLARE_serverglobalfunction(x)
146 #define PRVM_DECLARE_clientglobalfloat(x) {ev_float, #x},
147 #define PRVM_DECLARE_clientglobalvector(x) {ev_vector, #x},
148 #define PRVM_DECLARE_clientglobalstring(x) {ev_string, #x},
149 #define PRVM_DECLARE_clientglobaledict(x) {ev_entity, #x},
150 #define PRVM_DECLARE_clientglobalfunction(x) {ev_function, #x},
151 #define PRVM_DECLARE_menuglobalfloat(x)
152 #define PRVM_DECLARE_menuglobalvector(x)
153 #define PRVM_DECLARE_menuglobalstring(x)
154 #define PRVM_DECLARE_menuglobaledict(x)
155 #define PRVM_DECLARE_menuglobalfunction(x)
156 #define PRVM_DECLARE_serverfieldfloat(x)
157 #define PRVM_DECLARE_serverfieldvector(x)
158 #define PRVM_DECLARE_serverfieldstring(x)
159 #define PRVM_DECLARE_serverfieldedict(x)
160 #define PRVM_DECLARE_serverfieldfunction(x)
161 #define PRVM_DECLARE_clientfieldfloat(x)
162 #define PRVM_DECLARE_clientfieldvector(x)
163 #define PRVM_DECLARE_clientfieldstring(x)
164 #define PRVM_DECLARE_clientfieldedict(x)
165 #define PRVM_DECLARE_clientfieldfunction(x)
166 #define PRVM_DECLARE_menufieldfloat(x)
167 #define PRVM_DECLARE_menufieldvector(x)
168 #define PRVM_DECLARE_menufieldstring(x)
169 #define PRVM_DECLARE_menufieldedict(x)
170 #define PRVM_DECLARE_menufieldfunction(x)
171 #define PRVM_DECLARE_serverfunction(x)
172 #define PRVM_DECLARE_clientfunction(x)
173 #define PRVM_DECLARE_menufunction(x)
174 #define PRVM_DECLARE_field(x)
175 #define PRVM_DECLARE_global(x)
176 #define PRVM_DECLARE_function(x)
177 #include "prvm_offsets.h"
178 #undef PRVM_DECLARE_serverglobalfloat
179 #undef PRVM_DECLARE_serverglobalvector
180 #undef PRVM_DECLARE_serverglobalstring
181 #undef PRVM_DECLARE_serverglobaledict
182 #undef PRVM_DECLARE_serverglobalfunction
183 #undef PRVM_DECLARE_clientglobalfloat
184 #undef PRVM_DECLARE_clientglobalvector
185 #undef PRVM_DECLARE_clientglobalstring
186 #undef PRVM_DECLARE_clientglobaledict
187 #undef PRVM_DECLARE_clientglobalfunction
188 #undef PRVM_DECLARE_menuglobalfloat
189 #undef PRVM_DECLARE_menuglobalvector
190 #undef PRVM_DECLARE_menuglobalstring
191 #undef PRVM_DECLARE_menuglobaledict
192 #undef PRVM_DECLARE_menuglobalfunction
193 #undef PRVM_DECLARE_serverfieldfloat
194 #undef PRVM_DECLARE_serverfieldvector
195 #undef PRVM_DECLARE_serverfieldstring
196 #undef PRVM_DECLARE_serverfieldedict
197 #undef PRVM_DECLARE_serverfieldfunction
198 #undef PRVM_DECLARE_clientfieldfloat
199 #undef PRVM_DECLARE_clientfieldvector
200 #undef PRVM_DECLARE_clientfieldstring
201 #undef PRVM_DECLARE_clientfieldedict
202 #undef PRVM_DECLARE_clientfieldfunction
203 #undef PRVM_DECLARE_menufieldfloat
204 #undef PRVM_DECLARE_menufieldvector
205 #undef PRVM_DECLARE_menufieldstring
206 #undef PRVM_DECLARE_menufieldedict
207 #undef PRVM_DECLARE_menufieldfunction
208 #undef PRVM_DECLARE_serverfunction
209 #undef PRVM_DECLARE_clientfunction
210 #undef PRVM_DECLARE_menufunction
211 #undef PRVM_DECLARE_field
212 #undef PRVM_DECLARE_global
213 #undef PRVM_DECLARE_function
214 };
215
216 void CL_VM_UpdateDmgGlobals (int dmg_take, int dmg_save, vec3_t dmg_origin)
217 {
218         prvm_prog_t *prog = CLVM_prog;
219
220         if(prog->loaded)
221         {
222                 PRVM_clientglobalfloat(dmg_take) = dmg_take;
223                 PRVM_clientglobalfloat(dmg_save) = dmg_save;
224                 VectorCopy(dmg_origin, PRVM_clientglobalvector(dmg_origin));
225         }
226 }
227
228 void CSQC_UpdateNetworkTimes(double newtime, double oldtime)
229 {
230         prvm_prog_t *prog = CLVM_prog;
231
232         if(!prog->loaded)
233                 return;
234
235         PRVM_clientglobalfloat(servertime) = newtime;
236         PRVM_clientglobalfloat(serverprevtime) = oldtime;
237         PRVM_clientglobalfloat(serverdeltatime) = newtime - oldtime;
238 }
239
240 //[515]: set globals before calling R_UpdateView, WEIRD CRAP
241 static void CSQC_SetGlobals (double frametime)
242 {
243         vec3_t pmove_org;
244         prvm_prog_t *prog = CLVM_prog;
245
246         PRVM_clientglobalfloat(time) = cl.time;
247         PRVM_clientglobalfloat(cltime) = host.realtime; // Spike named it that way.
248         PRVM_clientglobalfloat(frametime) = frametime;
249         PRVM_clientglobalfloat(servercommandframe) = cls.servermovesequence;
250         PRVM_clientglobalfloat(clientcommandframe) = cl.movecmd[0].sequence;
251         VectorCopy(cl.viewangles, PRVM_clientglobalvector(input_angles));
252         // // FIXME: this actually belongs into getinputstate().. [12/17/2007 Black]
253         PRVM_clientglobalfloat(input_buttons) = cl.movecmd[0].buttons;
254         VectorSet(PRVM_clientglobalvector(input_movevalues), cl.movecmd[0].forwardmove, cl.movecmd[0].sidemove, cl.movecmd[0].upmove);
255         VectorCopy(cl.csqc_vieworiginfromengine, cl.csqc_vieworigin);
256         VectorCopy(cl.csqc_viewanglesfromengine, cl.csqc_viewangles);
257
258         // LadyHavoc: Spike says not to do this, but without pmove_org the
259         // CSQC is useless as it can't alter the view origin without
260         // completely replacing it
261         Matrix4x4_OriginFromMatrix(&cl.entities[cl.viewentity].render.matrix, pmove_org);
262         VectorCopy(pmove_org, PRVM_clientglobalvector(pmove_org));
263         VectorCopy(cl.movement_velocity, PRVM_clientglobalvector(pmove_vel));
264         PRVM_clientglobalfloat(pmove_onground) = cl.onground;
265         PRVM_clientglobalfloat(pmove_inwater) = cl.inwater;
266
267         VectorCopy(cl.viewangles, PRVM_clientglobalvector(view_angles));
268         VectorCopy(cl.punchangle, PRVM_clientglobalvector(view_punchangle));
269         VectorCopy(cl.punchvector, PRVM_clientglobalvector(view_punchvector));
270         PRVM_clientglobalfloat(maxclients) = cl.maxclients;
271
272         PRVM_clientglobalfloat(player_localentnum) = cl.viewentity;
273
274         CSQC_R_RecalcView();
275 }
276
277 void CSQC_Predraw (prvm_edict_t *ed)
278 {
279         prvm_prog_t *prog = CLVM_prog;
280         int b;
281         if(!PRVM_clientedictfunction(ed, predraw))
282                 return;
283         b = PRVM_clientglobaledict(self);
284         PRVM_clientglobaledict(self) = PRVM_EDICT_TO_PROG(ed);
285         prog->ExecuteProgram(prog, PRVM_clientedictfunction(ed, predraw), "CSQC_Predraw: NULL function\n");
286         PRVM_clientglobaledict(self) = b;
287 }
288
289 void CSQC_Think (prvm_edict_t *ed)
290 {
291         prvm_prog_t *prog = CLVM_prog;
292         int b;
293         if(PRVM_clientedictfunction(ed, think))
294         if(PRVM_clientedictfloat(ed, nextthink) && PRVM_clientedictfloat(ed, nextthink) <= PRVM_clientglobalfloat(time))
295         {
296                 PRVM_clientedictfloat(ed, nextthink) = 0;
297                 b = PRVM_clientglobaledict(self);
298                 PRVM_clientglobaledict(self) = PRVM_EDICT_TO_PROG(ed);
299                 prog->ExecuteProgram(prog, PRVM_clientedictfunction(ed, think), "CSQC_Think: NULL function\n");
300                 PRVM_clientglobaledict(self) = b;
301         }
302 }
303
304 extern cvar_t cl_noplayershadow;
305 qbool CSQC_AddRenderEdict(prvm_edict_t *ed, int edictnum)
306 {
307         prvm_prog_t *prog = CLVM_prog;
308         int renderflags;
309         int c;
310         float scale;
311         entity_render_t *entrender;
312         model_t *model;
313         prvm_vec3_t modellight_origin;
314
315         model = CL_GetModelFromEdict(ed);
316         if (!model)
317                 return false;
318
319         if (edictnum)
320         {
321                 if (r_refdef.scene.numentities >= r_refdef.scene.maxentities)
322                         return false;
323                 entrender = cl.csqcrenderentities + edictnum;
324                 r_refdef.scene.entities[r_refdef.scene.numentities++] = entrender;
325                 entrender->entitynumber = edictnum + MAX_EDICTS;
326                 //entrender->shadertime = 0; // shadertime was set by spawn()
327                 entrender->flags = 0;
328                 entrender->effects = 0;
329                 entrender->alpha = 1;
330                 entrender->scale = 1;
331                 VectorSet(entrender->colormod, 1, 1, 1);
332                 VectorSet(entrender->glowmod, 1, 1, 1);
333                 entrender->allowdecals = true;
334         }
335         else
336         {
337                 entrender = CL_NewTempEntity(0);
338                 if (!entrender)
339                         return false;
340         }
341
342         entrender->userwavefunc_param[0] = PRVM_clientedictfloat(ed, userwavefunc_param0);
343         entrender->userwavefunc_param[1] = PRVM_clientedictfloat(ed, userwavefunc_param1);
344         entrender->userwavefunc_param[2] = PRVM_clientedictfloat(ed, userwavefunc_param2);
345         entrender->userwavefunc_param[3] = PRVM_clientedictfloat(ed, userwavefunc_param3);
346
347         entrender->model = model;
348         entrender->skinnum = (int)PRVM_clientedictfloat(ed, skin);
349         entrender->effects |= entrender->model->effects;
350         renderflags = (int)PRVM_clientedictfloat(ed, renderflags);
351         entrender->alpha = PRVM_clientedictfloat(ed, alpha);
352         entrender->scale = scale = PRVM_clientedictfloat(ed, scale);
353         VectorCopy(PRVM_clientedictvector(ed, colormod), entrender->colormod);
354         VectorCopy(PRVM_clientedictvector(ed, glowmod), entrender->glowmod);
355         if(PRVM_clientedictfloat(ed, effects))  entrender->effects |= (int)PRVM_clientedictfloat(ed, effects);
356         if (!entrender->alpha)
357                 entrender->alpha = 1.0f;
358         if (!entrender->scale)
359                 entrender->scale = scale = 1.0f;
360         if (!VectorLength2(entrender->colormod))
361                 VectorSet(entrender->colormod, 1, 1, 1);
362         if (!VectorLength2(entrender->glowmod))
363                 VectorSet(entrender->glowmod, 1, 1, 1);
364
365         // LadyHavoc: use the CL_GetTagMatrix function on self to ensure consistent behavior (duplicate code would be bad)
366         // this also sets the custommodellight_origin for us
367         CL_GetTagMatrix(prog, &entrender->matrix, ed, 0, modellight_origin);
368         VectorCopy(modellight_origin, entrender->custommodellight_origin);
369
370         // set up the animation data
371         VM_GenerateFrameGroupBlend(prog, ed->priv.server->framegroupblend, ed);
372         VM_FrameBlendFromFrameGroupBlend(ed->priv.server->frameblend, ed->priv.server->framegroupblend, model, cl.time);
373         VM_UpdateEdictSkeleton(prog, ed, model, ed->priv.server->frameblend);
374         if (PRVM_clientedictfloat(ed, shadertime)) // hack for csprogs.dat files that do not set shadertime, leaves the value at entity spawn time
375                 entrender->shadertime = PRVM_clientedictfloat(ed, shadertime);
376
377         // transparent offset
378         if (renderflags & RF_USETRANSPARENTOFFSET)
379                 entrender->transparent_offset = PRVM_clientglobalfloat(transparent_offset);
380
381         // model light
382         if (renderflags & RF_MODELLIGHT)
383         {
384                 if (PRVM_clientedictvector(ed, modellight_ambient)) VectorCopy(PRVM_clientedictvector(ed, modellight_ambient), entrender->custommodellight_ambient); else VectorClear(entrender->custommodellight_ambient);
385                 if (PRVM_clientedictvector(ed, modellight_diffuse)) VectorCopy(PRVM_clientedictvector(ed, modellight_diffuse), entrender->custommodellight_diffuse); else VectorClear(entrender->custommodellight_diffuse);
386                 if (PRVM_clientedictvector(ed, modellight_dir))     VectorCopy(PRVM_clientedictvector(ed, modellight_dir), entrender->custommodellight_lightdir);    else VectorClear(entrender->custommodellight_lightdir);
387                 entrender->flags |= RENDER_CUSTOMIZEDMODELLIGHT;
388         }
389
390         if(renderflags)
391         {
392                 if(renderflags & RF_VIEWMODEL) entrender->flags |= RENDER_VIEWMODEL | RENDER_NODEPTHTEST;
393                 if(renderflags & RF_EXTERNALMODEL) entrender->flags |= RENDER_EXTERIORMODEL;
394                 if(renderflags & RF_WORLDOBJECT) entrender->flags |= RENDER_WORLDOBJECT;
395                 if(renderflags & RF_DEPTHHACK) entrender->flags |= RENDER_NODEPTHTEST;
396                 if(renderflags & RF_ADDITIVE) entrender->flags |= RENDER_ADDITIVE;
397                 if(renderflags & RF_DYNAMICMODELLIGHT) entrender->flags |= RENDER_DYNAMICMODELLIGHT;
398         }
399
400         c = (int)PRVM_clientedictfloat(ed, colormap);
401         if (c <= 0)
402                 CL_SetEntityColormapColors(entrender, -1);
403         else if (c <= cl.maxclients && cl.scores != NULL)
404                 CL_SetEntityColormapColors(entrender, cl.scores[c-1].colors);
405         else
406                 CL_SetEntityColormapColors(entrender, c);
407
408         entrender->flags &= ~(RENDER_SHADOW | RENDER_LIGHT | RENDER_NOSELFSHADOW);
409         // either fullbright or lit
410         if(!r_fullbright.integer)
411         {
412                 if (!(entrender->effects & EF_FULLBRIGHT) && !(renderflags & RF_FULLBRIGHT))
413                         entrender->flags |= RENDER_LIGHT;
414         }
415         // hide player shadow during intermission or nehahra movie
416         if (!(entrender->effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST))
417          &&  (entrender->alpha >= 1)
418          && !(renderflags & RF_NOSHADOW)
419          && !(entrender->flags & RENDER_VIEWMODEL)
420          && (!(entrender->flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
421                 entrender->flags |= RENDER_SHADOW;
422         if (entrender->flags & RENDER_VIEWMODEL)
423                 entrender->flags |= RENDER_NOSELFSHADOW;
424         if (entrender->effects & EF_NOSELFSHADOW)
425                 entrender->flags |= RENDER_NOSELFSHADOW;
426         if (entrender->effects & EF_NODEPTHTEST)
427                 entrender->flags |= RENDER_NODEPTHTEST;
428         if (entrender->effects & EF_ADDITIVE)
429                 entrender->flags |= RENDER_ADDITIVE;
430         if (entrender->effects & EF_DOUBLESIDED)
431                 entrender->flags |= RENDER_DOUBLESIDED;
432         if (entrender->effects & EF_DYNAMICMODELLIGHT)
433                 entrender->flags |= RENDER_DYNAMICMODELLIGHT;
434
435         // make the other useful stuff
436         memcpy(entrender->framegroupblend, ed->priv.server->framegroupblend, sizeof(ed->priv.server->framegroupblend));
437         CL_UpdateRenderEntity(entrender);
438
439         // override animation data with full control
440         memcpy(entrender->frameblend, ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend));
441         if (ed->priv.server->skeleton.relativetransforms)
442                 entrender->skeleton = &ed->priv.server->skeleton;
443         else
444                 entrender->skeleton = NULL;
445
446         return true;
447 }
448
449 // 0 = keydown, key, character (EXT_CSQC)
450 // 1 = keyup, key, character (EXT_CSQC)
451 // 2 = mousemove relative, x, y (EXT_CSQC)
452 // 3 = mousemove absolute, x, y (DP_CSQC)
453 qbool CL_VM_InputEvent (int eventtype, float x, float y)
454 {
455         prvm_prog_t *prog = CLVM_prog;
456         qbool r;
457
458         if(!prog->loaded)
459                 return false;
460
461         if (!PRVM_clientfunction(CSQC_InputEvent))
462                 r = false;
463         else
464         {
465                 PRVM_clientglobalfloat(time) = cl.time;
466                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
467                 PRVM_G_FLOAT(OFS_PARM0) = eventtype;
468                 PRVM_G_FLOAT(OFS_PARM1) = x; // key or x
469                 PRVM_G_FLOAT(OFS_PARM2) = y; // ascii or y
470                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_InputEvent), "QC function CSQC_InputEvent is missing");
471                 r = CSQC_RETURNVAL != 0;
472         }
473         return r;
474 }
475
476 extern r_refdef_view_t csqc_original_r_refdef_view;
477 extern r_refdef_view_t csqc_main_r_refdef_view;
478 qbool CL_VM_UpdateView (double frametime)
479 {
480         prvm_prog_t *prog = CLVM_prog;
481         vec3_t emptyvector;
482         emptyvector[0] = 0;
483         emptyvector[1] = 0;
484         emptyvector[2] = 0;
485 //      vec3_t oldangles;
486
487         if(!prog->loaded)
488                 return false;
489
490         R_TimeReport("pre-UpdateView");
491
492         csqc_original_r_refdef_view = r_refdef.view;
493         csqc_main_r_refdef_view = r_refdef.view;
494         //VectorCopy(cl.viewangles, oldangles);
495         PRVM_clientglobalfloat(time) = cl.time;
496         PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
497         CSQC_SetGlobals(frametime);
498         // clear renderable entity and light lists to prevent crashes if the
499         // CSQC_UpdateView function does not call R_ClearScene as it should
500         r_refdef.scene.numentities = 0;
501         r_refdef.scene.numlights = 0;
502         // polygonbegin without draw2d arg has to guess
503         prog->polygonbegin_guess2d = false;
504         // free memory for resources that are no longer referenced
505         PRVM_GarbageCollection(prog);
506         // pass in width and height and menu/focus state as parameters (EXT_CSQC_1)
507         PRVM_G_FLOAT(OFS_PARM0) = vid.width;
508         PRVM_G_FLOAT(OFS_PARM1) = vid.height;
509         /*
510          * This should be fine for now but FTEQW uses flags for keydest
511          * and checks that an array called "eyeoffset" is 0
512          *
513          * Just a note in case there's compatibility problems later
514          */
515         PRVM_G_FLOAT(OFS_PARM2) = key_dest == key_game;
516         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_UpdateView), "QC function CSQC_UpdateView is missing");
517         //VectorCopy(oldangles, cl.viewangles);
518         // Dresk : Reset Dmg Globals Here
519         CL_VM_UpdateDmgGlobals(0, 0, emptyvector);
520         r_refdef.view = csqc_main_r_refdef_view;
521         R_RenderView_UpdateViewVectors(); // we have to do this, as we undid the scene render doing this for us
522
523         R_TimeReport("UpdateView");
524         return true;
525 }
526
527 qbool CL_VM_ConsoleCommand(const char *text, size_t textlen)
528 {
529         prvm_prog_t *prog = CLVM_prog;
530         return PRVM_ConsoleCommand(prog, text, textlen, &prog->funcoffsets.CSQC_ConsoleCommand, false, cl.csqc_server2csqcentitynumber[cl.playerentity], cl.time, "QC function CSQC_ConsoleCommand is missing");
531 }
532
533 qbool CL_VM_Parse_TempEntity (void)
534 {
535         prvm_prog_t *prog = CLVM_prog;
536         int t;
537         qbool r = false;
538
539         if(!prog->loaded)
540                 return false;
541
542         if(PRVM_clientfunction(CSQC_Parse_TempEntity))
543         {
544                 t = cl_message.readcount;
545                 PRVM_clientglobalfloat(time) = cl.time;
546                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
547                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Parse_TempEntity), "QC function CSQC_Parse_TempEntity is missing");
548                 r = CSQC_RETURNVAL != 0;
549                 if(!r)
550                 {
551                         cl_message.readcount = t;
552                         cl_message.badread = false;
553                 }
554         }
555         return r;
556 }
557
558 void CL_VM_Parse_StuffCmd(const char *msg, size_t msg_len)
559 {
560         prvm_prog_t *prog = CLVM_prog;
561         int restorevm_tempstringsbuf_cursize;
562
563         if(msg[0] == 'c')
564         if(msg[1] == 's')
565         if(msg[2] == 'q')
566         if(msg[3] == 'c')
567         {
568                 // if this is setting a csqc variable, deprotect csqc_progcrc
569                 // temporarily so that it can be set by the cvar command,
570                 // and then reprotect it afterwards
571                 int crcflags = csqc_progcrc.flags;
572                 csqc_progcrc.flags &= ~CF_READONLY;
573                 csqc_progsize.flags &= ~CF_READONLY;
574                 Cmd_ExecuteString(cmd_local, msg, msg_len, src_local, true);
575                 csqc_progcrc.flags = csqc_progsize.flags = crcflags;
576                 return;
577         }
578
579         if(!prog->loaded)
580         {
581                 Cbuf_AddText(cmd_local, msg);
582                 return;
583         }
584
585         if(PRVM_clientfunction(CSQC_Parse_StuffCmd))
586         {
587                 PRVM_clientglobalfloat(time) = cl.time;
588                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
589                 restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
590                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, msg, msg_len);
591                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Parse_StuffCmd), "QC function CSQC_Parse_StuffCmd is missing");
592                 prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
593         }
594         else
595                 Cbuf_AddText(cmd_local, msg);
596 }
597
598 static void CL_VM_Parse_Print(const char *msg, size_t msg_len)
599 {
600         prvm_prog_t *prog = CLVM_prog;
601         int restorevm_tempstringsbuf_cursize;
602         PRVM_clientglobalfloat(time) = cl.time;
603         PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
604         restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
605         PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, msg, msg_len);
606         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Parse_Print), "QC function CSQC_Parse_Print is missing");
607         prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
608 }
609
610 void CSQC_AddPrintText(const char *msg, size_t msg_len)
611 {
612         prvm_prog_t *prog = CLVM_prog;
613         char *start = cl.csqc_printtextbuf + cl.csqc_printtextbuf_len;
614         size_t writebytes = min(msg_len + 1, MAX_INPUTLINE - cl.csqc_printtextbuf_len);
615
616         if(prog->loaded && PRVM_clientfunction(CSQC_Parse_Print))
617         {
618                 if(msg[msg_len - 1] != '\n' && msg[msg_len - 1] != '\r')
619                 {
620                         if(cl.csqc_printtextbuf_len + msg_len + 1 >= MAX_INPUTLINE)
621                         {
622                                 CL_VM_Parse_Print(cl.csqc_printtextbuf, cl.csqc_printtextbuf_len);
623                                 cl.csqc_printtextbuf[0] = '\0';
624                                 cl.csqc_printtextbuf_len = 0;
625                         }
626                         else
627                         {
628                                 memcpy(start, msg, writebytes);
629                                 cl.csqc_printtextbuf_len += msg_len;
630                         }
631                         return;
632                 }
633                 memcpy(start, msg, writebytes);
634                 cl.csqc_printtextbuf_len += msg_len;
635                 CL_VM_Parse_Print(cl.csqc_printtextbuf, cl.csqc_printtextbuf_len);
636                 cl.csqc_printtextbuf[0] = '\0';
637                 cl.csqc_printtextbuf_len = 0;
638         }
639         else
640                 Con_Print(msg);
641 }
642
643 void CL_VM_Parse_CenterPrint(const char *msg, size_t msg_len)
644 {
645         prvm_prog_t *prog = CLVM_prog;
646         int restorevm_tempstringsbuf_cursize;
647
648         if(prog->loaded && PRVM_clientfunction(CSQC_Parse_CenterPrint))
649         {
650                 PRVM_clientglobalfloat(time) = cl.time;
651                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
652                 restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
653                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, msg, msg_len);
654                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Parse_CenterPrint), "QC function CSQC_Parse_CenterPrint is missing");
655                 prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
656         }
657         else
658                 SCR_CenterPrint(msg);
659 }
660
661 void CL_VM_UpdateIntermissionState (int intermission)
662 {
663         prvm_prog_t *prog = CLVM_prog;
664
665         if(prog->loaded)
666                 PRVM_clientglobalfloat(intermission) = intermission;
667 }
668 void CL_VM_UpdateShowingScoresState (int showingscores)
669 {
670         prvm_prog_t *prog = CLVM_prog;
671
672         if(prog->loaded)
673                 PRVM_clientglobalfloat(sb_showscores) = showingscores;
674 }
675 qbool CL_VM_Event_Sound(int sound_num, float fvolume, int channel, float attenuation, int ent, vec3_t pos, int flags, float speed)
676 {
677         prvm_prog_t *prog = CLVM_prog;
678         qbool r = false;
679
680         if(prog->loaded)
681         {
682                 if(PRVM_clientfunction(CSQC_Event_Sound))
683                 {
684                         PRVM_clientglobalfloat(time) = cl.time;
685                         PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
686                         PRVM_G_FLOAT(OFS_PARM0) = ent;
687                         PRVM_G_FLOAT(OFS_PARM1) = CHAN_ENGINE2USER(channel);
688                         PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(prog, cl.sound_name[sound_num], strlen(cl.sound_name[sound_num]));
689                         PRVM_G_FLOAT(OFS_PARM3) = fvolume;
690                         PRVM_G_FLOAT(OFS_PARM4) = attenuation;
691                         VectorCopy(pos, PRVM_G_VECTOR(OFS_PARM5) );
692                         PRVM_G_FLOAT(OFS_PARM6) = speed * 100.0f;
693                         PRVM_G_FLOAT(OFS_PARM7) = flags; // flags
694                         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Event_Sound), "QC function CSQC_Event_Sound is missing");
695                         r = CSQC_RETURNVAL != 0;
696                 }
697         }
698
699         return r;
700 }
701 static void CL_VM_UpdateCoopDeathmatchGlobals (int gametype)
702 {
703         prvm_prog_t *prog = CLVM_prog;
704         // Avoid global names for clean(er) coding
705         int localcoop;
706         int localdeathmatch;
707
708         if(prog->loaded)
709         {
710                 if(gametype == GAME_COOP)
711                 {
712                         localcoop = 1;
713                         localdeathmatch = 0;
714                 }
715                 else if(gametype == GAME_DEATHMATCH)
716                 {
717                         localcoop = 0;
718                         localdeathmatch = 1;
719                 }
720                 else
721                 {
722                         // How did the ServerInfo send an unknown gametype?
723                         // Better just assign the globals as 0...
724                         localcoop = 0;
725                         localdeathmatch = 0;
726                 }
727                 PRVM_clientglobalfloat(coop) = localcoop;
728                 PRVM_clientglobalfloat(deathmatch) = localdeathmatch;
729         }
730 }
731 #if 0
732 static float CL_VM_Event (float event)          //[515]: needed ? I'd say "YES", but don't know for what :D
733 {
734         prvm_prog_t *prog = CLVM_prog;
735         float r = 0;
736
737         if(!prog->loaded)
738                 return 0;
739
740         if(PRVM_clientfunction(CSQC_Event))
741         {
742                 PRVM_clientglobalfloat(time) = cl.time;
743                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
744                 PRVM_G_FLOAT(OFS_PARM0) = event;
745                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Event), "QC function CSQC_Event is missing");
746                 r = CSQC_RETURNVAL;
747         }
748         return r;
749 }
750 #endif
751
752 void CSQC_ReadEntities (void)
753 {
754         prvm_prog_t *prog = CLVM_prog;
755         unsigned short entnum, oldself, realentnum;
756
757         if(!prog->loaded)
758         {
759                 Host_Error ("CSQC_ReadEntities: CSQC is not loaded");
760                 return;
761         }
762
763         PRVM_clientglobalfloat(time) = cl.time;
764         oldself = PRVM_clientglobaledict(self);
765         while(1)
766         {
767                 entnum = MSG_ReadShort(&cl_message);
768                 if(!entnum || cl_message.badread)
769                         break;
770                 realentnum = entnum & 0x7FFF;
771                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[realentnum];
772                 if(entnum & 0x8000)
773                 {
774                         if(PRVM_clientglobaledict(self))
775                         {
776                                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Ent_Remove), "QC function CSQC_Ent_Remove is missing");
777                                 cl.csqc_server2csqcentitynumber[realentnum] = 0;
778                         }
779                         else
780                         {
781                                 // LadyHavoc: removing an entity that is already gone on
782                                 // the csqc side is possible for legitimate reasons (such
783                                 // as a repeat of the remove message), so no warning is
784                                 // needed
785                                 //Con_Printf("Bad csqc_server2csqcentitynumber map\n"); //[515]: never happens ?
786                         }
787                 }
788                 else
789                 {
790                         if(!PRVM_clientglobaledict(self))
791                         {
792                                 if(!PRVM_clientfunction(CSQC_Ent_Spawn))
793                                 {
794                                         prvm_edict_t    *ed;
795                                         ed = PRVM_ED_Alloc(prog);
796                                         PRVM_clientedictfloat(ed, entnum) = realentnum;
797                                         PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT_TO_PROG(ed);
798                                 }
799                                 else
800                                 {
801                                         // entity( float entnum ) CSQC_Ent_Spawn;
802                                         // the qc function should set entnum, too (this way it also can return world [2/1/2008 Andreas]
803                                         PRVM_G_FLOAT(OFS_PARM0) = (float) realentnum;
804                                         // make sure no one gets wrong ideas
805                                         PRVM_clientglobaledict(self) = 0;
806                                         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Ent_Spawn), "QC function CSQC_Ent_Spawn is missing");
807                                         PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT( PRVM_G_INT( OFS_RETURN ) );
808                                 }
809                                 PRVM_G_FLOAT(OFS_PARM0) = 1;
810                                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Ent_Update), "QC function CSQC_Ent_Update is missing");
811                         }
812                         else {
813                                 PRVM_G_FLOAT(OFS_PARM0) = 0;
814                                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Ent_Update), "QC function CSQC_Ent_Update is missing");
815                         }
816                 }
817         }
818         PRVM_clientglobaledict(self) = oldself;
819 }
820
821 static void CLVM_begin_increase_edicts(prvm_prog_t *prog)
822 {
823         // links don't survive the transition, so unlink everything
824         World_UnlinkAll(&cl.world);
825 }
826
827 static void CLVM_end_increase_edicts(prvm_prog_t *prog)
828 {
829         int i;
830         prvm_edict_t *ent;
831
832         // link every entity except world
833         for (i = 1, ent = prog->edicts;i < prog->num_edicts;i++, ent++)
834                 if (!ent->free)
835                         CL_LinkEdict(ent);
836 }
837
838 static void CLVM_init_edict(prvm_prog_t *prog, prvm_edict_t *e)
839 {
840         int edictnum = PRVM_NUM_FOR_EDICT(e);
841         entity_render_t *entrender;
842         CL_ExpandCSQCRenderEntities(edictnum);
843         entrender = cl.csqcrenderentities + edictnum;
844         e->priv.server->move = false; // don't move on first frame
845         memset(entrender, 0, sizeof(*entrender));
846         entrender->shadertime = cl.time;
847 }
848
849 static void CLVM_free_edict(prvm_prog_t *prog, prvm_edict_t *ed)
850 {
851         entity_render_t *entrender = cl.csqcrenderentities + PRVM_NUM_FOR_EDICT(ed);
852         R_DecalSystem_Reset(&entrender->decalsystem);
853         memset(entrender, 0, sizeof(*entrender));
854         World_UnlinkEdict(ed);
855         memset(ed->fields.fp, 0, prog->entityfields * sizeof(prvm_vec_t));
856         VM_RemoveEdictSkeleton(prog, ed);
857 #ifdef USEODE
858         World_Physics_RemoveFromEntity(&cl.world, ed);
859         World_Physics_RemoveJointFromEntity(&cl.world, ed);
860 #endif
861 }
862
863 static void CLVM_count_edicts(prvm_prog_t *prog)
864 {
865         int             i;
866         prvm_edict_t    *ent;
867         int             active = 0, models = 0, solid = 0;
868
869         for (i=0 ; i<prog->num_edicts ; i++)
870         {
871                 ent = PRVM_EDICT_NUM(i);
872                 if (ent->free)
873                         continue;
874                 active++;
875                 if (PRVM_clientedictfloat(ent, solid))
876                         solid++;
877                 if (PRVM_clientedictstring(ent, model))
878                         models++;
879         }
880
881         Con_Printf("num_edicts:%3i\n", prog->num_edicts);
882         Con_Printf("active    :%3i\n", active);
883         Con_Printf("view      :%3i\n", models);
884         Con_Printf("touch     :%3i\n", solid);
885 }
886
887 static qbool CLVM_load_edict(prvm_prog_t *prog, prvm_edict_t *ent)
888 {
889         return true;
890 }
891
892 // returns true if the packet is valid, false if end of file is reached
893 // used for dumping the CSQC download into demo files
894 qbool MakeDownloadPacket(const char *filename, unsigned char *data, size_t len, int crc, int cnt, sizebuf_t *buf, int protocol)
895 {
896         int packetsize = buf->maxsize - 7; // byte short long
897         int npackets = ((int)len + packetsize - 1) / (packetsize);
898         char vabuf[1024];
899
900         if(protocol == PROTOCOL_QUAKEWORLD)
901                 return false; // CSQC can't run in QW anyway
902
903         SZ_Clear(buf);
904         if(cnt == 0)
905         {
906                 MSG_WriteByte(buf, svc_stufftext);
907                 MSG_WriteString(buf, va(vabuf, sizeof(vabuf), "\ncl_downloadbegin %lu %s\n", (unsigned long)len, filename));
908                 return true;
909         }
910         else if(cnt >= 1 && cnt <= npackets)
911         {
912                 unsigned long thispacketoffset = (cnt - 1) * packetsize;
913                 int thispacketsize = (int)len - thispacketoffset;
914                 if(thispacketsize > packetsize)
915                         thispacketsize = packetsize;
916
917                 MSG_WriteByte(buf, svc_downloaddata);
918                 MSG_WriteLong(buf, thispacketoffset);
919                 MSG_WriteShort(buf, thispacketsize);
920                 SZ_Write(buf, data + thispacketoffset, thispacketsize);
921
922                 return true;
923         }
924         else if(cnt == npackets + 1)
925         {
926                 MSG_WriteByte(buf, svc_stufftext);
927                 MSG_WriteString(buf, va(vabuf, sizeof(vabuf), "\ncl_downloadfinished %lu %d\n", (unsigned long)len, crc));
928                 return true;
929         }
930         return false;
931 }
932
933 extern cvar_t csqc_usedemoprogs;
934 void CL_VM_Init (void)
935 {
936         prvm_prog_t *prog = CLVM_prog;
937         const char* csprogsfn = NULL;
938         unsigned char *csprogsdata = NULL;
939         fs_offset_t csprogsdatasize = 0;
940         int csprogsdatacrc, requiredcrc;
941         int requiredsize;
942         char vabuf[1024];
943
944         // reset csqc_progcrc after reading it, so that changing servers doesn't
945         // expect csqc on the next server
946         requiredcrc = csqc_progcrc.integer;
947         requiredsize = csqc_progsize.integer;
948         Cvar_SetValueQuick(&csqc_progcrc, -1);
949         Cvar_SetValueQuick(&csqc_progsize, -1);
950
951         // if the server is not requesting a csprogs, then we're done here
952         if (requiredcrc < 0)
953                 return;
954
955         // see if the requested csprogs.dat file matches the requested crc
956         if (!cls.demoplayback || csqc_usedemoprogs.integer)
957         {
958                 csprogsfn = va(vabuf, sizeof(vabuf), "dlcache/%s.%i.%i", csqc_progname.string, requiredsize, requiredcrc);
959                 if(cls.caughtcsprogsdata && cls.caughtcsprogsdatasize == requiredsize && CRC_Block(cls.caughtcsprogsdata, (size_t)cls.caughtcsprogsdatasize) == requiredcrc)
960                 {
961                         Con_DPrintf("Using buffered \"%s\"\n", csprogsfn);
962                         csprogsdata = cls.caughtcsprogsdata;
963                         csprogsdatasize = cls.caughtcsprogsdatasize;
964                         cls.caughtcsprogsdata = NULL;
965                         cls.caughtcsprogsdatasize = 0;
966                 }
967                 else
968                 {
969                         Con_DPrintf("Not using buffered \"%s\" (buffered: %p, %d)\n", csprogsfn, (void *)cls.caughtcsprogsdata, (int) cls.caughtcsprogsdatasize);
970                         csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
971                 }
972         }
973         if (!csprogsdata)
974         {
975                 csprogsfn = csqc_progname.string;
976                 csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
977         }
978         if (csprogsdata)
979         {
980                 csprogsdatacrc = CRC_Block(csprogsdata, (size_t)csprogsdatasize);
981                 if (csprogsdatacrc != requiredcrc || csprogsdatasize != requiredsize)
982                 {
983                         if (cls.demoplayback)
984                         {
985                                 Con_Printf(CON_WARN "Warning: Your %s is not the same version as the demo was recorded with (CRC/size are %i/%i but should be %i/%i)\n", csqc_progname.string, csprogsdatacrc, (int)csprogsdatasize, requiredcrc, requiredsize);
986                                 // Mem_Free(csprogsdata);
987                                 // return;
988                                 // We WANT to continue here, and play the demo with different csprogs!
989                                 // After all, this is just a warning. Sure things may go wrong from here.
990                         }
991                         else
992                         {
993                                 Mem_Free(csprogsdata);
994                                 CL_DisconnectEx(false, "Your %s is not the same version as the server (CRC is %i/%i but should be %i/%i)\n", csqc_progname.string, csprogsdatacrc, (int)csprogsdatasize, requiredcrc, requiredsize);
995                                 return;
996                         }
997                 }
998         }
999         else
1000         {
1001                 if (requiredcrc >= 0)
1002                         CL_DisconnectEx(false, CON_ERROR "CL_VM_Init: %s requires CSQC, but \"%s\" wasn't found\n", cls.demoplayback ? "demo" : "server", csqc_progname.string);
1003                 return;
1004         }
1005
1006         PRVM_Prog_Init(prog, cmd_local);
1007
1008         // allocate the mempools
1009         prog->progs_mempool = Mem_AllocPool(csqc_progname.string, 0, NULL);
1010         prog->edictprivate_size = 0; // no private struct used
1011         prog->name = "client";
1012         prog->num_edicts = 1;
1013         prog->max_edicts = 512;
1014         prog->limit_edicts = CL_MAX_EDICTS;
1015         prog->reserved_edicts = 0;
1016         prog->edictprivate_size = sizeof(edict_engineprivate_t);
1017         // TODO: add a shared extension string #define and add real support for csqc extension strings [12/5/2007 Black]
1018         prog->extensionstring = vm_sv_extensions;
1019         prog->builtins = vm_cl_builtins;
1020         prog->numbuiltins = vm_cl_numbuiltins;
1021
1022         // all callbacks must be defined (pointers are not checked before calling)
1023         prog->begin_increase_edicts = CLVM_begin_increase_edicts;
1024         prog->end_increase_edicts   = CLVM_end_increase_edicts;
1025         prog->init_edict            = CLVM_init_edict;
1026         prog->free_edict            = CLVM_free_edict;
1027         prog->count_edicts          = CLVM_count_edicts;
1028         prog->load_edict            = CLVM_load_edict;
1029         prog->init_cmd              = CLVM_init_cmd;
1030         prog->reset_cmd             = CLVM_reset_cmd;
1031         prog->error_cmd             = Host_Error;
1032         prog->ExecuteProgram        = CLVM_ExecuteProgram;
1033
1034         PRVM_Prog_Load(prog, csprogsfn, csprogsdata, csprogsdatasize, cl_numrequiredfunc, cl_required_func, CL_REQFIELDS, cl_reqfields, CL_REQGLOBALS, cl_reqglobals);
1035
1036         if (!prog->loaded)
1037         {
1038                 Mem_Free(csprogsdata);
1039                 Host_Error("CSQC %s failed to load\n", csprogsfn);
1040         }
1041
1042         if(cls.demorecording)
1043         {
1044                 if(cls.demo_lastcsprogssize != csprogsdatasize || cls.demo_lastcsprogscrc != csprogsdatacrc)
1045                 {
1046                         int i;
1047                         static char buf[NET_MAXMESSAGE];
1048                         sizebuf_t sb;
1049                         unsigned char *demobuf; fs_offset_t demofilesize;
1050
1051                         sb.data = (unsigned char *) buf;
1052                         sb.maxsize = sizeof(buf);
1053                         i = 0;
1054
1055                         CL_CutDemo(&demobuf, &demofilesize);
1056                         while(MakeDownloadPacket(csqc_progname.string, csprogsdata, (size_t)csprogsdatasize, csprogsdatacrc, i++, &sb, cls.protocol))
1057                                 CL_WriteDemoMessage(&sb);
1058                         CL_PasteDemo(&demobuf, &demofilesize);
1059
1060                         cls.demo_lastcsprogssize = csprogsdatasize;
1061                         cls.demo_lastcsprogscrc = csprogsdatacrc;
1062                 }
1063         }
1064         Mem_Free(csprogsdata);
1065
1066         // check if OP_STATE animation is possible in this dat file
1067         if (prog->fieldoffsets.nextthink >= 0 && prog->fieldoffsets.frame >= 0 && prog->fieldoffsets.think >= 0 && prog->globaloffsets.self >= 0)
1068                 prog->flag |= PRVM_OP_STATE;
1069
1070         // set time
1071         PRVM_clientglobalfloat(time) = cl.time;
1072         PRVM_clientglobaledict(self) = 0;
1073
1074         PRVM_clientglobalstring(mapname) = PRVM_SetEngineString(prog, cl.worldbasename);
1075         PRVM_clientglobalfloat(player_localnum) = cl.realplayerentity - 1;
1076         PRVM_clientglobalfloat(player_localentnum) = cl.viewentity;
1077
1078         // set map description (use world entity 0)
1079         PRVM_clientedictstring(prog->edicts, message) = PRVM_SetEngineString(prog, cl.worldmessage);
1080         VectorCopy(cl.world.mins, PRVM_clientedictvector(prog->edicts, mins));
1081         VectorCopy(cl.world.maxs, PRVM_clientedictvector(prog->edicts, maxs));
1082         VectorCopy(cl.world.mins, PRVM_clientedictvector(prog->edicts, absmin));
1083         VectorCopy(cl.world.maxs, PRVM_clientedictvector(prog->edicts, absmax));
1084
1085         // call the prog init
1086         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Init), "QC function CSQC_Init is missing");
1087
1088         // Once CSQC_Init was called, we consider csqc code fully initialized.
1089         prog->inittime = host.realtime;
1090
1091         cl.csqc_vidvars.drawcrosshair = false;
1092         cl.csqc_vidvars.drawenginesbar = false;
1093
1094         // Update Coop and Deathmatch Globals (at this point the client knows them from ServerInfo)
1095         CL_VM_UpdateCoopDeathmatchGlobals(cl.gametype);
1096 }
1097
1098 void CL_VM_ShutDown (void)
1099 {
1100         prvm_prog_t *prog = CLVM_prog;
1101         Cmd_ClearCSQCCommands(cmd_local);
1102
1103         //Cvar_SetValueQuick(&csqc_progcrc, -1);
1104         //Cvar_SetValueQuick(&csqc_progsize, -1);
1105         if (prog->loaded)
1106         {
1107                 PRVM_clientglobalfloat(time) = cl.time;
1108                 PRVM_clientglobaledict(self) = 0;
1109                 if (PRVM_clientfunction(CSQC_Shutdown))
1110                         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Shutdown), "QC function CSQC_Shutdown is missing");
1111         }
1112         PRVM_Prog_Reset(prog);
1113         Con_DPrint("CSQC ^1unloaded\n");
1114 }
1115
1116 qbool CL_VM_GetEntitySoundOrigin(int entnum, vec3_t out)
1117 {
1118         prvm_prog_t *prog = CLVM_prog;
1119         prvm_edict_t *ed;
1120         model_t *mod;
1121         matrix4x4_t matrix;
1122         qbool r = 0;
1123
1124         ed = PRVM_EDICT_NUM(entnum - MAX_EDICTS);
1125
1126         if(!ed->free)
1127         {
1128                 mod = CL_GetModelFromEdict(ed);
1129                 VectorCopy(PRVM_clientedictvector(ed, origin), out);
1130                 if(CL_GetTagMatrix(prog, &matrix, ed, 0, NULL) == 0)
1131                         Matrix4x4_OriginFromMatrix(&matrix, out);
1132                 if (mod && mod->soundfromcenter)
1133                         VectorMAMAM(1.0f, out, 0.5f, mod->normalmins, 0.5f, mod->normalmaxs, out);
1134                 r = 1;
1135         }
1136
1137         return r;
1138 }
1139
1140 qbool CL_VM_TransformView(int entnum, matrix4x4_t *viewmatrix, mplane_t *clipplane, vec3_t visorigin)
1141 {
1142         prvm_prog_t *prog = CLVM_prog;
1143         qbool ret = false;
1144         prvm_edict_t *ed;
1145         vec3_t forward, left, up, origin, ang;
1146         matrix4x4_t mat, matq;
1147
1148         ed = PRVM_EDICT_NUM(entnum);
1149         // camera:
1150         //   camera_transform
1151         if(PRVM_clientedictfunction(ed, camera_transform))
1152         {
1153                 ret = true;
1154                 if(viewmatrix && clipplane && visorigin)
1155                 {
1156                         Matrix4x4_ToVectors(viewmatrix, forward, left, up, origin);
1157                         AnglesFromVectors(ang, forward, up, false);
1158                         PRVM_clientglobalfloat(time) = cl.time;
1159                         PRVM_clientglobaledict(self) = entnum;
1160                         VectorCopy(origin, PRVM_G_VECTOR(OFS_PARM0));
1161                         VectorCopy(ang, PRVM_G_VECTOR(OFS_PARM1));
1162                         VectorCopy(forward, PRVM_clientglobalvector(v_forward));
1163                         VectorScale(left, -1, PRVM_clientglobalvector(v_right));
1164                         VectorCopy(up, PRVM_clientglobalvector(v_up));
1165                         VectorCopy(origin, PRVM_clientglobalvector(trace_endpos));
1166                         prog->ExecuteProgram(prog, PRVM_clientedictfunction(ed, camera_transform), "QC function e.camera_transform is missing");
1167                         VectorCopy(PRVM_G_VECTOR(OFS_RETURN), origin);
1168                         VectorCopy(PRVM_clientglobalvector(v_forward), forward);
1169                         VectorScale(PRVM_clientglobalvector(v_right), -1, left);
1170                         VectorCopy(PRVM_clientglobalvector(v_up), up);
1171                         VectorCopy(PRVM_clientglobalvector(trace_endpos), visorigin);
1172                         Matrix4x4_Invert_Full(&mat, viewmatrix);
1173                         Matrix4x4_FromVectors(viewmatrix, forward, left, up, origin);
1174                         Matrix4x4_Concat(&matq, viewmatrix, &mat);
1175                         Matrix4x4_TransformPositivePlane(&matq, clipplane->normal[0], clipplane->normal[1], clipplane->normal[2], clipplane->dist, clipplane->normal_and_dist);
1176                 }
1177         }
1178
1179         return ret;
1180 }
1181
1182 int CL_VM_GetViewEntity(void)
1183 {
1184         if(cl.csqc_server2csqcentitynumber[cl.viewentity])
1185                 return cl.csqc_server2csqcentitynumber[cl.viewentity] + MAX_EDICTS;
1186         return cl.viewentity;
1187 }