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