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