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