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