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