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