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