]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - model_shared.c
major overhaul for thread-safety - many global variables and static
[xonotic/darkplaces.git] / model_shared.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
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 // models.c -- model loading and caching
21
22 // models are the only shared resource between a client and server running
23 // on the same machine.
24
25 #include "quakedef.h"
26 #include "image.h"
27 #include "r_shadow.h"
28 #include "polygon.h"
29
30 cvar_t r_enableshadowvolumes = {CVAR_SAVE, "r_enableshadowvolumes", "1", "Enables use of Stencil Shadow Volume shadowing methods, saves some memory if turned off"};
31 cvar_t r_mipskins = {CVAR_SAVE, "r_mipskins", "0", "mipmaps model skins so they render faster in the distance and do not display noise artifacts, can cause discoloration of skins if they contain undesirable border colors"};
32 cvar_t r_mipnormalmaps = {CVAR_SAVE, "r_mipnormalmaps", "1", "mipmaps normalmaps (turning it off looks sharper but may have aliasing)"};
33 cvar_t mod_generatelightmaps_unitspersample = {CVAR_SAVE, "mod_generatelightmaps_unitspersample", "8", "lightmap resolution"};
34 cvar_t mod_generatelightmaps_borderpixels = {CVAR_SAVE, "mod_generatelightmaps_borderpixels", "2", "extra space around polygons to prevent sampling artifacts"};
35 cvar_t mod_generatelightmaps_texturesize = {CVAR_SAVE, "mod_generatelightmaps_texturesize", "1024", "size of lightmap textures"};
36 cvar_t mod_generatelightmaps_lightmapsamples = {CVAR_SAVE, "mod_generatelightmaps_lightmapsamples", "16", "number of shadow tests done per lightmap pixel"};
37 cvar_t mod_generatelightmaps_vertexsamples = {CVAR_SAVE, "mod_generatelightmaps_vertexsamples", "16", "number of shadow tests done per vertex"};
38 cvar_t mod_generatelightmaps_gridsamples = {CVAR_SAVE, "mod_generatelightmaps_gridsamples", "64", "number of shadow tests done per lightgrid cell"};
39 cvar_t mod_generatelightmaps_lightmapradius = {CVAR_SAVE, "mod_generatelightmaps_lightmapradius", "16", "sampling area around each lightmap pixel"};
40 cvar_t mod_generatelightmaps_vertexradius = {CVAR_SAVE, "mod_generatelightmaps_vertexradius", "16", "sampling area around each vertex"};
41 cvar_t mod_generatelightmaps_gridradius = {CVAR_SAVE, "mod_generatelightmaps_gridradius", "64", "sampling area around each lightgrid cell center"};
42
43 dp_model_t *loadmodel;
44
45 static mempool_t *mod_mempool;
46 static memexpandablearray_t models;
47
48 static mempool_t* q3shaders_mem;
49 typedef struct q3shader_hash_entry_s
50 {
51   q3shaderinfo_t shader;
52   struct q3shader_hash_entry_s* chain;
53 } q3shader_hash_entry_t;
54 #define Q3SHADER_HASH_SIZE  1021
55 typedef struct q3shader_data_s
56 {
57   memexpandablearray_t hash_entries;
58   q3shader_hash_entry_t hash[Q3SHADER_HASH_SIZE];
59   memexpandablearray_t char_ptrs;
60 } q3shader_data_t;
61 static q3shader_data_t* q3shader_data;
62
63 static void mod_start(void)
64 {
65         int i, count;
66         int nummodels = Mem_ExpandableArray_IndexRange(&models);
67         dp_model_t *mod;
68
69         SCR_PushLoadingScreen(false, "Loading models", 1.0);
70         count = 0;
71         for (i = 0;i < nummodels;i++)
72                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
73                         if (mod->used)
74                                 ++count;
75         for (i = 0;i < nummodels;i++)
76                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
77                         if (mod->used)
78                         {
79                                 SCR_PushLoadingScreen(true, mod->name, 1.0 / count);
80                                 Mod_LoadModel(mod, true, false);
81                                 SCR_PopLoadingScreen(false);
82                         }
83         SCR_PopLoadingScreen(false);
84 }
85
86 static void mod_shutdown(void)
87 {
88         int i;
89         int nummodels = Mem_ExpandableArray_IndexRange(&models);
90         dp_model_t *mod;
91
92         for (i = 0;i < nummodels;i++)
93                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && (mod->loaded || mod->mempool))
94                         Mod_UnloadModel(mod);
95
96         Mod_FreeQ3Shaders();
97         Mod_Skeletal_FreeBuffers();
98 }
99
100 static void mod_newmap(void)
101 {
102         msurface_t *surface;
103         int i, j, k, surfacenum, ssize, tsize;
104         int nummodels = Mem_ExpandableArray_IndexRange(&models);
105         dp_model_t *mod;
106
107         for (i = 0;i < nummodels;i++)
108         {
109                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool)
110                 {
111                         for (j = 0;j < mod->num_textures && mod->data_textures;j++)
112                         {
113                                 for (k = 0;k < mod->data_textures[j].numskinframes;k++)
114                                         R_SkinFrame_MarkUsed(mod->data_textures[j].skinframes[k]);
115                                 for (k = 0;k < mod->data_textures[j].backgroundnumskinframes;k++)
116                                         R_SkinFrame_MarkUsed(mod->data_textures[j].backgroundskinframes[k]);
117                         }
118                         if (mod->brush.solidskyskinframe)
119                                 R_SkinFrame_MarkUsed(mod->brush.solidskyskinframe);
120                         if (mod->brush.alphaskyskinframe)
121                                 R_SkinFrame_MarkUsed(mod->brush.alphaskyskinframe);
122                 }
123         }
124
125         if (!cl_stainmaps_clearonload.integer)
126                 return;
127
128         for (i = 0;i < nummodels;i++)
129         {
130                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool && mod->data_surfaces)
131                 {
132                         for (surfacenum = 0, surface = mod->data_surfaces;surfacenum < mod->num_surfaces;surfacenum++, surface++)
133                         {
134                                 if (surface->lightmapinfo && surface->lightmapinfo->stainsamples)
135                                 {
136                                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
137                                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
138                                         memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
139                                         mod->brushq1.lightmapupdateflags[surfacenum] = true;
140                                 }
141                         }
142                 }
143         }
144 }
145
146 /*
147 ===============
148 Mod_Init
149 ===============
150 */
151 static void Mod_Print(void);
152 static void Mod_Precache (void);
153 static void Mod_Decompile_f(void);
154 static void Mod_GenerateLightmaps_f(void);
155 void Mod_Init (void)
156 {
157         mod_mempool = Mem_AllocPool("modelinfo", 0, NULL);
158         Mem_ExpandableArray_NewArray(&models, mod_mempool, sizeof(dp_model_t), 16);
159
160         Mod_BrushInit();
161         Mod_AliasInit();
162         Mod_SpriteInit();
163
164         Cvar_RegisterVariable(&r_enableshadowvolumes);
165         Cvar_RegisterVariable(&r_mipskins);
166         Cvar_RegisterVariable(&r_mipnormalmaps);
167         Cvar_RegisterVariable(&mod_generatelightmaps_unitspersample);
168         Cvar_RegisterVariable(&mod_generatelightmaps_borderpixels);
169         Cvar_RegisterVariable(&mod_generatelightmaps_texturesize);
170
171         Cvar_RegisterVariable(&mod_generatelightmaps_lightmapsamples);
172         Cvar_RegisterVariable(&mod_generatelightmaps_vertexsamples);
173         Cvar_RegisterVariable(&mod_generatelightmaps_gridsamples);
174         Cvar_RegisterVariable(&mod_generatelightmaps_lightmapradius);
175         Cvar_RegisterVariable(&mod_generatelightmaps_vertexradius);
176         Cvar_RegisterVariable(&mod_generatelightmaps_gridradius);
177
178         Cmd_AddCommand ("modellist", Mod_Print, "prints a list of loaded models");
179         Cmd_AddCommand ("modelprecache", Mod_Precache, "load a model");
180         Cmd_AddCommand ("modeldecompile", Mod_Decompile_f, "exports a model in several formats for editing purposes");
181         Cmd_AddCommand ("mod_generatelightmaps", Mod_GenerateLightmaps_f, "rebuilds lighting on current worldmodel");
182 }
183
184 void Mod_RenderInit(void)
185 {
186         R_RegisterModule("Models", mod_start, mod_shutdown, mod_newmap, NULL, NULL);
187 }
188
189 void Mod_UnloadModel (dp_model_t *mod)
190 {
191         char name[MAX_QPATH];
192         qboolean used;
193         dp_model_t *parentmodel;
194
195         if (developer_loading.integer)
196                 Con_Printf("unloading model %s\n", mod->name);
197
198         strlcpy(name, mod->name, sizeof(name));
199         parentmodel = mod->brush.parentmodel;
200         used = mod->used;
201         if (mod->mempool)
202         {
203                 if (mod->surfmesh.vertex3fbuffer)
204                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.vertex3fbuffer);
205                 mod->surfmesh.vertex3fbuffer = NULL;
206                 if (mod->surfmesh.vertexmeshbuffer)
207                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.vertexmeshbuffer);
208                 mod->surfmesh.vertexmeshbuffer = NULL;
209                 if (mod->surfmesh.data_element3i_indexbuffer)
210                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.data_element3i_indexbuffer);
211                 mod->surfmesh.data_element3i_indexbuffer = NULL;
212                 if (mod->surfmesh.data_element3s_indexbuffer)
213                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.data_element3s_indexbuffer);
214                 mod->surfmesh.data_element3s_indexbuffer = NULL;
215                 if (mod->surfmesh.vbo_vertexbuffer)
216                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.vbo_vertexbuffer);
217                 mod->surfmesh.vbo_vertexbuffer = NULL;
218         }
219         // free textures/memory attached to the model
220         R_FreeTexturePool(&mod->texturepool);
221         Mem_FreePool(&mod->mempool);
222         // clear the struct to make it available
223         memset(mod, 0, sizeof(dp_model_t));
224         // restore the fields we want to preserve
225         strlcpy(mod->name, name, sizeof(mod->name));
226         mod->brush.parentmodel = parentmodel;
227         mod->used = used;
228         mod->loaded = false;
229 }
230
231 static void R_Model_Null_Draw(entity_render_t *ent)
232 {
233         return;
234 }
235
236
237 typedef void (*mod_framegroupify_parsegroups_t) (unsigned int i, int start, int len, float fps, qboolean loop, void *pass);
238
239 static int Mod_FrameGroupify_ParseGroups(const char *buf, mod_framegroupify_parsegroups_t cb, void *pass)
240 {
241         const char *bufptr;
242         int start, len;
243         float fps;
244         unsigned int i;
245         qboolean loop;
246
247         bufptr = buf;
248         i = 0;
249         for(;;)
250         {
251                 // an anim scene!
252                 if (!COM_ParseToken_Simple(&bufptr, true, false))
253                         break;
254                 if (!strcmp(com_token, "\n"))
255                         continue; // empty line
256                 start = atoi(com_token);
257                 if (!COM_ParseToken_Simple(&bufptr, true, false))
258                         break;
259                 if (!strcmp(com_token, "\n"))
260                 {
261                         Con_Printf("framegroups file: missing number of frames\n");
262                         continue;
263                 }
264                 len = atoi(com_token);
265                 if (!COM_ParseToken_Simple(&bufptr, true, false))
266                         break;
267                 // we default to looping as it's usually wanted, so to NOT loop you append a 0
268                 if (strcmp(com_token, "\n"))
269                 {
270                         fps = atof(com_token);
271                         if (!COM_ParseToken_Simple(&bufptr, true, false))
272                                 break;
273                         if (strcmp(com_token, "\n"))
274                                 loop = atoi(com_token) != 0;
275                         else
276                                 loop = true;
277                 }
278                 else
279                 {
280                         fps = 20;
281                         loop = true;
282                 }
283
284                 if(cb)
285                         cb(i, start, len, fps, loop, pass);
286                 ++i;
287         }
288
289         return i;
290 }
291
292 static void Mod_FrameGroupify_ParseGroups_Store (unsigned int i, int start, int len, float fps, qboolean loop, void *pass)
293 {
294         dp_model_t *mod = (dp_model_t *) pass;
295         animscene_t *anim = &mod->animscenes[i];
296         dpsnprintf(anim->name, sizeof(anim[i].name), "groupified_%d_anim", i);
297         anim->firstframe = bound(0, start, mod->num_poses - 1);
298         anim->framecount = bound(1, len, mod->num_poses - anim->firstframe);
299         anim->framerate = max(1, fps);
300         anim->loop = !!loop;
301         //Con_Printf("frame group %d is %d %d %f %d\n", i, start, len, fps, loop);
302 }
303
304 static void Mod_FrameGroupify(dp_model_t *mod, const char *buf)
305 {
306         unsigned int cnt;
307
308         // 0. count
309         cnt = Mod_FrameGroupify_ParseGroups(buf, NULL, NULL);
310         if(!cnt)
311         {
312                 Con_Printf("no scene found in framegroups file, aborting\n");
313                 return;
314         }
315         mod->numframes = cnt;
316
317         // 1. reallocate
318         // (we do not free the previous animscenes, but model unloading will free the pool owning them, so it's okay)
319         mod->animscenes = (animscene_t *) Mem_Alloc(mod->mempool, sizeof(animscene_t) * mod->numframes);
320
321         // 2. parse
322         Mod_FrameGroupify_ParseGroups(buf, Mod_FrameGroupify_ParseGroups_Store, mod);
323 }
324
325 static void Mod_FindPotentialDeforms(dp_model_t *mod)
326 {
327         int i, j;
328         texture_t *texture;
329         mod->wantnormals = false;
330         mod->wanttangents = false;
331         for (i = 0;i < mod->num_textures;i++)
332         {
333                 texture = mod->data_textures + i;
334                 if (texture->tcgen.tcgen == Q3TCGEN_ENVIRONMENT)
335                         mod->wantnormals = true;
336                 for (j = 0;j < Q3MAXDEFORMS;j++)
337                 {
338                         if (texture->deforms[j].deform == Q3DEFORM_AUTOSPRITE)
339                         {
340                                 mod->wanttangents = true;
341                                 mod->wantnormals = true;
342                                 break;
343                         }
344                         if (texture->deforms[j].deform != Q3DEFORM_NONE)
345                                 mod->wantnormals = true;
346                 }
347         }
348 }
349
350 /*
351 ==================
352 Mod_LoadModel
353
354 Loads a model
355 ==================
356 */
357 dp_model_t *Mod_LoadModel(dp_model_t *mod, qboolean crash, qboolean checkdisk)
358 {
359         int num;
360         unsigned int crc;
361         void *buf;
362         fs_offset_t filesize = 0;
363         char vabuf[1024];
364
365         mod->used = true;
366
367         if (mod->name[0] == '*') // submodel
368                 return mod;
369         
370         if (!strcmp(mod->name, "null"))
371         {
372                 if(mod->loaded)
373                         return mod;
374
375                 if (mod->loaded || mod->mempool)
376                         Mod_UnloadModel(mod);
377
378                 if (developer_loading.integer)
379                         Con_Printf("loading model %s\n", mod->name);
380
381                 mod->used = true;
382                 mod->crc = (unsigned int)-1;
383                 mod->loaded = false;
384
385                 VectorClear(mod->normalmins);
386                 VectorClear(mod->normalmaxs);
387                 VectorClear(mod->yawmins);
388                 VectorClear(mod->yawmaxs);
389                 VectorClear(mod->rotatedmins);
390                 VectorClear(mod->rotatedmaxs);
391
392                 mod->modeldatatypestring = "null";
393                 mod->type = mod_null;
394                 mod->Draw = R_Model_Null_Draw;
395                 mod->numframes = 2;
396                 mod->numskins = 1;
397
398                 // no fatal errors occurred, so this model is ready to use.
399                 mod->loaded = true;
400
401                 return mod;
402         }
403
404         crc = 0;
405         buf = NULL;
406
407         // even if the model is loaded it still may need reloading...
408
409         // if it is not loaded or checkdisk is true we need to calculate the crc
410         if (!mod->loaded || checkdisk)
411         {
412                 if (checkdisk && mod->loaded)
413                         Con_DPrintf("checking model %s\n", mod->name);
414                 buf = FS_LoadFile (mod->name, tempmempool, false, &filesize);
415                 if (buf)
416                 {
417                         crc = CRC_Block((unsigned char *)buf, filesize);
418                         // we need to reload the model if the crc does not match
419                         if (mod->crc != crc)
420                                 mod->loaded = false;
421                 }
422         }
423
424         // if the model is already loaded and checks passed, just return
425         if (mod->loaded)
426         {
427                 if (buf)
428                         Mem_Free(buf);
429                 return mod;
430         }
431
432         if (developer_loading.integer)
433                 Con_Printf("loading model %s\n", mod->name);
434         
435         SCR_PushLoadingScreen(true, mod->name, 1);
436
437         // LordHavoc: unload the existing model in this slot (if there is one)
438         if (mod->loaded || mod->mempool)
439                 Mod_UnloadModel(mod);
440
441         // load the model
442         mod->used = true;
443         mod->crc = crc;
444         // errors can prevent the corresponding mod->loaded = true;
445         mod->loaded = false;
446
447         // default model radius and bounding box (mainly for missing models)
448         mod->radius = 16;
449         VectorSet(mod->normalmins, -mod->radius, -mod->radius, -mod->radius);
450         VectorSet(mod->normalmaxs, mod->radius, mod->radius, mod->radius);
451         VectorSet(mod->yawmins, -mod->radius, -mod->radius, -mod->radius);
452         VectorSet(mod->yawmaxs, mod->radius, mod->radius, mod->radius);
453         VectorSet(mod->rotatedmins, -mod->radius, -mod->radius, -mod->radius);
454         VectorSet(mod->rotatedmaxs, mod->radius, mod->radius, mod->radius);
455
456         if (!q3shaders_mem)
457         {
458                 // load q3 shaders for the first time, or after a level change
459                 Mod_LoadQ3Shaders();
460         }
461
462         if (buf)
463         {
464                 char *bufend = (char *)buf + filesize;
465
466                 // all models use memory, so allocate a memory pool
467                 mod->mempool = Mem_AllocPool(mod->name, 0, NULL);
468
469                 num = LittleLong(*((int *)buf));
470                 // call the apropriate loader
471                 loadmodel = mod;
472                 if (!strcasecmp(FS_FileExtension(mod->name), "obj")) Mod_OBJ_Load(mod, buf, bufend);
473                 else if (!memcmp(buf, "IDPO", 4)) Mod_IDP0_Load(mod, buf, bufend);
474                 else if (!memcmp(buf, "IDP2", 4)) Mod_IDP2_Load(mod, buf, bufend);
475                 else if (!memcmp(buf, "IDP3", 4)) Mod_IDP3_Load(mod, buf, bufend);
476                 else if (!memcmp(buf, "IDSP", 4)) Mod_IDSP_Load(mod, buf, bufend);
477                 else if (!memcmp(buf, "IDS2", 4)) Mod_IDS2_Load(mod, buf, bufend);
478                 else if (!memcmp(buf, "IBSP", 4)) Mod_IBSP_Load(mod, buf, bufend);
479                 else if (!memcmp(buf, "ZYMOTICMODEL", 12)) Mod_ZYMOTICMODEL_Load(mod, buf, bufend);
480                 else if (!memcmp(buf, "DARKPLACESMODEL", 16)) Mod_DARKPLACESMODEL_Load(mod, buf, bufend);
481                 else if (!memcmp(buf, "ACTRHEAD", 8)) Mod_PSKMODEL_Load(mod, buf, bufend);
482                 else if (!memcmp(buf, "INTERQUAKEMODEL", 16)) Mod_INTERQUAKEMODEL_Load(mod, buf, bufend);
483                 else if (strlen(mod->name) >= 4 && !strcmp(mod->name + strlen(mod->name) - 4, ".map")) Mod_MAP_Load(mod, buf, bufend);
484                 else if (num == BSPVERSION || num == 30) Mod_Q1BSP_Load(mod, buf, bufend);
485                 else Con_Printf("Mod_LoadModel: model \"%s\" is of unknown/unsupported type\n", mod->name);
486                 Mem_Free(buf);
487
488                 Mod_FindPotentialDeforms(mod);
489
490                 buf = FS_LoadFile(va(vabuf, sizeof(vabuf), "%s.framegroups", mod->name), tempmempool, false, &filesize);
491                 if(buf)
492                 {
493                         Mod_FrameGroupify(mod, (const char *)buf);
494                         Mem_Free(buf);
495                 }
496
497                 Mod_BuildVBOs();
498         }
499         else if (crash)
500         {
501                 // LordHavoc: Sys_Error was *ANNOYING*
502                 Con_Printf ("Mod_LoadModel: %s not found\n", mod->name);
503         }
504
505         // no fatal errors occurred, so this model is ready to use.
506         mod->loaded = true;
507
508         SCR_PopLoadingScreen(false);
509
510         return mod;
511 }
512
513 void Mod_ClearUsed(void)
514 {
515         int i;
516         int nummodels = Mem_ExpandableArray_IndexRange(&models);
517         dp_model_t *mod;
518         for (i = 0;i < nummodels;i++)
519                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0])
520                         mod->used = false;
521 }
522
523 void Mod_PurgeUnused(void)
524 {
525         int i;
526         int nummodels = Mem_ExpandableArray_IndexRange(&models);
527         dp_model_t *mod;
528         for (i = 0;i < nummodels;i++)
529         {
530                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !mod->used)
531                 {
532                         Mod_UnloadModel(mod);
533                         Mem_ExpandableArray_FreeRecord(&models, mod);
534                 }
535         }
536 }
537
538 /*
539 ==================
540 Mod_FindName
541
542 ==================
543 */
544 dp_model_t *Mod_FindName(const char *name, const char *parentname)
545 {
546         int i;
547         int nummodels;
548         dp_model_t *mod;
549
550         if (!parentname)
551                 parentname = "";
552
553         // if we're not dedicatd, the renderer calls will crash without video
554         Host_StartVideo();
555
556         nummodels = Mem_ExpandableArray_IndexRange(&models);
557
558         if (!name[0])
559                 Host_Error ("Mod_ForName: NULL name");
560
561         // search the currently loaded models
562         for (i = 0;i < nummodels;i++)
563         {
564                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !strcmp(mod->name, name) && ((!mod->brush.parentmodel && !parentname[0]) || (mod->brush.parentmodel && parentname[0] && !strcmp(mod->brush.parentmodel->name, parentname))))
565                 {
566                         mod->used = true;
567                         return mod;
568                 }
569         }
570
571         // no match found, create a new one
572         mod = (dp_model_t *) Mem_ExpandableArray_AllocRecord(&models);
573         strlcpy(mod->name, name, sizeof(mod->name));
574         if (parentname[0])
575                 mod->brush.parentmodel = Mod_FindName(parentname, NULL);
576         else
577                 mod->brush.parentmodel = NULL;
578         mod->loaded = false;
579         mod->used = true;
580         return mod;
581 }
582
583 /*
584 ==================
585 Mod_ForName
586
587 Loads in a model for the given name
588 ==================
589 */
590 dp_model_t *Mod_ForName(const char *name, qboolean crash, qboolean checkdisk, const char *parentname)
591 {
592         dp_model_t *model;
593         model = Mod_FindName(name, parentname);
594         if (!model->loaded || checkdisk)
595                 Mod_LoadModel(model, crash, checkdisk);
596         return model;
597 }
598
599 /*
600 ==================
601 Mod_Reload
602
603 Reloads all models if they have changed
604 ==================
605 */
606 void Mod_Reload(void)
607 {
608         int i, count;
609         int nummodels = Mem_ExpandableArray_IndexRange(&models);
610         dp_model_t *mod;
611
612         SCR_PushLoadingScreen(false, "Reloading models", 1.0);
613         count = 0;
614         for (i = 0;i < nummodels;i++)
615                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
616                         ++count;
617         for (i = 0;i < nummodels;i++)
618                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
619                 {
620                         SCR_PushLoadingScreen(true, mod->name, 1.0 / count);
621                         Mod_LoadModel(mod, true, true);
622                         SCR_PopLoadingScreen(false);
623                 }
624         SCR_PopLoadingScreen(false);
625 }
626
627 unsigned char *mod_base;
628
629
630 //=============================================================================
631
632 /*
633 ================
634 Mod_Print
635 ================
636 */
637 static void Mod_Print(void)
638 {
639         int i;
640         int nummodels = Mem_ExpandableArray_IndexRange(&models);
641         dp_model_t *mod;
642
643         Con_Print("Loaded models:\n");
644         for (i = 0;i < nummodels;i++)
645         {
646                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
647                 {
648                         if (mod->brush.numsubmodels)
649                                 Con_Printf("%4iK %s (%i submodels)\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name, mod->brush.numsubmodels);
650                         else
651                                 Con_Printf("%4iK %s\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name);
652                 }
653         }
654 }
655
656 /*
657 ================
658 Mod_Precache
659 ================
660 */
661 static void Mod_Precache(void)
662 {
663         if (Cmd_Argc() == 2)
664                 Mod_ForName(Cmd_Argv(1), false, true, Cmd_Argv(1)[0] == '*' ? cl.model_name[1] : NULL);
665         else
666                 Con_Print("usage: modelprecache <filename>\n");
667 }
668
669 int Mod_BuildVertexRemapTableFromElements(int numelements, const int *elements, int numvertices, int *remapvertices)
670 {
671         int i, count;
672         unsigned char *used;
673         used = (unsigned char *)Mem_Alloc(tempmempool, numvertices);
674         memset(used, 0, numvertices);
675         for (i = 0;i < numelements;i++)
676                 used[elements[i]] = 1;
677         for (i = 0, count = 0;i < numvertices;i++)
678                 remapvertices[i] = used[i] ? count++ : -1;
679         Mem_Free(used);
680         return count;
681 }
682
683 #if 1
684 // fast way, using an edge hash
685 #define TRIANGLEEDGEHASH 8192
686 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
687 {
688         int i, j, p, e1, e2, *n, hashindex, count, match;
689         const int *e;
690         typedef struct edgehashentry_s
691         {
692                 struct edgehashentry_s *next;
693                 int triangle;
694                 int element[2];
695         }
696         edgehashentry_t;
697         static edgehashentry_t **edgehash;
698         edgehashentry_t *edgehashentries, *hash;
699         if (!numtriangles)
700                 return;
701         edgehash = (edgehashentry_t **)Mem_Alloc(tempmempool, TRIANGLEEDGEHASH * sizeof(*edgehash));
702         // if there are too many triangles for the stack array, allocate larger buffer
703         edgehashentries = (edgehashentry_t *)Mem_Alloc(tempmempool, numtriangles * 3 * sizeof(edgehashentry_t));
704         // find neighboring triangles
705         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
706         {
707                 for (j = 0, p = 2;j < 3;p = j, j++)
708                 {
709                         e1 = e[p];
710                         e2 = e[j];
711                         // this hash index works for both forward and backward edges
712                         hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
713                         hash = edgehashentries + i * 3 + j;
714                         hash->next = edgehash[hashindex];
715                         edgehash[hashindex] = hash;
716                         hash->triangle = i;
717                         hash->element[0] = e1;
718                         hash->element[1] = e2;
719                 }
720         }
721         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
722         {
723                 for (j = 0, p = 2;j < 3;p = j, j++)
724                 {
725                         e1 = e[p];
726                         e2 = e[j];
727                         // this hash index works for both forward and backward edges
728                         hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
729                         count = 0;
730                         match = -1;
731                         for (hash = edgehash[hashindex];hash;hash = hash->next)
732                         {
733                                 if (hash->element[0] == e2 && hash->element[1] == e1)
734                                 {
735                                         if (hash->triangle != i)
736                                                 match = hash->triangle;
737                                         count++;
738                                 }
739                                 else if ((hash->element[0] == e1 && hash->element[1] == e2))
740                                         count++;
741                         }
742                         // detect edges shared by three triangles and make them seams
743                         if (count > 2)
744                                 match = -1;
745                         n[p] = match;
746                 }
747
748                 // also send a keepalive here (this can take a while too!)
749                 CL_KeepaliveMessage(false);
750         }
751         // free the allocated buffer
752         Mem_Free(edgehashentries);
753         Mem_Free(edgehash);
754 }
755 #else
756 // very slow but simple way
757 static int Mod_FindTriangleWithEdge(const int *elements, int numtriangles, int start, int end, int ignore)
758 {
759         int i, match, count;
760         count = 0;
761         match = -1;
762         for (i = 0;i < numtriangles;i++, elements += 3)
763         {
764                      if ((elements[0] == start && elements[1] == end)
765                       || (elements[1] == start && elements[2] == end)
766                       || (elements[2] == start && elements[0] == end))
767                 {
768                         if (i != ignore)
769                                 match = i;
770                         count++;
771                 }
772                 else if ((elements[1] == start && elements[0] == end)
773                       || (elements[2] == start && elements[1] == end)
774                       || (elements[0] == start && elements[2] == end))
775                         count++;
776         }
777         // detect edges shared by three triangles and make them seams
778         if (count > 2)
779                 match = -1;
780         return match;
781 }
782
783 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
784 {
785         int i, *n;
786         const int *e;
787         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
788         {
789                 n[0] = Mod_FindTriangleWithEdge(elements, numtriangles, e[1], e[0], i);
790                 n[1] = Mod_FindTriangleWithEdge(elements, numtriangles, e[2], e[1], i);
791                 n[2] = Mod_FindTriangleWithEdge(elements, numtriangles, e[0], e[2], i);
792         }
793 }
794 #endif
795
796 void Mod_ValidateElements(int *elements, int numtriangles, int firstvertex, int numverts, const char *filename, int fileline)
797 {
798         int i, warned = false, endvertex = firstvertex + numverts;
799         for (i = 0;i < numtriangles * 3;i++)
800         {
801                 if (elements[i] < firstvertex || elements[i] >= endvertex)
802                 {
803                         if (!warned)
804                         {
805                                 warned = true;
806                                 Con_Printf("Mod_ValidateElements: out of bounds elements detected at %s:%d\n", filename, fileline);
807                         }
808                         elements[i] = firstvertex;
809                 }
810         }
811 }
812
813 // warning: this is an expensive function!
814 void Mod_BuildNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const int *elements, float *normal3f, qboolean areaweighting)
815 {
816         int i, j;
817         const int *element;
818         float *vectorNormal;
819         float areaNormal[3];
820         // clear the vectors
821         memset(normal3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
822         // process each vertex of each triangle and accumulate the results
823         // use area-averaging, to make triangles with a big area have a bigger
824         // weighting on the vertex normal than triangles with a small area
825         // to do so, just add the 'normals' together (the bigger the area
826         // the greater the length of the normal is
827         element = elements;
828         for (i = 0; i < numtriangles; i++, element += 3)
829         {
830                 TriangleNormal(
831                         vertex3f + element[0] * 3,
832                         vertex3f + element[1] * 3,
833                         vertex3f + element[2] * 3,
834                         areaNormal
835                         );
836
837                 if (!areaweighting)
838                         VectorNormalize(areaNormal);
839
840                 for (j = 0;j < 3;j++)
841                 {
842                         vectorNormal = normal3f + element[j] * 3;
843                         vectorNormal[0] += areaNormal[0];
844                         vectorNormal[1] += areaNormal[1];
845                         vectorNormal[2] += areaNormal[2];
846                 }
847         }
848         // and just normalize the accumulated vertex normal in the end
849         vectorNormal = normal3f + 3 * firstvertex;
850         for (i = 0; i < numvertices; i++, vectorNormal += 3)
851                 VectorNormalize(vectorNormal);
852 }
853
854 #if 0
855 static void Mod_BuildBumpVectors(const float *v0, const float *v1, const float *v2, const float *tc0, const float *tc1, const float *tc2, float *svector3f, float *tvector3f, float *normal3f)
856 {
857         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
858         // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
859         // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
860
861         // 6 multiply, 9 subtract
862         VectorSubtract(v1, v0, v10);
863         VectorSubtract(v2, v0, v20);
864         normal3f[0] = v20[1] * v10[2] - v20[2] * v10[1];
865         normal3f[1] = v20[2] * v10[0] - v20[0] * v10[2];
866         normal3f[2] = v20[0] * v10[1] - v20[1] * v10[0];
867         // 12 multiply, 10 subtract
868         tc10[1] = tc1[1] - tc0[1];
869         tc20[1] = tc2[1] - tc0[1];
870         svector3f[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
871         svector3f[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
872         svector3f[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
873         tc10[0] = tc1[0] - tc0[0];
874         tc20[0] = tc2[0] - tc0[0];
875         tvector3f[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
876         tvector3f[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
877         tvector3f[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
878         // 12 multiply, 4 add, 6 subtract
879         f = DotProduct(svector3f, normal3f);
880         svector3f[0] -= f * normal3f[0];
881         svector3f[1] -= f * normal3f[1];
882         svector3f[2] -= f * normal3f[2];
883         f = DotProduct(tvector3f, normal3f);
884         tvector3f[0] -= f * normal3f[0];
885         tvector3f[1] -= f * normal3f[1];
886         tvector3f[2] -= f * normal3f[2];
887         // if texture is mapped the wrong way (counterclockwise), the tangents
888         // have to be flipped, this is detected by calculating a normal from the
889         // two tangents, and seeing if it is opposite the surface normal
890         // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
891         CrossProduct(tvector3f, svector3f, tangentcross);
892         if (DotProduct(tangentcross, normal3f) < 0)
893         {
894                 VectorNegate(svector3f, svector3f);
895                 VectorNegate(tvector3f, tvector3f);
896         }
897 }
898 #endif
899
900 // warning: this is a very expensive function!
901 void Mod_BuildTextureVectorsFromNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const float *texcoord2f, const float *normal3f, const int *elements, float *svector3f, float *tvector3f, qboolean areaweighting)
902 {
903         int i, tnum;
904         float sdir[3], tdir[3], normal[3], *sv, *tv;
905         const float *v0, *v1, *v2, *tc0, *tc1, *tc2, *n;
906         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
907         const int *e;
908         // clear the vectors
909         memset(svector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
910         memset(tvector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
911         // process each vertex of each triangle and accumulate the results
912         for (tnum = 0, e = elements;tnum < numtriangles;tnum++, e += 3)
913         {
914                 v0 = vertex3f + e[0] * 3;
915                 v1 = vertex3f + e[1] * 3;
916                 v2 = vertex3f + e[2] * 3;
917                 tc0 = texcoord2f + e[0] * 2;
918                 tc1 = texcoord2f + e[1] * 2;
919                 tc2 = texcoord2f + e[2] * 2;
920
921                 // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
922                 // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
923
924                 // calculate the edge directions and surface normal
925                 // 6 multiply, 9 subtract
926                 VectorSubtract(v1, v0, v10);
927                 VectorSubtract(v2, v0, v20);
928                 normal[0] = v20[1] * v10[2] - v20[2] * v10[1];
929                 normal[1] = v20[2] * v10[0] - v20[0] * v10[2];
930                 normal[2] = v20[0] * v10[1] - v20[1] * v10[0];
931
932                 // calculate the tangents
933                 // 12 multiply, 10 subtract
934                 tc10[1] = tc1[1] - tc0[1];
935                 tc20[1] = tc2[1] - tc0[1];
936                 sdir[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
937                 sdir[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
938                 sdir[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
939                 tc10[0] = tc1[0] - tc0[0];
940                 tc20[0] = tc2[0] - tc0[0];
941                 tdir[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
942                 tdir[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
943                 tdir[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
944
945                 // if texture is mapped the wrong way (counterclockwise), the tangents
946                 // have to be flipped, this is detected by calculating a normal from the
947                 // two tangents, and seeing if it is opposite the surface normal
948                 // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
949                 CrossProduct(tdir, sdir, tangentcross);
950                 if (DotProduct(tangentcross, normal) < 0)
951                 {
952                         VectorNegate(sdir, sdir);
953                         VectorNegate(tdir, tdir);
954                 }
955
956                 if (!areaweighting)
957                 {
958                         VectorNormalize(sdir);
959                         VectorNormalize(tdir);
960                 }
961                 for (i = 0;i < 3;i++)
962                 {
963                         VectorAdd(svector3f + e[i]*3, sdir, svector3f + e[i]*3);
964                         VectorAdd(tvector3f + e[i]*3, tdir, tvector3f + e[i]*3);
965                 }
966         }
967         // make the tangents completely perpendicular to the surface normal, and
968         // then normalize them
969         // 16 assignments, 2 divide, 2 sqrt, 2 negates, 14 adds, 24 multiplies
970         for (i = 0, sv = svector3f + 3 * firstvertex, tv = tvector3f + 3 * firstvertex, n = normal3f + 3 * firstvertex;i < numvertices;i++, sv += 3, tv += 3, n += 3)
971         {
972                 f = -DotProduct(sv, n);
973                 VectorMA(sv, f, n, sv);
974                 VectorNormalize(sv);
975                 f = -DotProduct(tv, n);
976                 VectorMA(tv, f, n, tv);
977                 VectorNormalize(tv);
978         }
979 }
980
981 void Mod_AllocSurfMesh(mempool_t *mempool, int numvertices, int numtriangles, qboolean lightmapoffsets, qboolean vertexcolors, qboolean neighbors)
982 {
983         unsigned char *data;
984         data = (unsigned char *)Mem_Alloc(mempool, numvertices * (3 + 3 + 3 + 3 + 2 + 2 + (vertexcolors ? 4 : 0)) * sizeof(float) + numvertices * (lightmapoffsets ? 1 : 0) * sizeof(int) + numtriangles * (3 + (neighbors ? 3 : 0)) * sizeof(int) + (numvertices <= 65536 ? numtriangles * sizeof(unsigned short[3]) : 0));
985         loadmodel->surfmesh.num_vertices = numvertices;
986         loadmodel->surfmesh.num_triangles = numtriangles;
987         if (loadmodel->surfmesh.num_vertices)
988         {
989                 loadmodel->surfmesh.data_vertex3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
990                 loadmodel->surfmesh.data_svector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
991                 loadmodel->surfmesh.data_tvector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
992                 loadmodel->surfmesh.data_normal3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
993                 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
994                 loadmodel->surfmesh.data_texcoordlightmap2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
995                 if (vertexcolors)
996                         loadmodel->surfmesh.data_lightmapcolor4f = (float *)data, data += sizeof(float[4]) * loadmodel->surfmesh.num_vertices;
997                 if (lightmapoffsets)
998                         loadmodel->surfmesh.data_lightmapoffsets = (int *)data, data += sizeof(int) * loadmodel->surfmesh.num_vertices;
999         }
1000         if (loadmodel->surfmesh.num_triangles)
1001         {
1002                 loadmodel->surfmesh.data_element3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
1003                 if (neighbors)
1004                         loadmodel->surfmesh.data_neighbor3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
1005                 if (loadmodel->surfmesh.num_vertices <= 65536)
1006                         loadmodel->surfmesh.data_element3s = (unsigned short *)data, data += sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles;
1007         }
1008 }
1009
1010 shadowmesh_t *Mod_ShadowMesh_Alloc(mempool_t *mempool, int maxverts, int maxtriangles, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, int light, int neighbors, int expandable)
1011 {
1012         shadowmesh_t *newmesh;
1013         unsigned char *data;
1014         int size;
1015         size = sizeof(shadowmesh_t);
1016         size += maxverts * sizeof(float[3]);
1017         if (light)
1018                 size += maxverts * sizeof(float[11]);
1019         size += maxtriangles * sizeof(int[3]);
1020         if (maxverts <= 65536)
1021                 size += maxtriangles * sizeof(unsigned short[3]);
1022         if (neighbors)
1023                 size += maxtriangles * sizeof(int[3]);
1024         if (expandable)
1025                 size += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *) + maxverts * sizeof(shadowmeshvertexhash_t);
1026         data = (unsigned char *)Mem_Alloc(mempool, size);
1027         newmesh = (shadowmesh_t *)data;data += sizeof(*newmesh);
1028         newmesh->map_diffuse = map_diffuse;
1029         newmesh->map_specular = map_specular;
1030         newmesh->map_normal = map_normal;
1031         newmesh->maxverts = maxverts;
1032         newmesh->maxtriangles = maxtriangles;
1033         newmesh->numverts = 0;
1034         newmesh->numtriangles = 0;
1035         memset(newmesh->sideoffsets, 0, sizeof(newmesh->sideoffsets));
1036         memset(newmesh->sidetotals, 0, sizeof(newmesh->sidetotals));
1037
1038         newmesh->vertex3f = (float *)data;data += maxverts * sizeof(float[3]);
1039         if (light)
1040         {
1041                 newmesh->svector3f = (float *)data;data += maxverts * sizeof(float[3]);
1042                 newmesh->tvector3f = (float *)data;data += maxverts * sizeof(float[3]);
1043                 newmesh->normal3f = (float *)data;data += maxverts * sizeof(float[3]);
1044                 newmesh->texcoord2f = (float *)data;data += maxverts * sizeof(float[2]);
1045         }
1046         newmesh->element3i = (int *)data;data += maxtriangles * sizeof(int[3]);
1047         if (neighbors)
1048         {
1049                 newmesh->neighbor3i = (int *)data;data += maxtriangles * sizeof(int[3]);
1050         }
1051         if (expandable)
1052         {
1053                 newmesh->vertexhashtable = (shadowmeshvertexhash_t **)data;data += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *);
1054                 newmesh->vertexhashentries = (shadowmeshvertexhash_t *)data;data += maxverts * sizeof(shadowmeshvertexhash_t);
1055         }
1056         if (maxverts <= 65536)
1057                 newmesh->element3s = (unsigned short *)data;data += maxtriangles * sizeof(unsigned short[3]);
1058         return newmesh;
1059 }
1060
1061 shadowmesh_t *Mod_ShadowMesh_ReAlloc(mempool_t *mempool, shadowmesh_t *oldmesh, int light, int neighbors)
1062 {
1063         shadowmesh_t *newmesh;
1064         newmesh = Mod_ShadowMesh_Alloc(mempool, oldmesh->numverts, oldmesh->numtriangles, oldmesh->map_diffuse, oldmesh->map_specular, oldmesh->map_normal, light, neighbors, false);
1065         newmesh->numverts = oldmesh->numverts;
1066         newmesh->numtriangles = oldmesh->numtriangles;
1067         memcpy(newmesh->sideoffsets, oldmesh->sideoffsets, sizeof(oldmesh->sideoffsets));
1068         memcpy(newmesh->sidetotals, oldmesh->sidetotals, sizeof(oldmesh->sidetotals));
1069
1070         memcpy(newmesh->vertex3f, oldmesh->vertex3f, oldmesh->numverts * sizeof(float[3]));
1071         if (newmesh->svector3f && oldmesh->svector3f)
1072         {
1073                 memcpy(newmesh->svector3f, oldmesh->svector3f, oldmesh->numverts * sizeof(float[3]));
1074                 memcpy(newmesh->tvector3f, oldmesh->tvector3f, oldmesh->numverts * sizeof(float[3]));
1075                 memcpy(newmesh->normal3f, oldmesh->normal3f, oldmesh->numverts * sizeof(float[3]));
1076                 memcpy(newmesh->texcoord2f, oldmesh->texcoord2f, oldmesh->numverts * sizeof(float[2]));
1077         }
1078         memcpy(newmesh->element3i, oldmesh->element3i, oldmesh->numtriangles * sizeof(int[3]));
1079         if (newmesh->neighbor3i && oldmesh->neighbor3i)
1080                 memcpy(newmesh->neighbor3i, oldmesh->neighbor3i, oldmesh->numtriangles * sizeof(int[3]));
1081         return newmesh;
1082 }
1083
1084 int Mod_ShadowMesh_AddVertex(shadowmesh_t *mesh, float *vertex14f)
1085 {
1086         int hashindex, vnum;
1087         shadowmeshvertexhash_t *hash;
1088         // this uses prime numbers intentionally
1089         hashindex = (unsigned int) (vertex14f[0] * 2003 + vertex14f[1] * 4001 + vertex14f[2] * 7919) % SHADOWMESHVERTEXHASH;
1090         for (hash = mesh->vertexhashtable[hashindex];hash;hash = hash->next)
1091         {
1092                 vnum = (hash - mesh->vertexhashentries);
1093                 if ((mesh->vertex3f == NULL || (mesh->vertex3f[vnum * 3 + 0] == vertex14f[0] && mesh->vertex3f[vnum * 3 + 1] == vertex14f[1] && mesh->vertex3f[vnum * 3 + 2] == vertex14f[2]))
1094                  && (mesh->svector3f == NULL || (mesh->svector3f[vnum * 3 + 0] == vertex14f[3] && mesh->svector3f[vnum * 3 + 1] == vertex14f[4] && mesh->svector3f[vnum * 3 + 2] == vertex14f[5]))
1095                  && (mesh->tvector3f == NULL || (mesh->tvector3f[vnum * 3 + 0] == vertex14f[6] && mesh->tvector3f[vnum * 3 + 1] == vertex14f[7] && mesh->tvector3f[vnum * 3 + 2] == vertex14f[8]))
1096                  && (mesh->normal3f == NULL || (mesh->normal3f[vnum * 3 + 0] == vertex14f[9] && mesh->normal3f[vnum * 3 + 1] == vertex14f[10] && mesh->normal3f[vnum * 3 + 2] == vertex14f[11]))
1097                  && (mesh->texcoord2f == NULL || (mesh->texcoord2f[vnum * 2 + 0] == vertex14f[12] && mesh->texcoord2f[vnum * 2 + 1] == vertex14f[13])))
1098                         return hash - mesh->vertexhashentries;
1099         }
1100         vnum = mesh->numverts++;
1101         hash = mesh->vertexhashentries + vnum;
1102         hash->next = mesh->vertexhashtable[hashindex];
1103         mesh->vertexhashtable[hashindex] = hash;
1104         if (mesh->vertex3f) {mesh->vertex3f[vnum * 3 + 0] = vertex14f[0];mesh->vertex3f[vnum * 3 + 1] = vertex14f[1];mesh->vertex3f[vnum * 3 + 2] = vertex14f[2];}
1105         if (mesh->svector3f) {mesh->svector3f[vnum * 3 + 0] = vertex14f[3];mesh->svector3f[vnum * 3 + 1] = vertex14f[4];mesh->svector3f[vnum * 3 + 2] = vertex14f[5];}
1106         if (mesh->tvector3f) {mesh->tvector3f[vnum * 3 + 0] = vertex14f[6];mesh->tvector3f[vnum * 3 + 1] = vertex14f[7];mesh->tvector3f[vnum * 3 + 2] = vertex14f[8];}
1107         if (mesh->normal3f) {mesh->normal3f[vnum * 3 + 0] = vertex14f[9];mesh->normal3f[vnum * 3 + 1] = vertex14f[10];mesh->normal3f[vnum * 3 + 2] = vertex14f[11];}
1108         if (mesh->texcoord2f) {mesh->texcoord2f[vnum * 2 + 0] = vertex14f[12];mesh->texcoord2f[vnum * 2 + 1] = vertex14f[13];}
1109         return vnum;
1110 }
1111
1112 void Mod_ShadowMesh_AddTriangle(mempool_t *mempool, shadowmesh_t *mesh, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, float *vertex14f)
1113 {
1114         if (mesh->numtriangles == 0)
1115         {
1116                 // set the properties on this empty mesh to be more favorable...
1117                 // (note: this case only occurs for the first triangle added to a new mesh chain)
1118                 mesh->map_diffuse = map_diffuse;
1119                 mesh->map_specular = map_specular;
1120                 mesh->map_normal = map_normal;
1121         }
1122         while (mesh->map_diffuse != map_diffuse || mesh->map_specular != map_specular || mesh->map_normal != map_normal || mesh->numverts + 3 > mesh->maxverts || mesh->numtriangles + 1 > mesh->maxtriangles)
1123         {
1124                 if (mesh->next == NULL)
1125                         mesh->next = Mod_ShadowMesh_Alloc(mempool, max(mesh->maxverts, 300), max(mesh->maxtriangles, 100), map_diffuse, map_specular, map_normal, mesh->svector3f != NULL, mesh->neighbor3i != NULL, true);
1126                 mesh = mesh->next;
1127         }
1128         mesh->element3i[mesh->numtriangles * 3 + 0] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 0);
1129         mesh->element3i[mesh->numtriangles * 3 + 1] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 1);
1130         mesh->element3i[mesh->numtriangles * 3 + 2] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 2);
1131         mesh->numtriangles++;
1132 }
1133
1134 void Mod_ShadowMesh_AddMesh(mempool_t *mempool, shadowmesh_t *mesh, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, const float *vertex3f, const float *svector3f, const float *tvector3f, const float *normal3f, const float *texcoord2f, int numtris, const int *element3i)
1135 {
1136         int i, j, e;
1137         float vbuf[3*14], *v;
1138         memset(vbuf, 0, sizeof(vbuf));
1139         for (i = 0;i < numtris;i++)
1140         {
1141                 for (j = 0, v = vbuf;j < 3;j++, v += 14)
1142                 {
1143                         e = *element3i++;
1144                         if (vertex3f)
1145                         {
1146                                 v[0] = vertex3f[e * 3 + 0];
1147                                 v[1] = vertex3f[e * 3 + 1];
1148                                 v[2] = vertex3f[e * 3 + 2];
1149                         }
1150                         if (svector3f)
1151                         {
1152                                 v[3] = svector3f[e * 3 + 0];
1153                                 v[4] = svector3f[e * 3 + 1];
1154                                 v[5] = svector3f[e * 3 + 2];
1155                         }
1156                         if (tvector3f)
1157                         {
1158                                 v[6] = tvector3f[e * 3 + 0];
1159                                 v[7] = tvector3f[e * 3 + 1];
1160                                 v[8] = tvector3f[e * 3 + 2];
1161                         }
1162                         if (normal3f)
1163                         {
1164                                 v[9] = normal3f[e * 3 + 0];
1165                                 v[10] = normal3f[e * 3 + 1];
1166                                 v[11] = normal3f[e * 3 + 2];
1167                         }
1168                         if (texcoord2f)
1169                         {
1170                                 v[12] = texcoord2f[e * 2 + 0];
1171                                 v[13] = texcoord2f[e * 2 + 1];
1172                         }
1173                 }
1174                 Mod_ShadowMesh_AddTriangle(mempool, mesh, map_diffuse, map_specular, map_normal, vbuf);
1175         }
1176
1177         // the triangle calculation can take a while, so let's do a keepalive here
1178         CL_KeepaliveMessage(false);
1179 }
1180
1181 shadowmesh_t *Mod_ShadowMesh_Begin(mempool_t *mempool, int maxverts, int maxtriangles, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, int light, int neighbors, int expandable)
1182 {
1183         // the preparation before shadow mesh initialization can take a while, so let's do a keepalive here
1184         CL_KeepaliveMessage(false);
1185
1186         return Mod_ShadowMesh_Alloc(mempool, maxverts, maxtriangles, map_diffuse, map_specular, map_normal, light, neighbors, expandable);
1187 }
1188
1189 static void Mod_ShadowMesh_CreateVBOs(shadowmesh_t *mesh, mempool_t *mempool)
1190 {
1191         if (!mesh->numverts)
1192                 return;
1193
1194         // build r_vertexmesh_t array
1195         // (compressed interleaved array for D3D)
1196         if (!mesh->vertexmesh && mesh->texcoord2f && vid.useinterleavedarrays)
1197         {
1198                 int vertexindex;
1199                 int numvertices = mesh->numverts;
1200                 r_vertexmesh_t *vertexmesh;
1201                 mesh->vertexmesh = vertexmesh = (r_vertexmesh_t*)Mem_Alloc(mempool, numvertices * sizeof(*mesh->vertexmesh));
1202                 for (vertexindex = 0;vertexindex < numvertices;vertexindex++, vertexmesh++)
1203                 {
1204                         VectorCopy(mesh->vertex3f + 3*vertexindex, vertexmesh->vertex3f);
1205                         VectorScale(mesh->svector3f + 3*vertexindex, 1.0f, vertexmesh->svector3f);
1206                         VectorScale(mesh->tvector3f + 3*vertexindex, 1.0f, vertexmesh->tvector3f);
1207                         VectorScale(mesh->normal3f + 3*vertexindex, 1.0f, vertexmesh->normal3f);
1208                         Vector2Copy(mesh->texcoord2f + 2*vertexindex, vertexmesh->texcoordtexture2f);
1209                 }
1210         }
1211
1212         // upload r_vertexmesh_t array as a buffer
1213         if (mesh->vertexmesh && !mesh->vertexmeshbuffer)
1214                 mesh->vertexmeshbuffer = R_Mesh_CreateMeshBuffer(mesh->vertexmesh, mesh->numverts * sizeof(*mesh->vertexmesh), loadmodel->name, false, false, false);
1215
1216         // upload vertex3f array as a buffer
1217         if (mesh->vertex3f && !mesh->vertex3fbuffer)
1218                 mesh->vertex3fbuffer = R_Mesh_CreateMeshBuffer(mesh->vertex3f, mesh->numverts * sizeof(float[3]), loadmodel->name, false, false, false);
1219
1220         // upload short indices as a buffer
1221         if (mesh->element3s && !mesh->element3s_indexbuffer)
1222                 mesh->element3s_indexbuffer = R_Mesh_CreateMeshBuffer(mesh->element3s, mesh->numtriangles * sizeof(short[3]), loadmodel->name, true, false, true);
1223
1224         // upload int indices as a buffer
1225         if (mesh->element3i && !mesh->element3i_indexbuffer && !mesh->element3s)
1226                 mesh->element3i_indexbuffer = R_Mesh_CreateMeshBuffer(mesh->element3i, mesh->numtriangles * sizeof(int[3]), loadmodel->name, true, false, false);
1227
1228         // vertex buffer is several arrays and we put them in the same buffer
1229         //
1230         // is this wise?  the texcoordtexture2f array is used with dynamic
1231         // vertex/svector/tvector/normal when rendering animated models, on the
1232         // other hand animated models don't use a lot of vertices anyway...
1233         if (!mesh->vbo_vertexbuffer && !vid.useinterleavedarrays)
1234         {
1235                 size_t size;
1236                 unsigned char *mem;
1237                 size = 0;
1238                 mesh->vbooffset_vertex3f           = size;if (mesh->vertex3f          ) size += mesh->numverts * sizeof(float[3]);
1239                 mesh->vbooffset_svector3f          = size;if (mesh->svector3f         ) size += mesh->numverts * sizeof(float[3]);
1240                 mesh->vbooffset_tvector3f          = size;if (mesh->tvector3f         ) size += mesh->numverts * sizeof(float[3]);
1241                 mesh->vbooffset_normal3f           = size;if (mesh->normal3f          ) size += mesh->numverts * sizeof(float[3]);
1242                 mesh->vbooffset_texcoord2f         = size;if (mesh->texcoord2f        ) size += mesh->numverts * sizeof(float[2]);
1243                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
1244                 if (mesh->vertex3f          ) memcpy(mem + mesh->vbooffset_vertex3f          , mesh->vertex3f          , mesh->numverts * sizeof(float[3]));
1245                 if (mesh->svector3f         ) memcpy(mem + mesh->vbooffset_svector3f         , mesh->svector3f         , mesh->numverts * sizeof(float[3]));
1246                 if (mesh->tvector3f         ) memcpy(mem + mesh->vbooffset_tvector3f         , mesh->tvector3f         , mesh->numverts * sizeof(float[3]));
1247                 if (mesh->normal3f          ) memcpy(mem + mesh->vbooffset_normal3f          , mesh->normal3f          , mesh->numverts * sizeof(float[3]));
1248                 if (mesh->texcoord2f        ) memcpy(mem + mesh->vbooffset_texcoord2f        , mesh->texcoord2f        , mesh->numverts * sizeof(float[2]));
1249                 mesh->vbo_vertexbuffer = R_Mesh_CreateMeshBuffer(mem, size, "shadowmesh", false, false, false);
1250                 Mem_Free(mem);
1251         }
1252 }
1253
1254 shadowmesh_t *Mod_ShadowMesh_Finish(mempool_t *mempool, shadowmesh_t *firstmesh, qboolean light, qboolean neighbors, qboolean createvbo)
1255 {
1256         shadowmesh_t *mesh, *newmesh, *nextmesh;
1257         // reallocate meshs to conserve space
1258         for (mesh = firstmesh, firstmesh = NULL;mesh;mesh = nextmesh)
1259         {
1260                 nextmesh = mesh->next;
1261                 if (mesh->numverts >= 3 && mesh->numtriangles >= 1)
1262                 {
1263                         newmesh = Mod_ShadowMesh_ReAlloc(mempool, mesh, light, neighbors);
1264                         newmesh->next = firstmesh;
1265                         firstmesh = newmesh;
1266                         if (newmesh->element3s)
1267                         {
1268                                 int i;
1269                                 for (i = 0;i < newmesh->numtriangles*3;i++)
1270                                         newmesh->element3s[i] = newmesh->element3i[i];
1271                         }
1272                         if (createvbo)
1273                                 Mod_ShadowMesh_CreateVBOs(newmesh, mempool);
1274                 }
1275                 Mem_Free(mesh);
1276         }
1277
1278         // this can take a while, so let's do a keepalive here
1279         CL_KeepaliveMessage(false);
1280
1281         return firstmesh;
1282 }
1283
1284 void Mod_ShadowMesh_CalcBBox(shadowmesh_t *firstmesh, vec3_t mins, vec3_t maxs, vec3_t center, float *radius)
1285 {
1286         int i;
1287         shadowmesh_t *mesh;
1288         vec3_t nmins, nmaxs, ncenter, temp;
1289         float nradius2, dist2, *v;
1290         VectorClear(nmins);
1291         VectorClear(nmaxs);
1292         // calculate bbox
1293         for (mesh = firstmesh;mesh;mesh = mesh->next)
1294         {
1295                 if (mesh == firstmesh)
1296                 {
1297                         VectorCopy(mesh->vertex3f, nmins);
1298                         VectorCopy(mesh->vertex3f, nmaxs);
1299                 }
1300                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1301                 {
1302                         if (nmins[0] > v[0]) nmins[0] = v[0];if (nmaxs[0] < v[0]) nmaxs[0] = v[0];
1303                         if (nmins[1] > v[1]) nmins[1] = v[1];if (nmaxs[1] < v[1]) nmaxs[1] = v[1];
1304                         if (nmins[2] > v[2]) nmins[2] = v[2];if (nmaxs[2] < v[2]) nmaxs[2] = v[2];
1305                 }
1306         }
1307         // calculate center and radius
1308         ncenter[0] = (nmins[0] + nmaxs[0]) * 0.5f;
1309         ncenter[1] = (nmins[1] + nmaxs[1]) * 0.5f;
1310         ncenter[2] = (nmins[2] + nmaxs[2]) * 0.5f;
1311         nradius2 = 0;
1312         for (mesh = firstmesh;mesh;mesh = mesh->next)
1313         {
1314                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1315                 {
1316                         VectorSubtract(v, ncenter, temp);
1317                         dist2 = DotProduct(temp, temp);
1318                         if (nradius2 < dist2)
1319                                 nradius2 = dist2;
1320                 }
1321         }
1322         // return data
1323         if (mins)
1324                 VectorCopy(nmins, mins);
1325         if (maxs)
1326                 VectorCopy(nmaxs, maxs);
1327         if (center)
1328                 VectorCopy(ncenter, center);
1329         if (radius)
1330                 *radius = sqrt(nradius2);
1331 }
1332
1333 void Mod_ShadowMesh_Free(shadowmesh_t *mesh)
1334 {
1335         shadowmesh_t *nextmesh;
1336         for (;mesh;mesh = nextmesh)
1337         {
1338                 if (mesh->vertex3fbuffer)
1339                         R_Mesh_DestroyMeshBuffer(mesh->vertex3fbuffer);
1340                 if (mesh->vertexmeshbuffer)
1341                         R_Mesh_DestroyMeshBuffer(mesh->vertexmeshbuffer);
1342                 if (mesh->element3i_indexbuffer)
1343                         R_Mesh_DestroyMeshBuffer(mesh->element3i_indexbuffer);
1344                 if (mesh->element3s_indexbuffer)
1345                         R_Mesh_DestroyMeshBuffer(mesh->element3s_indexbuffer);
1346                 if (mesh->vbo_vertexbuffer)
1347                         R_Mesh_DestroyMeshBuffer(mesh->vbo_vertexbuffer);
1348                 nextmesh = mesh->next;
1349                 Mem_Free(mesh);
1350         }
1351 }
1352
1353 void Mod_CreateCollisionMesh(dp_model_t *mod)
1354 {
1355         int k, numcollisionmeshtriangles;
1356         qboolean usesinglecollisionmesh = false;
1357         const msurface_t *surface = NULL;
1358
1359         mempool_t *mempool = mod->mempool;
1360         if (!mempool && mod->brush.parentmodel)
1361                 mempool = mod->brush.parentmodel->mempool;
1362         // make a single combined collision mesh for physics engine use
1363         // TODO rewrite this to use the collision brushes as source, to fix issues with e.g. common/caulk which creates no drawsurface
1364         numcollisionmeshtriangles = 0;
1365         for (k = 0;k < mod->nummodelsurfaces;k++)
1366         {
1367                 surface = mod->data_surfaces + mod->firstmodelsurface + k;
1368                 if (!strcmp(surface->texture->name, "collision")) // found collision mesh
1369                 {
1370                         usesinglecollisionmesh = true;
1371                         numcollisionmeshtriangles = surface->num_triangles;
1372                         break;
1373                 }
1374                 if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1375                         continue;
1376                 numcollisionmeshtriangles += surface->num_triangles;
1377         }
1378         mod->brush.collisionmesh = Mod_ShadowMesh_Begin(mempool, numcollisionmeshtriangles * 3, numcollisionmeshtriangles, NULL, NULL, NULL, false, false, true);
1379         if (usesinglecollisionmesh)
1380                 Mod_ShadowMesh_AddMesh(mempool, mod->brush.collisionmesh, NULL, NULL, NULL, mod->surfmesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (mod->surfmesh.data_element3i + 3 * surface->num_firsttriangle));
1381         else
1382         {
1383                 for (k = 0;k < mod->nummodelsurfaces;k++)
1384                 {
1385                         surface = mod->data_surfaces + mod->firstmodelsurface + k;
1386                         if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1387                                 continue;
1388                         Mod_ShadowMesh_AddMesh(mempool, mod->brush.collisionmesh, NULL, NULL, NULL, mod->surfmesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (mod->surfmesh.data_element3i + 3 * surface->num_firsttriangle));
1389                 }
1390         }
1391         mod->brush.collisionmesh = Mod_ShadowMesh_Finish(mempool, mod->brush.collisionmesh, false, false, false);
1392 }
1393
1394 #if 0
1395 static void Mod_GetTerrainVertex3fTexCoord2fFromBGRA(const unsigned char *imagepixels, int imagewidth, int imageheight, int ix, int iy, float *vertex3f, float *texcoord2f, matrix4x4_t *pixelstepmatrix, matrix4x4_t *pixeltexturestepmatrix)
1396 {
1397         float v[3], tc[3];
1398         v[0] = ix;
1399         v[1] = iy;
1400         if (ix >= 0 && iy >= 0 && ix < imagewidth && iy < imageheight)
1401                 v[2] = (imagepixels[((iy*imagewidth)+ix)*4+0] + imagepixels[((iy*imagewidth)+ix)*4+1] + imagepixels[((iy*imagewidth)+ix)*4+2]) * (1.0f / 765.0f);
1402         else
1403                 v[2] = 0;
1404         Matrix4x4_Transform(pixelstepmatrix, v, vertex3f);
1405         Matrix4x4_Transform(pixeltexturestepmatrix, v, tc);
1406         texcoord2f[0] = tc[0];
1407         texcoord2f[1] = tc[1];
1408 }
1409
1410 static void Mod_GetTerrainVertexFromBGRA(const unsigned char *imagepixels, int imagewidth, int imageheight, int ix, int iy, float *vertex3f, float *svector3f, float *tvector3f, float *normal3f, float *texcoord2f, matrix4x4_t *pixelstepmatrix, matrix4x4_t *pixeltexturestepmatrix)
1411 {
1412         float vup[3], vdown[3], vleft[3], vright[3];
1413         float tcup[3], tcdown[3], tcleft[3], tcright[3];
1414         float sv[3], tv[3], nl[3];
1415         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, pixelstepmatrix, pixeltexturestepmatrix);
1416         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy - 1, vup, tcup, pixelstepmatrix, pixeltexturestepmatrix);
1417         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy + 1, vdown, tcdown, pixelstepmatrix, pixeltexturestepmatrix);
1418         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix - 1, iy, vleft, tcleft, pixelstepmatrix, pixeltexturestepmatrix);
1419         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix + 1, iy, vright, tcright, pixelstepmatrix, pixeltexturestepmatrix);
1420         Mod_BuildBumpVectors(vertex3f, vup, vright, texcoord2f, tcup, tcright, svector3f, tvector3f, normal3f);
1421         Mod_BuildBumpVectors(vertex3f, vright, vdown, texcoord2f, tcright, tcdown, sv, tv, nl);
1422         VectorAdd(svector3f, sv, svector3f);
1423         VectorAdd(tvector3f, tv, tvector3f);
1424         VectorAdd(normal3f, nl, normal3f);
1425         Mod_BuildBumpVectors(vertex3f, vdown, vleft, texcoord2f, tcdown, tcleft, sv, tv, nl);
1426         VectorAdd(svector3f, sv, svector3f);
1427         VectorAdd(tvector3f, tv, tvector3f);
1428         VectorAdd(normal3f, nl, normal3f);
1429         Mod_BuildBumpVectors(vertex3f, vleft, vup, texcoord2f, tcleft, tcup, sv, tv, nl);
1430         VectorAdd(svector3f, sv, svector3f);
1431         VectorAdd(tvector3f, tv, tvector3f);
1432         VectorAdd(normal3f, nl, normal3f);
1433 }
1434
1435 static void Mod_ConstructTerrainPatchFromBGRA(const unsigned char *imagepixels, int imagewidth, int imageheight, int x1, int y1, int width, int height, int *element3i, int *neighbor3i, float *vertex3f, float *svector3f, float *tvector3f, float *normal3f, float *texcoord2f, matrix4x4_t *pixelstepmatrix, matrix4x4_t *pixeltexturestepmatrix)
1436 {
1437         int x, y, ix, iy, *e;
1438         e = element3i;
1439         for (y = 0;y < height;y++)
1440         {
1441                 for (x = 0;x < width;x++)
1442                 {
1443                         e[0] = (y + 1) * (width + 1) + (x + 0);
1444                         e[1] = (y + 0) * (width + 1) + (x + 0);
1445                         e[2] = (y + 1) * (width + 1) + (x + 1);
1446                         e[3] = (y + 0) * (width + 1) + (x + 0);
1447                         e[4] = (y + 0) * (width + 1) + (x + 1);
1448                         e[5] = (y + 1) * (width + 1) + (x + 1);
1449                         e += 6;
1450                 }
1451         }
1452         Mod_BuildTriangleNeighbors(neighbor3i, element3i, width*height*2);
1453         for (y = 0, iy = y1;y < height + 1;y++, iy++)
1454                 for (x = 0, ix = x1;x < width + 1;x++, ix++, vertex3f += 3, texcoord2f += 2, svector3f += 3, tvector3f += 3, normal3f += 3)
1455                         Mod_GetTerrainVertexFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, svector3f, tvector3f, normal3f, pixelstepmatrix, pixeltexturestepmatrix);
1456 }
1457 #endif
1458
1459 #if 0
1460 void Mod_Terrain_SurfaceRecurseChunk(dp_model_t *model, int stepsize, int x, int y)
1461 {
1462         float mins[3];
1463         float maxs[3];
1464         float chunkwidth = min(stepsize, model->terrain.width - 1 - x);
1465         float chunkheight = min(stepsize, model->terrain.height - 1 - y);
1466         float viewvector[3];
1467         unsigned int firstvertex;
1468         unsigned int *e;
1469         float *v;
1470         if (chunkwidth < 2 || chunkheight < 2)
1471                 return;
1472         VectorSet(mins, model->terrain.mins[0] +  x    * stepsize * model->terrain.scale[0], model->terrain.mins[1] +  y    * stepsize * model->terrain.scale[1], model->terrain.mins[2]);
1473         VectorSet(maxs, model->terrain.mins[0] + (x+1) * stepsize * model->terrain.scale[0], model->terrain.mins[1] + (y+1) * stepsize * model->terrain.scale[1], model->terrain.maxs[2]);
1474         viewvector[0] = bound(mins[0], localvieworigin, maxs[0]) - model->terrain.vieworigin[0];
1475         viewvector[1] = bound(mins[1], localvieworigin, maxs[1]) - model->terrain.vieworigin[1];
1476         viewvector[2] = bound(mins[2], localvieworigin, maxs[2]) - model->terrain.vieworigin[2];
1477         if (stepsize > 1 && VectorLength(viewvector) < stepsize*model->terrain.scale[0]*r_terrain_lodscale.value)
1478         {
1479                 // too close for this stepsize, emit as 4 chunks instead
1480                 stepsize /= 2;
1481                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y);
1482                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y);
1483                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y+stepsize);
1484                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y+stepsize);
1485                 return;
1486         }
1487         // emit the geometry at stepsize into our vertex buffer / index buffer
1488         // we add two columns and two rows for skirt
1489         outwidth = chunkwidth+2;
1490         outheight = chunkheight+2;
1491         outwidth2 = outwidth-1;
1492         outheight2 = outheight-1;
1493         outwidth3 = outwidth+1;
1494         outheight3 = outheight+1;
1495         firstvertex = numvertices;
1496         e = model->terrain.element3i + numtriangles;
1497         numtriangles += chunkwidth*chunkheight*2+chunkwidth*2*2+chunkheight*2*2;
1498         v = model->terrain.vertex3f + numvertices;
1499         numvertices += (chunkwidth+1)*(chunkheight+1)+(chunkwidth+1)*2+(chunkheight+1)*2;
1500         // emit the triangles (note: the skirt is treated as two extra rows and two extra columns)
1501         for (ty = 0;ty < outheight;ty++)
1502         {
1503                 for (tx = 0;tx < outwidth;tx++)
1504                 {
1505                         *e++ = firstvertex + (ty  )*outwidth3+(tx  );
1506                         *e++ = firstvertex + (ty  )*outwidth3+(tx+1);
1507                         *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1508                         *e++ = firstvertex + (ty  )*outwidth3+(tx  );
1509                         *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1510                         *e++ = firstvertex + (ty+1)*outwidth3+(tx  );
1511                 }
1512         }
1513         // TODO: emit surface vertices (x+tx*stepsize, y+ty*stepsize)
1514         for (ty = 0;ty <= outheight;ty++)
1515         {
1516                 skirtrow = ty == 0 || ty == outheight;
1517                 ry = y+bound(1, ty, outheight)*stepsize;
1518                 for (tx = 0;tx <= outwidth;tx++)
1519                 {
1520                         skirt = skirtrow || tx == 0 || tx == outwidth;
1521                         rx = x+bound(1, tx, outwidth)*stepsize;
1522                         v[0] = rx*scale[0];
1523                         v[1] = ry*scale[1];
1524                         v[2] = heightmap[ry*terrainwidth+rx]*scale[2];
1525                         v += 3;
1526                 }
1527         }
1528         // TODO: emit skirt vertices
1529 }
1530
1531 void Mod_Terrain_UpdateSurfacesForViewOrigin(dp_model_t *model)
1532 {
1533         for (y = 0;y < model->terrain.size[1];y += model->terrain.
1534         Mod_Terrain_SurfaceRecurseChunk(model, model->terrain.maxstepsize, x, y);
1535         Mod_Terrain_BuildChunk(model, 
1536 }
1537 #endif
1538
1539 static int Mod_LoadQ3Shaders_EnumerateWaveFunc(const char *s)
1540 {
1541         int offset = 0;
1542         if (!strncasecmp(s, "user", 4)) // parse stuff like "user1sin", always user<n>func
1543         {
1544                 offset = bound(0, s[4] - '0', 9);
1545                 offset = (offset + 1) << Q3WAVEFUNC_USER_SHIFT;
1546                 s += 4;
1547                 if(*s)
1548                         ++s;
1549         }
1550         if (!strcasecmp(s, "sin"))             return offset | Q3WAVEFUNC_SIN;
1551         if (!strcasecmp(s, "square"))          return offset | Q3WAVEFUNC_SQUARE;
1552         if (!strcasecmp(s, "triangle"))        return offset | Q3WAVEFUNC_TRIANGLE;
1553         if (!strcasecmp(s, "sawtooth"))        return offset | Q3WAVEFUNC_SAWTOOTH;
1554         if (!strcasecmp(s, "inversesawtooth")) return offset | Q3WAVEFUNC_INVERSESAWTOOTH;
1555         if (!strcasecmp(s, "noise"))           return offset | Q3WAVEFUNC_NOISE;
1556         if (!strcasecmp(s, "none"))            return offset | Q3WAVEFUNC_NONE;
1557         Con_DPrintf("Mod_LoadQ3Shaders: unknown wavefunc %s\n", s);
1558         return offset | Q3WAVEFUNC_NONE;
1559 }
1560
1561 void Mod_FreeQ3Shaders(void)
1562 {
1563         Mem_FreePool(&q3shaders_mem);
1564 }
1565
1566 static void Q3Shader_AddToHash (q3shaderinfo_t* shader)
1567 {
1568         unsigned short hash = CRC_Block_CaseInsensitive ((const unsigned char *)shader->name, strlen (shader->name));
1569         q3shader_hash_entry_t* entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
1570         q3shader_hash_entry_t* lastEntry = NULL;
1571         while (entry != NULL)
1572         {
1573                 if (strcasecmp (entry->shader.name, shader->name) == 0)
1574                 {
1575                         // redeclaration
1576                         if(shader->dpshaderkill)
1577                         {
1578                                 // killed shader is a redeclarion? we can safely ignore it
1579                                 return;
1580                         }
1581                         else if(entry->shader.dpshaderkill)
1582                         {
1583                                 // replace the old shader!
1584                                 // this will skip the entry allocating part
1585                                 // below and just replace the shader
1586                                 break;
1587                         }
1588                         else
1589                         {
1590                                 unsigned char *start, *end, *start2;
1591                                 start = (unsigned char *) (&shader->Q3SHADERINFO_COMPARE_START);
1592                                 end = ((unsigned char *) (&shader->Q3SHADERINFO_COMPARE_END)) + sizeof(shader->Q3SHADERINFO_COMPARE_END);
1593                                 start2 = (unsigned char *) (&entry->shader.Q3SHADERINFO_COMPARE_START);
1594                                 if(memcmp(start, start2, end - start))
1595                                         Con_DPrintf("Shader '%s' already defined, ignoring mismatching redeclaration\n", shader->name);
1596                                 else
1597                                         Con_DPrintf("Shader '%s' already defined\n", shader->name);
1598                                 return;
1599                         }
1600                 }
1601                 lastEntry = entry;
1602                 entry = entry->chain;
1603         }
1604         if (entry == NULL)
1605         {
1606                 if (lastEntry->shader.name[0] != 0)
1607                 {
1608                         /* Add to chain */
1609                         q3shader_hash_entry_t* newEntry = (q3shader_hash_entry_t*)
1610                           Mem_ExpandableArray_AllocRecord (&q3shader_data->hash_entries);
1611
1612                         while (lastEntry->chain != NULL) lastEntry = lastEntry->chain;
1613                         lastEntry->chain = newEntry;
1614                         newEntry->chain = NULL;
1615                         lastEntry = newEntry;
1616                 }
1617                 /* else: head of chain, in hash entry array */
1618                 entry = lastEntry;
1619         }
1620         memcpy (&entry->shader, shader, sizeof (q3shaderinfo_t));
1621 }
1622
1623 extern cvar_t mod_noshader_default_offsetmapping;
1624 extern cvar_t mod_q3shader_default_offsetmapping;
1625 extern cvar_t mod_q3shader_default_offsetmapping_scale;
1626 extern cvar_t mod_q3shader_default_offsetmapping_bias;
1627 extern cvar_t mod_q3shader_default_polygonoffset;
1628 extern cvar_t mod_q3shader_default_polygonfactor;
1629 extern cvar_t mod_q3shader_force_addalpha;
1630 void Mod_LoadQ3Shaders(void)
1631 {
1632         int j;
1633         int fileindex;
1634         fssearch_t *search;
1635         char *f;
1636         const char *text;
1637         q3shaderinfo_t shader;
1638         q3shaderinfo_layer_t *layer;
1639         int numparameters;
1640         char parameter[TEXTURE_MAXFRAMES + 4][Q3PATHLENGTH];
1641         char *custsurfaceparmnames[256]; // VorteX: q3map2 has 64 but well, someone will need more
1642         unsigned long custsurfaceparms[256]; 
1643         int numcustsurfaceparms;
1644         qboolean dpshaderkill;
1645
1646         Mod_FreeQ3Shaders();
1647
1648         q3shaders_mem = Mem_AllocPool("q3shaders", 0, NULL);
1649         q3shader_data = (q3shader_data_t*)Mem_Alloc (q3shaders_mem,
1650                 sizeof (q3shader_data_t));
1651         Mem_ExpandableArray_NewArray (&q3shader_data->hash_entries,
1652                 q3shaders_mem, sizeof (q3shader_hash_entry_t), 256);
1653         Mem_ExpandableArray_NewArray (&q3shader_data->char_ptrs,
1654                 q3shaders_mem, sizeof (char**), 256);
1655
1656         // parse custinfoparms.txt
1657         numcustsurfaceparms = 0;
1658         if ((text = f = (char *)FS_LoadFile("scripts/custinfoparms.txt", tempmempool, false, NULL)) != NULL)
1659         {
1660                 if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1661                         Con_DPrintf("scripts/custinfoparms.txt: contentflags section parsing error - expected \"{\", found \"%s\"\n", com_token);
1662                 else
1663                 {
1664                         while (COM_ParseToken_QuakeC(&text, false))
1665                                 if (!strcasecmp(com_token, "}"))
1666                                         break;
1667                         // custom surfaceflags section
1668                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1669                                 Con_DPrintf("scripts/custinfoparms.txt: surfaceflags section parsing error - expected \"{\", found \"%s\"\n", com_token);
1670                         else
1671                         {
1672                                 while(COM_ParseToken_QuakeC(&text, false))
1673                                 {
1674                                         if (!strcasecmp(com_token, "}"))
1675                                                 break;  
1676                                         // register surfaceflag
1677                                         if (numcustsurfaceparms >= 256)
1678                                         {
1679                                                 Con_Printf("scripts/custinfoparms.txt: surfaceflags section parsing error - max 256 surfaceflags exceeded\n");
1680                                                 break;
1681                                         }
1682                                         // name
1683                                         j = strlen(com_token)+1;
1684                                         custsurfaceparmnames[numcustsurfaceparms] = (char *)Mem_Alloc(tempmempool, j);
1685                                         strlcpy(custsurfaceparmnames[numcustsurfaceparms], com_token, j+1);
1686                                         // value
1687                                         if (COM_ParseToken_QuakeC(&text, false))
1688                                                 custsurfaceparms[numcustsurfaceparms] = strtol(com_token, NULL, 0);
1689                                         else
1690                                                 custsurfaceparms[numcustsurfaceparms] = 0;
1691                                         numcustsurfaceparms++;
1692                                 }
1693                         }
1694                 }
1695                 Mem_Free(f);
1696         }
1697
1698         // parse shaders
1699         search = FS_Search("scripts/*.shader", true, false);
1700         if (!search)
1701                 return;
1702         for (fileindex = 0;fileindex < search->numfilenames;fileindex++)
1703         {
1704                 text = f = (char *)FS_LoadFile(search->filenames[fileindex], tempmempool, false, NULL);
1705                 if (!f)
1706                         continue;
1707                 while (COM_ParseToken_QuakeC(&text, false))
1708                 {
1709                         memset (&shader, 0, sizeof(shader));
1710                         shader.reflectmin = 0;
1711                         shader.reflectmax = 1;
1712                         shader.refractfactor = 1;
1713                         Vector4Set(shader.refractcolor4f, 1, 1, 1, 1);
1714                         shader.reflectfactor = 1;
1715                         Vector4Set(shader.reflectcolor4f, 1, 1, 1, 1);
1716                         shader.r_water_wateralpha = 1;
1717                         shader.offsetmapping = (mod_q3shader_default_offsetmapping.value) ? OFFSETMAPPING_DEFAULT : OFFSETMAPPING_OFF;
1718                         shader.offsetscale = mod_q3shader_default_offsetmapping_scale.value;
1719                         shader.offsetbias = mod_q3shader_default_offsetmapping_bias.value;
1720                         shader.specularscalemod = 1;
1721                         shader.specularpowermod = 1;
1722                         shader.biaspolygonoffset = mod_q3shader_default_polygonoffset.value;
1723                         shader.biaspolygonfactor = mod_q3shader_default_polygonfactor.value;
1724
1725                         strlcpy(shader.name, com_token, sizeof(shader.name));
1726                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1727                         {
1728                                 Con_DPrintf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[fileindex], com_token);
1729                                 break;
1730                         }
1731                         while (COM_ParseToken_QuakeC(&text, false))
1732                         {
1733                                 if (!strcasecmp(com_token, "}"))
1734                                         break;
1735                                 if (!strcasecmp(com_token, "{"))
1736                                 {
1737                                         static q3shaderinfo_layer_t dummy;
1738                                         if (shader.numlayers < Q3SHADER_MAXLAYERS)
1739                                         {
1740                                                 layer = shader.layers + shader.numlayers++;
1741                                         }
1742                                         else
1743                                         {
1744                                                 // parse and process it anyway, just don't store it (so a map $lightmap or such stuff still is found)
1745                                                 memset(&dummy, 0, sizeof(dummy));
1746                                                 layer = &dummy;
1747                                         }
1748                                         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1749                                         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1750                                         layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1751                                         layer->blendfunc[0] = GL_ONE;
1752                                         layer->blendfunc[1] = GL_ZERO;
1753                                         while (COM_ParseToken_QuakeC(&text, false))
1754                                         {
1755                                                 if (!strcasecmp(com_token, "}"))
1756                                                         break;
1757                                                 if (!strcasecmp(com_token, "\n"))
1758                                                         continue;
1759                                                 numparameters = 0;
1760                                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1761                                                 {
1762                                                         if (j < TEXTURE_MAXFRAMES + 4)
1763                                                         {
1764                                                                 // remap dp_water to dpwater, dp_reflect to dpreflect, etc.
1765                                                                 if(j == 0 && !strncasecmp(com_token, "dp_", 3))
1766                                                                         dpsnprintf(parameter[j], sizeof(parameter[j]), "dp%s", &com_token[3]);
1767                                                                 else
1768                                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1769                                                                 numparameters = j + 1;
1770                                                         }
1771                                                         if (!COM_ParseToken_QuakeC(&text, true))
1772                                                                 break;
1773                                                 }
1774                                                 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1775                                                 //      parameter[j][0] = 0;
1776                                                 if (developer_insane.integer)
1777                                                 {
1778                                                         Con_DPrintf("%s %i: ", shader.name, shader.numlayers - 1);
1779                                                         for (j = 0;j < numparameters;j++)
1780                                                                 Con_DPrintf(" %s", parameter[j]);
1781                                                         Con_DPrint("\n");
1782                                                 }
1783                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "blendfunc"))
1784                                                 {
1785                                                         if (numparameters == 2)
1786                                                         {
1787                                                                 if (!strcasecmp(parameter[1], "add"))
1788                                                                 {
1789                                                                         layer->blendfunc[0] = GL_ONE;
1790                                                                         layer->blendfunc[1] = GL_ONE;
1791                                                                 }
1792                                                                 else if (!strcasecmp(parameter[1], "addalpha"))
1793                                                                 {
1794                                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1795                                                                         layer->blendfunc[1] = GL_ONE;
1796                                                                 }
1797                                                                 else if (!strcasecmp(parameter[1], "filter"))
1798                                                                 {
1799                                                                         layer->blendfunc[0] = GL_DST_COLOR;
1800                                                                         layer->blendfunc[1] = GL_ZERO;
1801                                                                 }
1802                                                                 else if (!strcasecmp(parameter[1], "blend"))
1803                                                                 {
1804                                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1805                                                                         layer->blendfunc[1] = GL_ONE_MINUS_SRC_ALPHA;
1806                                                                 }
1807                                                         }
1808                                                         else if (numparameters == 3)
1809                                                         {
1810                                                                 int k;
1811                                                                 for (k = 0;k < 2;k++)
1812                                                                 {
1813                                                                         if (!strcasecmp(parameter[k+1], "GL_ONE"))
1814                                                                                 layer->blendfunc[k] = GL_ONE;
1815                                                                         else if (!strcasecmp(parameter[k+1], "GL_ZERO"))
1816                                                                                 layer->blendfunc[k] = GL_ZERO;
1817                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_COLOR"))
1818                                                                                 layer->blendfunc[k] = GL_SRC_COLOR;
1819                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_ALPHA"))
1820                                                                                 layer->blendfunc[k] = GL_SRC_ALPHA;
1821                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_COLOR"))
1822                                                                                 layer->blendfunc[k] = GL_DST_COLOR;
1823                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_ALPHA"))
1824                                                                                 layer->blendfunc[k] = GL_DST_ALPHA;
1825                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_COLOR"))
1826                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_COLOR;
1827                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_ALPHA"))
1828                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_ALPHA;
1829                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_COLOR"))
1830                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_COLOR;
1831                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_ALPHA"))
1832                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1833                                                                         else
1834                                                                                 layer->blendfunc[k] = GL_ONE; // default in case of parsing error
1835                                                                 }
1836                                                         }
1837                                                 }
1838                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
1839                                                         layer->alphatest = true;
1840                                                 if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
1841                                                 {
1842                                                         if (!strcasecmp(parameter[0], "clampmap"))
1843                                                                 layer->clampmap = true;
1844                                                         layer->numframes = 1;
1845                                                         layer->framerate = 1;
1846                                                         layer->texturename = (char**)Mem_ExpandableArray_AllocRecord (
1847                                                                 &q3shader_data->char_ptrs);
1848                                                         layer->texturename[0] = Mem_strdup (q3shaders_mem, parameter[1]);
1849                                                         if (!strcasecmp(parameter[1], "$lightmap"))
1850                                                                 shader.lighting = true;
1851                                                 }
1852                                                 else if (numparameters >= 3 && (!strcasecmp(parameter[0], "animmap") || !strcasecmp(parameter[0], "animclampmap")))
1853                                                 {
1854                                                         int i;
1855                                                         layer->numframes = min(numparameters - 2, TEXTURE_MAXFRAMES);
1856                                                         layer->framerate = atof(parameter[1]);
1857                                                         layer->texturename = (char **) Mem_Alloc (q3shaders_mem, sizeof (char*) * layer->numframes);
1858                                                         for (i = 0;i < layer->numframes;i++)
1859                                                                 layer->texturename[i] = Mem_strdup (q3shaders_mem, parameter[i + 2]);
1860                                                 }
1861                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "rgbgen"))
1862                                                 {
1863                                                         int i;
1864                                                         for (i = 0;i < numparameters - 2 && i < Q3RGBGEN_MAXPARMS;i++)
1865                                                                 layer->rgbgen.parms[i] = atof(parameter[i+2]);
1866                                                              if (!strcasecmp(parameter[1], "identity"))         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1867                                                         else if (!strcasecmp(parameter[1], "const"))            layer->rgbgen.rgbgen = Q3RGBGEN_CONST;
1868                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->rgbgen.rgbgen = Q3RGBGEN_ENTITY;
1869                                                         else if (!strcasecmp(parameter[1], "exactvertex"))      layer->rgbgen.rgbgen = Q3RGBGEN_EXACTVERTEX;
1870                                                         else if (!strcasecmp(parameter[1], "identitylighting")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITYLIGHTING;
1871                                                         else if (!strcasecmp(parameter[1], "lightingdiffuse"))  layer->rgbgen.rgbgen = Q3RGBGEN_LIGHTINGDIFFUSE;
1872                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSENTITY;
1873                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSVERTEX;
1874                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->rgbgen.rgbgen = Q3RGBGEN_VERTEX;
1875                                                         else if (!strcasecmp(parameter[1], "wave"))
1876                                                         {
1877                                                                 layer->rgbgen.rgbgen = Q3RGBGEN_WAVE;
1878                                                                 layer->rgbgen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1879                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1880                                                                         layer->rgbgen.waveparms[i] = atof(parameter[i+3]);
1881                                                         }
1882                                                         else Con_DPrintf("%s parsing warning: unknown rgbgen %s\n", search->filenames[fileindex], parameter[1]);
1883                                                 }
1884                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphagen"))
1885                                                 {
1886                                                         int i;
1887                                                         for (i = 0;i < numparameters - 2 && i < Q3ALPHAGEN_MAXPARMS;i++)
1888                                                                 layer->alphagen.parms[i] = atof(parameter[i+2]);
1889                                                              if (!strcasecmp(parameter[1], "identity"))         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1890                                                         else if (!strcasecmp(parameter[1], "const"))            layer->alphagen.alphagen = Q3ALPHAGEN_CONST;
1891                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->alphagen.alphagen = Q3ALPHAGEN_ENTITY;
1892                                                         else if (!strcasecmp(parameter[1], "lightingspecular")) layer->alphagen.alphagen = Q3ALPHAGEN_LIGHTINGSPECULAR;
1893                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSENTITY;
1894                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSVERTEX;
1895                                                         else if (!strcasecmp(parameter[1], "portal"))           layer->alphagen.alphagen = Q3ALPHAGEN_PORTAL;
1896                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->alphagen.alphagen = Q3ALPHAGEN_VERTEX;
1897                                                         else if (!strcasecmp(parameter[1], "wave"))
1898                                                         {
1899                                                                 layer->alphagen.alphagen = Q3ALPHAGEN_WAVE;
1900                                                                 layer->alphagen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1901                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1902                                                                         layer->alphagen.waveparms[i] = atof(parameter[i+3]);
1903                                                         }
1904                                                         else Con_DPrintf("%s parsing warning: unknown alphagen %s\n", search->filenames[fileindex], parameter[1]);
1905                                                 }
1906                                                 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "texgen") || !strcasecmp(parameter[0], "tcgen")))
1907                                                 {
1908                                                         int i;
1909                                                         // observed values: tcgen environment
1910                                                         // no other values have been observed in real shaders
1911                                                         for (i = 0;i < numparameters - 2 && i < Q3TCGEN_MAXPARMS;i++)
1912                                                                 layer->tcgen.parms[i] = atof(parameter[i+2]);
1913                                                              if (!strcasecmp(parameter[1], "base"))        layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1914                                                         else if (!strcasecmp(parameter[1], "texture"))     layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1915                                                         else if (!strcasecmp(parameter[1], "environment")) layer->tcgen.tcgen = Q3TCGEN_ENVIRONMENT;
1916                                                         else if (!strcasecmp(parameter[1], "lightmap"))    layer->tcgen.tcgen = Q3TCGEN_LIGHTMAP;
1917                                                         else if (!strcasecmp(parameter[1], "vector"))      layer->tcgen.tcgen = Q3TCGEN_VECTOR;
1918                                                         else Con_DPrintf("%s parsing warning: unknown tcgen mode %s\n", search->filenames[fileindex], parameter[1]);
1919                                                 }
1920                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "tcmod"))
1921                                                 {
1922                                                         int i, tcmodindex;
1923                                                         // observed values:
1924                                                         // tcmod rotate #
1925                                                         // tcmod scale # #
1926                                                         // tcmod scroll # #
1927                                                         // tcmod stretch sin # # # #
1928                                                         // tcmod stretch triangle # # # #
1929                                                         // tcmod transform # # # # # #
1930                                                         // tcmod turb # # # #
1931                                                         // tcmod turb sin # # # #  (this is bogus)
1932                                                         // no other values have been observed in real shaders
1933                                                         for (tcmodindex = 0;tcmodindex < Q3MAXTCMODS;tcmodindex++)
1934                                                                 if (!layer->tcmods[tcmodindex].tcmod)
1935                                                                         break;
1936                                                         if (tcmodindex < Q3MAXTCMODS)
1937                                                         {
1938                                                                 for (i = 0;i < numparameters - 2 && i < Q3TCMOD_MAXPARMS;i++)
1939                                                                         layer->tcmods[tcmodindex].parms[i] = atof(parameter[i+2]);
1940                                                                          if (!strcasecmp(parameter[1], "entitytranslate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ENTITYTRANSLATE;
1941                                                                 else if (!strcasecmp(parameter[1], "rotate"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ROTATE;
1942                                                                 else if (!strcasecmp(parameter[1], "scale"))           layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCALE;
1943                                                                 else if (!strcasecmp(parameter[1], "scroll"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCROLL;
1944                                                                 else if (!strcasecmp(parameter[1], "page"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_PAGE;
1945                                                                 else if (!strcasecmp(parameter[1], "stretch"))
1946                                                                 {
1947                                                                         layer->tcmods[tcmodindex].tcmod = Q3TCMOD_STRETCH;
1948                                                                         layer->tcmods[tcmodindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1949                                                                         for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1950                                                                                 layer->tcmods[tcmodindex].waveparms[i] = atof(parameter[i+3]);
1951                                                                 }
1952                                                                 else if (!strcasecmp(parameter[1], "transform"))       layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TRANSFORM;
1953                                                                 else if (!strcasecmp(parameter[1], "turb"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TURBULENT;
1954                                                                 else Con_DPrintf("%s parsing warning: unknown tcmod mode %s\n", search->filenames[fileindex], parameter[1]);
1955                                                         }
1956                                                         else
1957                                                                 Con_DPrintf("%s parsing warning: too many tcmods on one layer\n", search->filenames[fileindex]);
1958                                                 }
1959                                                 // break out a level if it was a closing brace (not using the character here to not confuse vim)
1960                                                 if (!strcasecmp(com_token, "}"))
1961                                                         break;
1962                                         }
1963                                         if (layer->rgbgen.rgbgen == Q3RGBGEN_LIGHTINGDIFFUSE || layer->rgbgen.rgbgen == Q3RGBGEN_VERTEX)
1964                                                 shader.lighting = true;
1965                                         if (layer->alphagen.alphagen == Q3ALPHAGEN_VERTEX)
1966                                         {
1967                                                 if (layer == shader.layers + 0)
1968                                                 {
1969                                                         // vertex controlled transparency
1970                                                         shader.vertexalpha = true;
1971                                                 }
1972                                                 else
1973                                                 {
1974                                                         // multilayer terrain shader or similar
1975                                                         shader.textureblendalpha = true;
1976                                                 }
1977                                         }
1978
1979                                         if(mod_q3shader_force_addalpha.integer)
1980                                         {
1981                                                 // for a long while, DP treated GL_ONE GL_ONE as GL_SRC_ALPHA GL_ONE
1982                                                 // this cvar brings back this behaviour
1983                                                 if(layer->blendfunc[0] == GL_ONE && layer->blendfunc[1] == GL_ONE)
1984                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1985                                         }
1986
1987                                         layer->texflags = 0;
1988                                         if (layer->alphatest)
1989                                                 layer->texflags |= TEXF_ALPHA;
1990                                         switch(layer->blendfunc[0])
1991                                         {
1992                                                 case GL_SRC_ALPHA:
1993                                                 case GL_ONE_MINUS_SRC_ALPHA:
1994                                                         layer->texflags |= TEXF_ALPHA;
1995                                                         break;
1996                                         }
1997                                         switch(layer->blendfunc[1])
1998                                         {
1999                                                 case GL_SRC_ALPHA:
2000                                                 case GL_ONE_MINUS_SRC_ALPHA:
2001                                                         layer->texflags |= TEXF_ALPHA;
2002                                                         break;
2003                                         }
2004                                         if (!(shader.surfaceparms & Q3SURFACEPARM_NOMIPMAPS))
2005                                                 layer->texflags |= TEXF_MIPMAP;
2006                                         if (!(shader.textureflags & Q3TEXTUREFLAG_NOPICMIP))
2007                                                 layer->texflags |= TEXF_PICMIP | TEXF_COMPRESS;
2008                                         if (layer->clampmap)
2009                                                 layer->texflags |= TEXF_CLAMP;
2010                                         continue;
2011                                 }
2012                                 numparameters = 0;
2013                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
2014                                 {
2015                                         if (j < TEXTURE_MAXFRAMES + 4)
2016                                         {
2017                                                 // remap dp_water to dpwater, dp_reflect to dpreflect, etc.
2018                                                 if(j == 0 && !strncasecmp(com_token, "dp_", 3))
2019                                                         dpsnprintf(parameter[j], sizeof(parameter[j]), "dp%s", &com_token[3]);
2020                                                 else
2021                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
2022                                                 numparameters = j + 1;
2023                                         }
2024                                         if (!COM_ParseToken_QuakeC(&text, true))
2025                                                 break;
2026                                 }
2027                                 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
2028                                 //      parameter[j][0] = 0;
2029                                 if (fileindex == 0 && !strcasecmp(com_token, "}"))
2030                                         break;
2031                                 if (developer_insane.integer)
2032                                 {
2033                                         Con_DPrintf("%s: ", shader.name);
2034                                         for (j = 0;j < numparameters;j++)
2035                                                 Con_DPrintf(" %s", parameter[j]);
2036                                         Con_DPrint("\n");
2037                                 }
2038                                 if (numparameters < 1)
2039                                         continue;
2040                                 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
2041                                 {
2042                                         if (!strcasecmp(parameter[1], "alphashadow"))
2043                                                 shader.surfaceparms |= Q3SURFACEPARM_ALPHASHADOW;
2044                                         else if (!strcasecmp(parameter[1], "areaportal"))
2045                                                 shader.surfaceparms |= Q3SURFACEPARM_AREAPORTAL;
2046                                         else if (!strcasecmp(parameter[1], "botclip"))
2047                                                 shader.surfaceparms |= Q3SURFACEPARM_BOTCLIP;
2048                                         else if (!strcasecmp(parameter[1], "clusterportal"))
2049                                                 shader.surfaceparms |= Q3SURFACEPARM_CLUSTERPORTAL;
2050                                         else if (!strcasecmp(parameter[1], "detail"))
2051                                                 shader.surfaceparms |= Q3SURFACEPARM_DETAIL;
2052                                         else if (!strcasecmp(parameter[1], "donotenter"))
2053                                                 shader.surfaceparms |= Q3SURFACEPARM_DONOTENTER;
2054                                         else if (!strcasecmp(parameter[1], "dust"))
2055                                                 shader.surfaceparms |= Q3SURFACEPARM_DUST;
2056                                         else if (!strcasecmp(parameter[1], "hint"))
2057                                                 shader.surfaceparms |= Q3SURFACEPARM_HINT;
2058                                         else if (!strcasecmp(parameter[1], "fog"))
2059                                                 shader.surfaceparms |= Q3SURFACEPARM_FOG;
2060                                         else if (!strcasecmp(parameter[1], "lava"))
2061                                                 shader.surfaceparms |= Q3SURFACEPARM_LAVA;
2062                                         else if (!strcasecmp(parameter[1], "lightfilter"))
2063                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTFILTER;
2064                                         else if (!strcasecmp(parameter[1], "lightgrid"))
2065                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTGRID;
2066                                         else if (!strcasecmp(parameter[1], "metalsteps"))
2067                                                 shader.surfaceparms |= Q3SURFACEPARM_METALSTEPS;
2068                                         else if (!strcasecmp(parameter[1], "nodamage"))
2069                                                 shader.surfaceparms |= Q3SURFACEPARM_NODAMAGE;
2070                                         else if (!strcasecmp(parameter[1], "nodlight"))
2071                                                 shader.surfaceparms |= Q3SURFACEPARM_NODLIGHT;
2072                                         else if (!strcasecmp(parameter[1], "nodraw"))
2073                                                 shader.surfaceparms |= Q3SURFACEPARM_NODRAW;
2074                                         else if (!strcasecmp(parameter[1], "nodrop"))
2075                                                 shader.surfaceparms |= Q3SURFACEPARM_NODROP;
2076                                         else if (!strcasecmp(parameter[1], "noimpact"))
2077                                                 shader.surfaceparms |= Q3SURFACEPARM_NOIMPACT;
2078                                         else if (!strcasecmp(parameter[1], "nolightmap"))
2079                                                 shader.surfaceparms |= Q3SURFACEPARM_NOLIGHTMAP;
2080                                         else if (!strcasecmp(parameter[1], "nomarks"))
2081                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMARKS;
2082                                         else if (!strcasecmp(parameter[1], "nomipmaps"))
2083                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
2084                                         else if (!strcasecmp(parameter[1], "nonsolid"))
2085                                                 shader.surfaceparms |= Q3SURFACEPARM_NONSOLID;
2086                                         else if (!strcasecmp(parameter[1], "origin"))
2087                                                 shader.surfaceparms |= Q3SURFACEPARM_ORIGIN;
2088                                         else if (!strcasecmp(parameter[1], "playerclip"))
2089                                                 shader.surfaceparms |= Q3SURFACEPARM_PLAYERCLIP;
2090                                         else if (!strcasecmp(parameter[1], "sky"))
2091                                                 shader.surfaceparms |= Q3SURFACEPARM_SKY;
2092                                         else if (!strcasecmp(parameter[1], "slick"))
2093                                                 shader.surfaceparms |= Q3SURFACEPARM_SLICK;
2094                                         else if (!strcasecmp(parameter[1], "slime"))
2095                                                 shader.surfaceparms |= Q3SURFACEPARM_SLIME;
2096                                         else if (!strcasecmp(parameter[1], "structural"))
2097                                                 shader.surfaceparms |= Q3SURFACEPARM_STRUCTURAL;
2098                                         else if (!strcasecmp(parameter[1], "trans"))
2099                                                 shader.surfaceparms |= Q3SURFACEPARM_TRANS;
2100                                         else if (!strcasecmp(parameter[1], "water"))
2101                                                 shader.surfaceparms |= Q3SURFACEPARM_WATER;
2102                                         else if (!strcasecmp(parameter[1], "pointlight"))
2103                                                 shader.surfaceparms |= Q3SURFACEPARM_POINTLIGHT;
2104                                         else if (!strcasecmp(parameter[1], "antiportal"))
2105                                                 shader.surfaceparms |= Q3SURFACEPARM_ANTIPORTAL;
2106                                         else
2107                                         {
2108                                                 // try custom surfaceparms
2109                                                 for (j = 0; j < numcustsurfaceparms; j++)
2110                                                 {
2111                                                         if (!strcasecmp(custsurfaceparmnames[j], parameter[1]))
2112                                                         {
2113                                                                 shader.surfaceparms |= custsurfaceparms[j];
2114                                                                 break;
2115                                                         }
2116                                                 }
2117                                                 // failed all
2118                                                 if (j == numcustsurfaceparms)
2119                                                         Con_DPrintf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[fileindex], parameter[1]);
2120                                         }
2121                                 }
2122                                 else if (!strcasecmp(parameter[0], "dpshadow"))
2123                                         shader.dpshadow = true;
2124                                 else if (!strcasecmp(parameter[0], "dpnoshadow"))
2125                                         shader.dpnoshadow = true;
2126                                 else if (!strcasecmp(parameter[0], "dpnortlight"))
2127                                         shader.dpnortlight = true;
2128                                 else if (!strcasecmp(parameter[0], "dpreflectcube"))
2129                                         strlcpy(shader.dpreflectcube, parameter[1], sizeof(shader.dpreflectcube));
2130                                 else if (!strcasecmp(parameter[0], "dpmeshcollisions"))
2131                                         shader.dpmeshcollisions = true;
2132                                 // this sets dpshaderkill to true if dpshaderkillifcvarzero was used, and to false if dpnoshaderkillifcvarzero was used
2133                                 else if (((dpshaderkill = !strcasecmp(parameter[0], "dpshaderkillifcvarzero")) || !strcasecmp(parameter[0], "dpnoshaderkillifcvarzero")) && numparameters >= 2)
2134                                 {
2135                                         if (Cvar_VariableValue(parameter[1]) == 0.0f)
2136                                                 shader.dpshaderkill = dpshaderkill;
2137                                 }
2138                                 // this sets dpshaderkill to true if dpshaderkillifcvar was used, and to false if dpnoshaderkillifcvar was used
2139                                 else if (((dpshaderkill = !strcasecmp(parameter[0], "dpshaderkillifcvar")) || !strcasecmp(parameter[0], "dpnoshaderkillifcvar")) && numparameters >= 2)
2140                                 {
2141                                         const char *op = NULL;
2142                                         if (numparameters >= 3)
2143                                                 op = parameter[2];
2144                                         if(!op)
2145                                         {
2146                                                 if (Cvar_VariableValue(parameter[1]) != 0.0f)
2147                                                         shader.dpshaderkill = dpshaderkill;
2148                                         }
2149                                         else if (numparameters >= 4 && !strcmp(op, "=="))
2150                                         {
2151                                                 if (Cvar_VariableValue(parameter[1]) == atof(parameter[3]))
2152                                                         shader.dpshaderkill = dpshaderkill;
2153                                         }
2154                                         else if (numparameters >= 4 && !strcmp(op, "!="))
2155                                         {
2156                                                 if (Cvar_VariableValue(parameter[1]) != atof(parameter[3]))
2157                                                         shader.dpshaderkill = dpshaderkill;
2158                                         }
2159                                         else if (numparameters >= 4 && !strcmp(op, ">"))
2160                                         {
2161                                                 if (Cvar_VariableValue(parameter[1]) > atof(parameter[3]))
2162                                                         shader.dpshaderkill = dpshaderkill;
2163                                         }
2164                                         else if (numparameters >= 4 && !strcmp(op, "<"))
2165                                         {
2166                                                 if (Cvar_VariableValue(parameter[1]) < atof(parameter[3]))
2167                                                         shader.dpshaderkill = dpshaderkill;
2168                                         }
2169                                         else if (numparameters >= 4 && !strcmp(op, ">="))
2170                                         {
2171                                                 if (Cvar_VariableValue(parameter[1]) >= atof(parameter[3]))
2172                                                         shader.dpshaderkill = dpshaderkill;
2173                                         }
2174                                         else if (numparameters >= 4 && !strcmp(op, "<="))
2175                                         {
2176                                                 if (Cvar_VariableValue(parameter[1]) <= atof(parameter[3]))
2177                                                         shader.dpshaderkill = dpshaderkill;
2178                                         }
2179                                         else
2180                                         {
2181                                                 Con_DPrintf("%s parsing warning: unknown dpshaderkillifcvar op \"%s\", or not enough arguments\n", search->filenames[fileindex], op);
2182                                         }
2183                                 }
2184                                 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
2185                                 {
2186                                         // some q3 skies don't have the sky parm set
2187                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
2188                                         strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
2189                                 }
2190                                 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
2191                                 {
2192                                         // some q3 skies don't have the sky parm set
2193                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
2194                                         if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
2195                                                 strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
2196                                 }
2197                                 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
2198                                 {
2199                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
2200                                                 shader.textureflags |= Q3TEXTUREFLAG_TWOSIDED;
2201                                 }
2202                                 else if (!strcasecmp(parameter[0], "nomipmaps"))
2203                                         shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
2204                                 else if (!strcasecmp(parameter[0], "nopicmip"))
2205                                         shader.textureflags |= Q3TEXTUREFLAG_NOPICMIP;
2206                                 else if (!strcasecmp(parameter[0], "polygonoffset"))
2207                                         shader.textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
2208                                 else if (!strcasecmp(parameter[0], "dppolygonoffset"))
2209                                 {
2210                                         shader.textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
2211                                         if(numparameters >= 2)
2212                                         {
2213                                                 shader.biaspolygonfactor = atof(parameter[1]);
2214                                                 if(numparameters >= 3)
2215                                                         shader.biaspolygonoffset = atof(parameter[2]);
2216                                                 else
2217                                                         shader.biaspolygonoffset = 0;
2218                                         }
2219                                 }
2220                                 else if (!strcasecmp(parameter[0], "dprefract") && numparameters >= 5)
2221                                 {
2222                                         shader.textureflags |= Q3TEXTUREFLAG_REFRACTION;
2223                                         shader.refractfactor = atof(parameter[1]);
2224                                         Vector4Set(shader.refractcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), 1);
2225                                 }
2226                                 else if (!strcasecmp(parameter[0], "dpreflect") && numparameters >= 6)
2227                                 {
2228                                         shader.textureflags |= Q3TEXTUREFLAG_REFLECTION;
2229                                         shader.reflectfactor = atof(parameter[1]);
2230                                         Vector4Set(shader.reflectcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), atof(parameter[5]));
2231                                 }
2232                                 else if (!strcasecmp(parameter[0], "dpcamera"))
2233                                 {
2234                                         shader.textureflags |= Q3TEXTUREFLAG_CAMERA;
2235                                 }
2236                                 else if (!strcasecmp(parameter[0], "dpwater") && numparameters >= 12)
2237                                 {
2238                                         shader.textureflags |= Q3TEXTUREFLAG_WATERSHADER;
2239                                         shader.reflectmin = atof(parameter[1]);
2240                                         shader.reflectmax = atof(parameter[2]);
2241                                         shader.refractfactor = atof(parameter[3]);
2242                                         shader.reflectfactor = atof(parameter[4]);
2243                                         Vector4Set(shader.refractcolor4f, atof(parameter[5]), atof(parameter[6]), atof(parameter[7]), 1);
2244                                         Vector4Set(shader.reflectcolor4f, atof(parameter[8]), atof(parameter[9]), atof(parameter[10]), 1);
2245                                         shader.r_water_wateralpha = atof(parameter[11]);
2246                                 }
2247                                 else if (!strcasecmp(parameter[0], "dpwaterscroll") && numparameters >= 3)
2248                                 {
2249                                         shader.r_water_waterscroll[0] = 1/atof(parameter[1]);
2250                                         shader.r_water_waterscroll[1] = 1/atof(parameter[2]);
2251                                 }
2252                                 else if (!strcasecmp(parameter[0], "dpglossintensitymod") && numparameters >= 2)
2253                                 {
2254                                         shader.specularscalemod = atof(parameter[1]);
2255                                 }
2256                                 else if (!strcasecmp(parameter[0], "dpglossexponentmod") && numparameters >= 2)
2257                                 {
2258                                         shader.specularpowermod = atof(parameter[1]);
2259                                 }
2260                                 else if (!strcasecmp(parameter[0], "dprtlightambient") && numparameters >= 2)
2261                                 {
2262                                         shader.rtlightambient = atof(parameter[1]);
2263                                 }
2264                                 else if (!strcasecmp(parameter[0], "dpoffsetmapping") && numparameters >= 2)
2265                                 {
2266                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "off"))
2267                                                 shader.offsetmapping = OFFSETMAPPING_OFF;
2268                                         else if (!strcasecmp(parameter[1], "default") || !strcasecmp(parameter[1], "normal"))
2269                                                 shader.offsetmapping = OFFSETMAPPING_DEFAULT;
2270                                         else if (!strcasecmp(parameter[1], "linear"))
2271                                                 shader.offsetmapping = OFFSETMAPPING_LINEAR;
2272                                         else if (!strcasecmp(parameter[1], "relief"))
2273                                                 shader.offsetmapping = OFFSETMAPPING_RELIEF;
2274                                         if (numparameters >= 3)
2275                                                 shader.offsetscale = atof(parameter[2]);
2276                                         if (numparameters >= 5)
2277                                         {
2278                                                 if(!strcasecmp(parameter[3], "bias"))
2279                                                         shader.offsetbias = atof(parameter[4]);
2280                                                 else if(!strcasecmp(parameter[3], "match"))
2281                                                         shader.offsetbias = 1.0f - atof(parameter[4]);
2282                                                 else if(!strcasecmp(parameter[3], "match8"))
2283                                                         shader.offsetbias = 1.0f - atof(parameter[4]) / 255.0f;
2284                                                 else if(!strcasecmp(parameter[3], "match16"))
2285                                                         shader.offsetbias = 1.0f - atof(parameter[4]) / 65535.0f;
2286                                         }
2287                                 }
2288                                 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
2289                                 {
2290                                         int i, deformindex;
2291                                         for (deformindex = 0;deformindex < Q3MAXDEFORMS;deformindex++)
2292                                                 if (!shader.deforms[deformindex].deform)
2293                                                         break;
2294                                         if (deformindex < Q3MAXDEFORMS)
2295                                         {
2296                                                 for (i = 0;i < numparameters - 2 && i < Q3DEFORM_MAXPARMS;i++)
2297                                                         shader.deforms[deformindex].parms[i] = atof(parameter[i+2]);
2298                                                      if (!strcasecmp(parameter[1], "projectionshadow")) shader.deforms[deformindex].deform = Q3DEFORM_PROJECTIONSHADOW;
2299                                                 else if (!strcasecmp(parameter[1], "autosprite"      )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE;
2300                                                 else if (!strcasecmp(parameter[1], "autosprite2"     )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE2;
2301                                                 else if (!strcasecmp(parameter[1], "text0"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT0;
2302                                                 else if (!strcasecmp(parameter[1], "text1"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT1;
2303                                                 else if (!strcasecmp(parameter[1], "text2"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT2;
2304                                                 else if (!strcasecmp(parameter[1], "text3"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT3;
2305                                                 else if (!strcasecmp(parameter[1], "text4"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT4;
2306                                                 else if (!strcasecmp(parameter[1], "text5"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT5;
2307                                                 else if (!strcasecmp(parameter[1], "text6"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT6;
2308                                                 else if (!strcasecmp(parameter[1], "text7"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT7;
2309                                                 else if (!strcasecmp(parameter[1], "bulge"           )) shader.deforms[deformindex].deform = Q3DEFORM_BULGE;
2310                                                 else if (!strcasecmp(parameter[1], "normal"          )) shader.deforms[deformindex].deform = Q3DEFORM_NORMAL;
2311                                                 else if (!strcasecmp(parameter[1], "wave"            ))
2312                                                 {
2313                                                         shader.deforms[deformindex].deform = Q3DEFORM_WAVE;
2314                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[3]);
2315                                                         for (i = 0;i < numparameters - 4 && i < Q3WAVEPARMS;i++)
2316                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+4]);
2317                                                 }
2318                                                 else if (!strcasecmp(parameter[1], "move"            ))
2319                                                 {
2320                                                         shader.deforms[deformindex].deform = Q3DEFORM_MOVE;
2321                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[5]);
2322                                                         for (i = 0;i < numparameters - 6 && i < Q3WAVEPARMS;i++)
2323                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+6]);
2324                                                 }
2325                                         }
2326                                 }
2327                         }
2328                         // hide this shader if a cvar said it should be killed
2329                         if (shader.dpshaderkill)
2330                                 shader.numlayers = 0;
2331                         // pick the primary layer to render with
2332                         if (shader.numlayers)
2333                         {
2334                                 shader.backgroundlayer = -1;
2335                                 shader.primarylayer = 0;
2336                                 // if lightmap comes first this is definitely an ordinary texture
2337                                 // if the first two layers have the correct blendfuncs and use vertex alpha, it is a blended terrain shader
2338                                 if ((shader.layers[shader.primarylayer].texturename != NULL)
2339                                   && !strcasecmp(shader.layers[shader.primarylayer].texturename[0], "$lightmap"))
2340                                 {
2341                                         shader.backgroundlayer = -1;
2342                                         shader.primarylayer = 1;
2343                                 }
2344                                 else if (shader.numlayers >= 2
2345                                 &&   shader.layers[1].alphagen.alphagen == Q3ALPHAGEN_VERTEX
2346                                 &&  (shader.layers[0].blendfunc[0] == GL_ONE       && shader.layers[0].blendfunc[1] == GL_ZERO                && !shader.layers[0].alphatest)
2347                                 && ((shader.layers[1].blendfunc[0] == GL_SRC_ALPHA && shader.layers[1].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2348                                 ||  (shader.layers[1].blendfunc[0] == GL_ONE       && shader.layers[1].blendfunc[1] == GL_ZERO                &&  shader.layers[1].alphatest)))
2349                                 {
2350                                         // terrain blending or other effects
2351                                         shader.backgroundlayer = 0;
2352                                         shader.primarylayer = 1;
2353                                 }
2354                         }
2355                         // fix up multiple reflection types
2356                         if(shader.textureflags & Q3TEXTUREFLAG_WATERSHADER)
2357                                 shader.textureflags &= ~(Q3TEXTUREFLAG_REFRACTION | Q3TEXTUREFLAG_REFLECTION | Q3TEXTUREFLAG_CAMERA);
2358
2359                         Q3Shader_AddToHash (&shader);
2360                 }
2361                 Mem_Free(f);
2362         }
2363         FS_FreeSearch(search);
2364         // free custinfoparm values
2365         for (j = 0; j < numcustsurfaceparms; j++)
2366                 Mem_Free(custsurfaceparmnames[j]);
2367 }
2368
2369 q3shaderinfo_t *Mod_LookupQ3Shader(const char *name)
2370 {
2371         unsigned short hash;
2372         q3shader_hash_entry_t* entry;
2373         if (!q3shaders_mem)
2374                 Mod_LoadQ3Shaders();
2375         hash = CRC_Block_CaseInsensitive ((const unsigned char *)name, strlen (name));
2376         entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
2377         while (entry != NULL)
2378         {
2379                 if (strcasecmp (entry->shader.name, name) == 0)
2380                         return &entry->shader;
2381                 entry = entry->chain;
2382         }
2383         return NULL;
2384 }
2385
2386 qboolean Mod_LoadTextureFromQ3Shader(texture_t *texture, const char *name, qboolean warnmissing, qboolean fallback, int defaulttexflags)
2387 {
2388         int j;
2389         int texflagsmask, texflagsor;
2390         qboolean success = true;
2391         q3shaderinfo_t *shader;
2392         if (!name)
2393                 name = "";
2394         strlcpy(texture->name, name, sizeof(texture->name));
2395         shader = name[0] ? Mod_LookupQ3Shader(name) : NULL;
2396
2397         texflagsmask = ~0;
2398         if(!(defaulttexflags & TEXF_PICMIP))
2399                 texflagsmask &= ~TEXF_PICMIP;
2400         if(!(defaulttexflags & TEXF_COMPRESS))
2401                 texflagsmask &= ~TEXF_COMPRESS;
2402         texflagsor = 0;
2403         if(defaulttexflags & TEXF_ISWORLD)
2404                 texflagsor |= TEXF_ISWORLD;
2405         if(defaulttexflags & TEXF_ISSPRITE)
2406                 texflagsor |= TEXF_ISSPRITE;
2407         // unless later loaded from the shader
2408         texture->offsetmapping = (mod_noshader_default_offsetmapping.value) ? OFFSETMAPPING_DEFAULT : OFFSETMAPPING_OFF;
2409         texture->offsetscale = 1;
2410         texture->offsetbias = 0;
2411         texture->specularscalemod = 1;
2412         texture->specularpowermod = 1; 
2413         texture->rtlightambient = 0;
2414         // WHEN ADDING DEFAULTS HERE, REMEMBER TO SYNC TO SHADER LOADING ABOVE
2415         // HERE, AND Q1BSP LOADING
2416         // JUST GREP FOR "specularscalemod = 1".
2417
2418         if (shader)
2419         {
2420                 if (developer_loading.integer)
2421                         Con_Printf("%s: loaded shader for %s\n", loadmodel->name, name);
2422                 texture->surfaceparms = shader->surfaceparms;
2423
2424                 // allow disabling of picmip or compression by defaulttexflags
2425                 texture->textureflags = (shader->textureflags & texflagsmask) | texflagsor;
2426
2427                 if (shader->surfaceparms & Q3SURFACEPARM_SKY)
2428                 {
2429                         texture->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2430                         if (shader->skyboxname[0])
2431                         {
2432                                 // quake3 seems to append a _ to the skybox name, so this must do so as well
2433                                 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", shader->skyboxname);
2434                         }
2435                 }
2436                 else if ((texture->surfaceflags & Q3SURFACEFLAG_NODRAW) || shader->numlayers == 0)
2437                         texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2438                 else
2439                         texture->basematerialflags = MATERIALFLAG_WALL;
2440
2441                 if (shader->layers[0].alphatest)
2442                         texture->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
2443                 if (shader->textureflags & Q3TEXTUREFLAG_TWOSIDED)
2444                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
2445                 if (shader->textureflags & Q3TEXTUREFLAG_POLYGONOFFSET)
2446                 {
2447                         texture->biaspolygonoffset += shader->biaspolygonoffset;
2448                         texture->biaspolygonfactor += shader->biaspolygonfactor;
2449                 }
2450                 if (shader->textureflags & Q3TEXTUREFLAG_REFRACTION)
2451                         texture->basematerialflags |= MATERIALFLAG_REFRACTION;
2452                 if (shader->textureflags & Q3TEXTUREFLAG_REFLECTION)
2453                         texture->basematerialflags |= MATERIALFLAG_REFLECTION;
2454                 if (shader->textureflags & Q3TEXTUREFLAG_WATERSHADER)
2455                         texture->basematerialflags |= MATERIALFLAG_WATERSHADER;
2456                 if (shader->textureflags & Q3TEXTUREFLAG_CAMERA)
2457                         texture->basematerialflags |= MATERIALFLAG_CAMERA;
2458                 texture->customblendfunc[0] = GL_ONE;
2459                 texture->customblendfunc[1] = GL_ZERO;
2460                 if (shader->numlayers > 0)
2461                 {
2462                         texture->customblendfunc[0] = shader->layers[0].blendfunc[0];
2463                         texture->customblendfunc[1] = shader->layers[0].blendfunc[1];
2464 /*
2465 Q3 shader blendfuncs actually used in the game (* = supported by DP)
2466 * additive               GL_ONE GL_ONE
2467 additive weird         GL_ONE GL_SRC_ALPHA
2468 additive weird 2       GL_ONE GL_ONE_MINUS_SRC_ALPHA
2469 * alpha                  GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
2470 alpha inverse          GL_ONE_MINUS_SRC_ALPHA GL_SRC_ALPHA
2471 brighten               GL_DST_COLOR GL_ONE
2472 brighten               GL_ONE GL_SRC_COLOR
2473 brighten weird         GL_DST_COLOR GL_ONE_MINUS_DST_ALPHA
2474 brighten weird 2       GL_DST_COLOR GL_SRC_ALPHA
2475 * modulate               GL_DST_COLOR GL_ZERO
2476 * modulate               GL_ZERO GL_SRC_COLOR
2477 modulate inverse       GL_ZERO GL_ONE_MINUS_SRC_COLOR
2478 modulate inverse alpha GL_ZERO GL_SRC_ALPHA
2479 modulate weird inverse GL_ONE_MINUS_DST_COLOR GL_ZERO
2480 * modulate x2            GL_DST_COLOR GL_SRC_COLOR
2481 * no blend               GL_ONE GL_ZERO
2482 nothing                GL_ZERO GL_ONE
2483 */
2484                         // if not opaque, figure out what blendfunc to use
2485                         if (shader->layers[0].blendfunc[0] != GL_ONE || shader->layers[0].blendfunc[1] != GL_ZERO)
2486                         {
2487                                 if (shader->layers[0].blendfunc[0] == GL_ONE && shader->layers[0].blendfunc[1] == GL_ONE)
2488                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2489                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE)
2490                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2491                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2492                                         texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2493                                 else
2494                                         texture->basematerialflags |= MATERIALFLAG_CUSTOMBLEND | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2495                         }
2496                 }
2497                 if (!shader->lighting)
2498                         texture->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
2499                 if (shader->primarylayer >= 0)
2500                 {
2501                         q3shaderinfo_layer_t* primarylayer = shader->layers + shader->primarylayer;
2502                         // copy over many primarylayer parameters
2503                         texture->rgbgen = primarylayer->rgbgen;
2504                         texture->alphagen = primarylayer->alphagen;
2505                         texture->tcgen = primarylayer->tcgen;
2506                         memcpy(texture->tcmods, primarylayer->tcmods, sizeof(texture->tcmods));
2507                         // load the textures
2508                         texture->numskinframes = primarylayer->numframes;
2509                         texture->skinframerate = primarylayer->framerate;
2510                         for (j = 0;j < primarylayer->numframes;j++)
2511                         {
2512                                 if(cls.state == ca_dedicated)
2513                                 {
2514                                         texture->skinframes[j] = NULL;
2515                                 }
2516                                 else if (!(texture->skinframes[j] = R_SkinFrame_LoadExternal(primarylayer->texturename[j], (primarylayer->texflags & texflagsmask) | texflagsor, false)))
2517                                 {
2518                                         Con_Printf("^1%s:^7 could not load texture ^3\"%s\"^7 (frame %i) for shader ^2\"%s\"\n", loadmodel->name, primarylayer->texturename[j], j, texture->name);
2519                                         texture->skinframes[j] = R_SkinFrame_LoadMissing();
2520                                 }
2521                         }
2522                 }
2523                 if (shader->backgroundlayer >= 0)
2524                 {
2525                         q3shaderinfo_layer_t* backgroundlayer = shader->layers + shader->backgroundlayer;
2526                         // copy over one secondarylayer parameter
2527                         memcpy(texture->backgroundtcmods, backgroundlayer->tcmods, sizeof(texture->backgroundtcmods));
2528                         // load the textures
2529                         texture->backgroundnumskinframes = backgroundlayer->numframes;
2530                         texture->backgroundskinframerate = backgroundlayer->framerate;
2531                         for (j = 0;j < backgroundlayer->numframes;j++)
2532                         {
2533                                 if(cls.state == ca_dedicated)
2534                                 {
2535                                         texture->skinframes[j] = NULL;
2536                                 }
2537                                 else if (!(texture->backgroundskinframes[j] = R_SkinFrame_LoadExternal(backgroundlayer->texturename[j], (backgroundlayer->texflags & texflagsmask) | texflagsor, false)))
2538                                 {
2539                                         Con_Printf("^1%s:^7 could not load texture ^3\"%s\"^7 (background frame %i) for shader ^2\"%s\"\n", loadmodel->name, backgroundlayer->texturename[j], j, texture->name);
2540                                         texture->backgroundskinframes[j] = R_SkinFrame_LoadMissing();
2541                                 }
2542                         }
2543                 }
2544                 if (shader->dpshadow)
2545                         texture->basematerialflags &= ~MATERIALFLAG_NOSHADOW;
2546                 if (shader->dpnoshadow)
2547                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW;
2548                 if (shader->dpnortlight)
2549                         texture->basematerialflags |= MATERIALFLAG_NORTLIGHT;
2550                 memcpy(texture->deforms, shader->deforms, sizeof(texture->deforms));
2551                 texture->reflectmin = shader->reflectmin;
2552                 texture->reflectmax = shader->reflectmax;
2553                 texture->refractfactor = shader->refractfactor;
2554                 Vector4Copy(shader->refractcolor4f, texture->refractcolor4f);
2555                 texture->reflectfactor = shader->reflectfactor;
2556                 Vector4Copy(shader->reflectcolor4f, texture->reflectcolor4f);
2557                 texture->r_water_wateralpha = shader->r_water_wateralpha;
2558                 Vector2Copy(shader->r_water_waterscroll, texture->r_water_waterscroll);
2559                 texture->offsetmapping = shader->offsetmapping;
2560                 texture->offsetscale = shader->offsetscale;
2561                 texture->offsetbias = shader->offsetbias;
2562                 texture->specularscalemod = shader->specularscalemod;
2563                 texture->specularpowermod = shader->specularpowermod;
2564                 texture->rtlightambient = shader->rtlightambient;
2565                 if (shader->dpreflectcube[0])
2566                         texture->reflectcubetexture = R_GetCubemap(shader->dpreflectcube);
2567
2568                 // set up default supercontents (on q3bsp this is overridden by the q3bsp loader)
2569                 texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2570                 if (shader->surfaceparms & Q3SURFACEPARM_LAVA         ) texture->supercontents  = SUPERCONTENTS_LAVA         ;
2571                 if (shader->surfaceparms & Q3SURFACEPARM_SLIME        ) texture->supercontents  = SUPERCONTENTS_SLIME        ;
2572                 if (shader->surfaceparms & Q3SURFACEPARM_WATER        ) texture->supercontents  = SUPERCONTENTS_WATER        ;
2573                 if (shader->surfaceparms & Q3SURFACEPARM_NONSOLID     ) texture->supercontents  = 0                          ;
2574                 if (shader->surfaceparms & Q3SURFACEPARM_PLAYERCLIP   ) texture->supercontents  = SUPERCONTENTS_PLAYERCLIP   ;
2575                 if (shader->surfaceparms & Q3SURFACEPARM_BOTCLIP      ) texture->supercontents  = SUPERCONTENTS_MONSTERCLIP  ;
2576                 if (shader->surfaceparms & Q3SURFACEPARM_SKY          ) texture->supercontents  = SUPERCONTENTS_SKY          ;
2577
2578         //      if (shader->surfaceparms & Q3SURFACEPARM_ALPHASHADOW  ) texture->supercontents |= SUPERCONTENTS_ALPHASHADOW  ;
2579         //      if (shader->surfaceparms & Q3SURFACEPARM_AREAPORTAL   ) texture->supercontents |= SUPERCONTENTS_AREAPORTAL   ;
2580         //      if (shader->surfaceparms & Q3SURFACEPARM_CLUSTERPORTAL) texture->supercontents |= SUPERCONTENTS_CLUSTERPORTAL;
2581         //      if (shader->surfaceparms & Q3SURFACEPARM_DETAIL       ) texture->supercontents |= SUPERCONTENTS_DETAIL       ;
2582                 if (shader->surfaceparms & Q3SURFACEPARM_DONOTENTER   ) texture->supercontents |= SUPERCONTENTS_DONOTENTER   ;
2583         //      if (shader->surfaceparms & Q3SURFACEPARM_FOG          ) texture->supercontents |= SUPERCONTENTS_FOG          ;
2584                 if (shader->surfaceparms & Q3SURFACEPARM_LAVA         ) texture->supercontents |= SUPERCONTENTS_LAVA         ;
2585         //      if (shader->surfaceparms & Q3SURFACEPARM_LIGHTFILTER  ) texture->supercontents |= SUPERCONTENTS_LIGHTFILTER  ;
2586         //      if (shader->surfaceparms & Q3SURFACEPARM_METALSTEPS   ) texture->supercontents |= SUPERCONTENTS_METALSTEPS   ;
2587         //      if (shader->surfaceparms & Q3SURFACEPARM_NODAMAGE     ) texture->supercontents |= SUPERCONTENTS_NODAMAGE     ;
2588         //      if (shader->surfaceparms & Q3SURFACEPARM_NODLIGHT     ) texture->supercontents |= SUPERCONTENTS_NODLIGHT     ;
2589         //      if (shader->surfaceparms & Q3SURFACEPARM_NODRAW       ) texture->supercontents |= SUPERCONTENTS_NODRAW       ;
2590                 if (shader->surfaceparms & Q3SURFACEPARM_NODROP       ) texture->supercontents |= SUPERCONTENTS_NODROP       ;
2591         //      if (shader->surfaceparms & Q3SURFACEPARM_NOIMPACT     ) texture->supercontents |= SUPERCONTENTS_NOIMPACT     ;
2592         //      if (shader->surfaceparms & Q3SURFACEPARM_NOLIGHTMAP   ) texture->supercontents |= SUPERCONTENTS_NOLIGHTMAP   ;
2593         //      if (shader->surfaceparms & Q3SURFACEPARM_NOMARKS      ) texture->supercontents |= SUPERCONTENTS_NOMARKS      ;
2594         //      if (shader->surfaceparms & Q3SURFACEPARM_NOMIPMAPS    ) texture->supercontents |= SUPERCONTENTS_NOMIPMAPS    ;
2595                 if (shader->surfaceparms & Q3SURFACEPARM_NONSOLID     ) texture->supercontents &=~SUPERCONTENTS_SOLID        ;
2596         //      if (shader->surfaceparms & Q3SURFACEPARM_ORIGIN       ) texture->supercontents |= SUPERCONTENTS_ORIGIN       ;
2597                 if (shader->surfaceparms & Q3SURFACEPARM_PLAYERCLIP   ) texture->supercontents |= SUPERCONTENTS_PLAYERCLIP   ;
2598                 if (shader->surfaceparms & Q3SURFACEPARM_SKY          ) texture->supercontents |= SUPERCONTENTS_SKY          ;
2599         //      if (shader->surfaceparms & Q3SURFACEPARM_SLICK        ) texture->supercontents |= SUPERCONTENTS_SLICK        ;
2600                 if (shader->surfaceparms & Q3SURFACEPARM_SLIME        ) texture->supercontents |= SUPERCONTENTS_SLIME        ;
2601         //      if (shader->surfaceparms & Q3SURFACEPARM_STRUCTURAL   ) texture->supercontents |= SUPERCONTENTS_STRUCTURAL   ;
2602         //      if (shader->surfaceparms & Q3SURFACEPARM_TRANS        ) texture->supercontents |= SUPERCONTENTS_TRANS        ;
2603                 if (shader->surfaceparms & Q3SURFACEPARM_WATER        ) texture->supercontents |= SUPERCONTENTS_WATER        ;
2604         //      if (shader->surfaceparms & Q3SURFACEPARM_POINTLIGHT   ) texture->supercontents |= SUPERCONTENTS_POINTLIGHT   ;
2605         //      if (shader->surfaceparms & Q3SURFACEPARM_HINT         ) texture->supercontents |= SUPERCONTENTS_HINT         ;
2606         //      if (shader->surfaceparms & Q3SURFACEPARM_DUST         ) texture->supercontents |= SUPERCONTENTS_DUST         ;
2607                 if (shader->surfaceparms & Q3SURFACEPARM_BOTCLIP      ) texture->supercontents |= SUPERCONTENTS_BOTCLIP      | SUPERCONTENTS_MONSTERCLIP;
2608         //      if (shader->surfaceparms & Q3SURFACEPARM_LIGHTGRID    ) texture->supercontents |= SUPERCONTENTS_LIGHTGRID    ;
2609         //      if (shader->surfaceparms & Q3SURFACEPARM_ANTIPORTAL   ) texture->supercontents |= SUPERCONTENTS_ANTIPORTAL   ;
2610
2611                 if (shader->dpmeshcollisions)
2612                         texture->basematerialflags |= MATERIALFLAG_MESHCOLLISIONS;
2613                 if (shader->dpshaderkill && developer_extra.integer)
2614                         Con_DPrintf("^1%s:^7 killing shader ^3\"%s\" because of cvar\n", loadmodel->name, name);
2615         }
2616         else if (!strcmp(texture->name, "noshader") || !texture->name[0])
2617         {
2618                 if (developer_extra.integer)
2619                         Con_DPrintf("^1%s:^7 using fallback noshader material for ^3\"%s\"\n", loadmodel->name, name);
2620                 texture->surfaceparms = 0;
2621                 texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2622         }
2623         else if (!strcmp(texture->name, "common/nodraw") || !strcmp(texture->name, "textures/common/nodraw"))
2624         {
2625                 if (developer_extra.integer)
2626                         Con_DPrintf("^1%s:^7 using fallback nodraw material for ^3\"%s\"\n", loadmodel->name, name);
2627                 texture->surfaceparms = 0;
2628                 texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2629                 texture->supercontents = SUPERCONTENTS_SOLID;
2630         }
2631         else
2632         {
2633                 if (developer_extra.integer)
2634                         Con_DPrintf("^1%s:^7 No shader found for texture ^3\"%s\"\n", loadmodel->name, texture->name);
2635                 texture->surfaceparms = 0;
2636                 if (texture->surfaceflags & Q3SURFACEFLAG_NODRAW)
2637                 {
2638                         texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2639                         texture->supercontents = SUPERCONTENTS_SOLID;
2640                 }
2641                 else if (texture->surfaceflags & Q3SURFACEFLAG_SKY)
2642                 {
2643                         texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2644                         texture->supercontents = SUPERCONTENTS_SKY;
2645                 }
2646                 else
2647                 {
2648                         texture->basematerialflags |= MATERIALFLAG_WALL;
2649                         texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2650                 }
2651                 texture->numskinframes = 1;
2652                 if(cls.state == ca_dedicated)
2653                 {
2654                         texture->skinframes[0] = NULL;
2655                         success = false;
2656                 }
2657                 else
2658                 {
2659                         if (fallback)
2660                         {
2661                                 if ((texture->skinframes[0] = R_SkinFrame_LoadExternal(texture->name, defaulttexflags, false)))
2662                                 {
2663                                         if(texture->skinframes[0]->hasalpha)
2664                                                 texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2665                                 }
2666                                 else
2667                                         success = false;
2668                         }
2669                         else
2670                                 success = false;
2671                         if (!success && warnmissing)
2672                                 Con_Printf("^1%s:^7 could not load texture ^3\"%s\"\n", loadmodel->name, texture->name);
2673                 }
2674         }
2675         // init the animation variables
2676         texture->currentframe = texture;
2677         if (texture->numskinframes < 1)
2678                 texture->numskinframes = 1;
2679         if (!texture->skinframes[0])
2680                 texture->skinframes[0] = R_SkinFrame_LoadMissing();
2681         texture->currentskinframe = texture->skinframes[0];
2682         texture->backgroundcurrentskinframe = texture->backgroundskinframes[0];
2683         return success;
2684 }
2685
2686 skinfile_t *Mod_LoadSkinFiles(void)
2687 {
2688         int i, words, line, wordsoverflow;
2689         char *text;
2690         const char *data;
2691         skinfile_t *skinfile = NULL, *first = NULL;
2692         skinfileitem_t *skinfileitem;
2693         char word[10][MAX_QPATH];
2694         char vabuf[1024];
2695
2696 /*
2697 sample file:
2698 U_bodyBox,models/players/Legoman/BikerA2.tga
2699 U_RArm,models/players/Legoman/BikerA1.tga
2700 U_LArm,models/players/Legoman/BikerA1.tga
2701 U_armor,common/nodraw
2702 U_sword,common/nodraw
2703 U_shield,common/nodraw
2704 U_homb,common/nodraw
2705 U_backpack,common/nodraw
2706 U_colcha,common/nodraw
2707 tag_head,
2708 tag_weapon,
2709 tag_torso,
2710 */
2711         memset(word, 0, sizeof(word));
2712         for (i = 0;i < 256 && (data = text = (char *)FS_LoadFile(va(vabuf, sizeof(vabuf), "%s_%i.skin", loadmodel->name, i), tempmempool, true, NULL));i++)
2713         {
2714                 // If it's the first file we parse
2715                 if (skinfile == NULL)
2716                 {
2717                         skinfile = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2718                         first = skinfile;
2719                 }
2720                 else
2721                 {
2722                         skinfile->next = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2723                         skinfile = skinfile->next;
2724                 }
2725                 skinfile->next = NULL;
2726
2727                 for(line = 0;;line++)
2728                 {
2729                         // parse line
2730                         if (!COM_ParseToken_QuakeC(&data, true))
2731                                 break;
2732                         if (!strcmp(com_token, "\n"))
2733                                 continue;
2734                         words = 0;
2735                         wordsoverflow = false;
2736                         do
2737                         {
2738                                 if (words < 10)
2739                                         strlcpy(word[words++], com_token, sizeof (word[0]));
2740                                 else
2741                                         wordsoverflow = true;
2742                         }
2743                         while (COM_ParseToken_QuakeC(&data, true) && strcmp(com_token, "\n"));
2744                         if (wordsoverflow)
2745                         {
2746                                 Con_Printf("Mod_LoadSkinFiles: parsing error in file \"%s_%i.skin\" on line #%i: line with too many statements, skipping\n", loadmodel->name, i, line);
2747                                 continue;
2748                         }
2749                         // words is always >= 1
2750                         if (!strcmp(word[0], "replace"))
2751                         {
2752                                 if (words == 3)
2753                                 {
2754                                         if (developer_loading.integer)
2755                                                 Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[1], word[2]);
2756                                         skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2757                                         skinfileitem->next = skinfile->items;
2758                                         skinfile->items = skinfileitem;
2759                                         strlcpy (skinfileitem->name, word[1], sizeof (skinfileitem->name));
2760                                         strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2761                                 }
2762                                 else
2763                                         Con_Printf("Mod_LoadSkinFiles: parsing error in file \"%s_%i.skin\" on line #%i: wrong number of parameters to command \"%s\", see documentation in DP_GFX_SKINFILES extension in dpextensions.qc\n", loadmodel->name, i, line, word[0]);
2764                         }
2765                         else if (words >= 2 && !strncmp(word[0], "tag_", 4))
2766                         {
2767                                 // tag name, like "tag_weapon,"
2768                                 // not used for anything (not even in Quake3)
2769                         }
2770                         else if (words >= 2 && !strcmp(word[1], ","))
2771                         {
2772                                 // mesh shader name, like "U_RArm,models/players/Legoman/BikerA1.tga"
2773                                 if (developer_loading.integer)
2774                                         Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[0], word[2]);
2775                                 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2776                                 skinfileitem->next = skinfile->items;
2777                                 skinfile->items = skinfileitem;
2778                                 strlcpy (skinfileitem->name, word[0], sizeof (skinfileitem->name));
2779                                 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2780                         }
2781                         else
2782                                 Con_Printf("Mod_LoadSkinFiles: parsing error in file \"%s_%i.skin\" on line #%i: does not look like tag or mesh specification, or replace command, see documentation in DP_GFX_SKINFILES extension in dpextensions.qc\n", loadmodel->name, i, line);
2783                 }
2784                 Mem_Free(text);
2785         }
2786         if (i)
2787                 loadmodel->numskins = i;
2788         return first;
2789 }
2790
2791 void Mod_FreeSkinFiles(skinfile_t *skinfile)
2792 {
2793         skinfile_t *next;
2794         skinfileitem_t *skinfileitem, *nextitem;
2795         for (;skinfile;skinfile = next)
2796         {
2797                 next = skinfile->next;
2798                 for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = nextitem)
2799                 {
2800                         nextitem = skinfileitem->next;
2801                         Mem_Free(skinfileitem);
2802                 }
2803                 Mem_Free(skinfile);
2804         }
2805 }
2806
2807 int Mod_CountSkinFiles(skinfile_t *skinfile)
2808 {
2809         int i;
2810         for (i = 0;skinfile;skinfile = skinfile->next, i++);
2811         return i;
2812 }
2813
2814 void Mod_SnapVertices(int numcomponents, int numvertices, float *vertices, float snap)
2815 {
2816         int i;
2817         double isnap = 1.0 / snap;
2818         for (i = 0;i < numvertices*numcomponents;i++)
2819                 vertices[i] = floor(vertices[i]*isnap)*snap;
2820 }
2821
2822 int Mod_RemoveDegenerateTriangles(int numtriangles, const int *inelement3i, int *outelement3i, const float *vertex3f)
2823 {
2824         int i, outtriangles;
2825         float edgedir1[3], edgedir2[3], temp[3];
2826         // a degenerate triangle is one with no width (thickness, surface area)
2827         // these are characterized by having all 3 points colinear (along a line)
2828         // or having two points identical
2829         // the simplest check is to calculate the triangle's area
2830         for (i = 0, outtriangles = 0;i < numtriangles;i++, inelement3i += 3)
2831         {
2832                 // calculate first edge
2833                 VectorSubtract(vertex3f + inelement3i[1] * 3, vertex3f + inelement3i[0] * 3, edgedir1);
2834                 VectorSubtract(vertex3f + inelement3i[2] * 3, vertex3f + inelement3i[0] * 3, edgedir2);
2835                 CrossProduct(edgedir1, edgedir2, temp);
2836                 if (VectorLength2(temp) < 0.001f)
2837                         continue; // degenerate triangle (no area)
2838                 // valid triangle (has area)
2839                 VectorCopy(inelement3i, outelement3i);
2840                 outelement3i += 3;
2841                 outtriangles++;
2842         }
2843         return outtriangles;
2844 }
2845
2846 void Mod_VertexRangeFromElements(int numelements, const int *elements, int *firstvertexpointer, int *lastvertexpointer)
2847 {
2848         int i, e;
2849         int firstvertex, lastvertex;
2850         if (numelements > 0 && elements)
2851         {
2852                 firstvertex = lastvertex = elements[0];
2853                 for (i = 1;i < numelements;i++)
2854                 {
2855                         e = elements[i];
2856                         firstvertex = min(firstvertex, e);
2857                         lastvertex = max(lastvertex, e);
2858                 }
2859         }
2860         else
2861                 firstvertex = lastvertex = 0;
2862         if (firstvertexpointer)
2863                 *firstvertexpointer = firstvertex;
2864         if (lastvertexpointer)
2865                 *lastvertexpointer = lastvertex;
2866 }
2867
2868 void Mod_MakeSortedSurfaces(dp_model_t *mod)
2869 {
2870         // make an optimal set of texture-sorted batches to draw...
2871         int j, t;
2872         int *firstsurfacefortexture;
2873         int *numsurfacesfortexture;
2874         if (!mod->sortedmodelsurfaces)
2875                 mod->sortedmodelsurfaces = (int *) Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
2876         firstsurfacefortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*firstsurfacefortexture));
2877         numsurfacesfortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*numsurfacesfortexture));
2878         memset(numsurfacesfortexture, 0, mod->num_textures * sizeof(*numsurfacesfortexture));
2879         for (j = 0;j < mod->nummodelsurfaces;j++)
2880         {
2881                 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2882                 int t = (int)(surface->texture - mod->data_textures);
2883                 numsurfacesfortexture[t]++;
2884         }
2885         j = 0;
2886         for (t = 0;t < mod->num_textures;t++)
2887         {
2888                 firstsurfacefortexture[t] = j;
2889                 j += numsurfacesfortexture[t];
2890         }
2891         for (j = 0;j < mod->nummodelsurfaces;j++)
2892         {
2893                 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2894                 int t = (int)(surface->texture - mod->data_textures);
2895                 mod->sortedmodelsurfaces[firstsurfacefortexture[t]++] = j + mod->firstmodelsurface;
2896         }
2897         Mem_Free(firstsurfacefortexture);
2898         Mem_Free(numsurfacesfortexture);
2899 }
2900
2901 void Mod_BuildVBOs(void)
2902 {
2903         if (!loadmodel->surfmesh.num_vertices)
2904                 return;
2905
2906         if (gl_paranoid.integer && loadmodel->surfmesh.data_element3s && loadmodel->surfmesh.data_element3i)
2907         {
2908                 int i;
2909                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2910                 {
2911                         if (loadmodel->surfmesh.data_element3s[i] != loadmodel->surfmesh.data_element3i[i])
2912                         {
2913                                 Con_Printf("Mod_BuildVBOs: element %u is incorrect (%u should be %u)\n", i, loadmodel->surfmesh.data_element3s[i], loadmodel->surfmesh.data_element3i[i]);
2914                                 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2915                         }
2916                 }
2917         }
2918
2919         // build r_vertexmesh_t array
2920         // (compressed interleaved array for D3D)
2921         if (!loadmodel->surfmesh.vertexmesh && vid.useinterleavedarrays)
2922         {
2923                 int vertexindex;
2924                 int numvertices = loadmodel->surfmesh.num_vertices;
2925                 r_vertexmesh_t *vertexmesh;
2926                 loadmodel->surfmesh.vertexmesh = vertexmesh = (r_vertexmesh_t*)Mem_Alloc(loadmodel->mempool, numvertices * sizeof(*loadmodel->surfmesh.vertexmesh));
2927                 for (vertexindex = 0;vertexindex < numvertices;vertexindex++, vertexmesh++)
2928                 {
2929                         VectorCopy(loadmodel->surfmesh.data_vertex3f + 3*vertexindex, vertexmesh->vertex3f);
2930                         VectorScale(loadmodel->surfmesh.data_svector3f + 3*vertexindex, 1.0f, vertexmesh->svector3f);
2931                         VectorScale(loadmodel->surfmesh.data_tvector3f + 3*vertexindex, 1.0f, vertexmesh->tvector3f);
2932                         VectorScale(loadmodel->surfmesh.data_normal3f + 3*vertexindex, 1.0f, vertexmesh->normal3f);
2933                         if (loadmodel->surfmesh.data_lightmapcolor4f)
2934                                 Vector4Copy(loadmodel->surfmesh.data_lightmapcolor4f + 4*vertexindex, vertexmesh->color4f);
2935                         Vector2Copy(loadmodel->surfmesh.data_texcoordtexture2f + 2*vertexindex, vertexmesh->texcoordtexture2f);
2936                         if (loadmodel->surfmesh.data_texcoordlightmap2f)
2937                                 Vector2Scale(loadmodel->surfmesh.data_texcoordlightmap2f + 2*vertexindex, 1.0f, vertexmesh->texcoordlightmap2f);
2938                 }
2939         }
2940
2941         // upload r_vertexmesh_t array as a buffer
2942         if (loadmodel->surfmesh.vertexmesh && !loadmodel->surfmesh.vertexmeshbuffer)
2943                 loadmodel->surfmesh.vertexmeshbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.vertexmesh, loadmodel->surfmesh.num_vertices * sizeof(*loadmodel->surfmesh.vertexmesh), loadmodel->name, false, false, false);
2944
2945         // upload vertex3f array as a buffer
2946         if (loadmodel->surfmesh.data_vertex3f && !loadmodel->surfmesh.vertex3fbuffer)
2947                 loadmodel->surfmesh.vertex3fbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.num_vertices * sizeof(float[3]), loadmodel->name, false, false, false);
2948
2949         // upload short indices as a buffer
2950         if (loadmodel->surfmesh.data_element3s && !loadmodel->surfmesh.data_element3s_indexbuffer)
2951                 loadmodel->surfmesh.data_element3s_indexbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles * sizeof(short[3]), loadmodel->name, true, false, true);
2952
2953         // upload int indices as a buffer
2954         if (loadmodel->surfmesh.data_element3i && !loadmodel->surfmesh.data_element3i_indexbuffer && !loadmodel->surfmesh.data_element3s)
2955                 loadmodel->surfmesh.data_element3i_indexbuffer = R_Mesh_CreateMeshBuffer(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles * sizeof(int[3]), loadmodel->name, true, false, false);
2956
2957         // only build a vbo if one has not already been created (this is important for brush models which load specially)
2958         // vertex buffer is several arrays and we put them in the same buffer
2959         //
2960         // is this wise?  the texcoordtexture2f array is used with dynamic
2961         // vertex/svector/tvector/normal when rendering animated models, on the
2962         // other hand animated models don't use a lot of vertices anyway...
2963         if (!loadmodel->surfmesh.vbo_vertexbuffer && !vid.useinterleavedarrays)
2964         {
2965                 size_t size;
2966                 unsigned char *mem;
2967                 size = 0;
2968                 loadmodel->surfmesh.vbooffset_vertex3f           = size;if (loadmodel->surfmesh.data_vertex3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2969                 loadmodel->surfmesh.vbooffset_svector3f          = size;if (loadmodel->surfmesh.data_svector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2970                 loadmodel->surfmesh.vbooffset_tvector3f          = size;if (loadmodel->surfmesh.data_tvector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2971                 loadmodel->surfmesh.vbooffset_normal3f           = size;if (loadmodel->surfmesh.data_normal3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2972                 loadmodel->surfmesh.vbooffset_texcoordtexture2f  = size;if (loadmodel->surfmesh.data_texcoordtexture2f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2973                 loadmodel->surfmesh.vbooffset_texcoordlightmap2f = size;if (loadmodel->surfmesh.data_texcoordlightmap2f) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2974                 loadmodel->surfmesh.vbooffset_lightmapcolor4f    = size;if (loadmodel->surfmesh.data_lightmapcolor4f   ) size += loadmodel->surfmesh.num_vertices * sizeof(float[4]);
2975                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
2976                 if (loadmodel->surfmesh.data_vertex3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_vertex3f          , loadmodel->surfmesh.data_vertex3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2977                 if (loadmodel->surfmesh.data_svector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_svector3f         , loadmodel->surfmesh.data_svector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2978                 if (loadmodel->surfmesh.data_tvector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_tvector3f         , loadmodel->surfmesh.data_tvector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2979                 if (loadmodel->surfmesh.data_normal3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_normal3f          , loadmodel->surfmesh.data_normal3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2980                 if (loadmodel->surfmesh.data_texcoordtexture2f ) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordtexture2f , loadmodel->surfmesh.data_texcoordtexture2f , loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2981                 if (loadmodel->surfmesh.data_texcoordlightmap2f) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordlightmap2f, loadmodel->surfmesh.data_texcoordlightmap2f, loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2982                 if (loadmodel->surfmesh.data_lightmapcolor4f   ) memcpy(mem + loadmodel->surfmesh.vbooffset_lightmapcolor4f   , loadmodel->surfmesh.data_lightmapcolor4f   , loadmodel->surfmesh.num_vertices * sizeof(float[4]));
2983                 loadmodel->surfmesh.vbo_vertexbuffer = R_Mesh_CreateMeshBuffer(mem, size, loadmodel->name, false, false, false);
2984                 Mem_Free(mem);
2985         }
2986 }
2987
2988 static void Mod_Decompile_OBJ(dp_model_t *model, const char *filename, const char *mtlfilename, const char *originalfilename)
2989 {
2990         int submodelindex, vertexindex, surfaceindex, triangleindex, textureindex, countvertices = 0, countsurfaces = 0, countfaces = 0, counttextures = 0;
2991         int a, b, c;
2992         const char *texname;
2993         const int *e;
2994         const float *v, *vn, *vt;
2995         size_t l;
2996         size_t outbufferpos = 0;
2997         size_t outbuffermax = 0x100000;
2998         char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
2999         const msurface_t *surface;
3000         const int maxtextures = 256;
3001         char *texturenames = (char *) Z_Malloc(maxtextures * MAX_QPATH);
3002         dp_model_t *submodel;
3003
3004         // construct the mtllib file
3005         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "# mtllib for %s exported by darkplaces engine\n", originalfilename);
3006         if (l > 0)
3007                 outbufferpos += l;
3008         for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
3009         {
3010                 countsurfaces++;
3011                 countvertices += surface->num_vertices;
3012                 countfaces += surface->num_triangles;
3013                 texname = (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default";
3014                 for (textureindex = 0;textureindex < counttextures;textureindex++)
3015                         if (!strcmp(texturenames + textureindex * MAX_QPATH, texname))
3016                                 break;
3017                 if (textureindex < counttextures)
3018                         continue; // already wrote this material entry
3019                 if (textureindex >= maxtextures)
3020                         continue; // just a precaution
3021                 textureindex = counttextures++;
3022                 strlcpy(texturenames + textureindex * MAX_QPATH, texname, MAX_QPATH);
3023                 if (outbufferpos >= outbuffermax >> 1)
3024                 {
3025                         outbuffermax *= 2;
3026                         oldbuffer = outbuffer;
3027                         outbuffer = (char *) Z_Malloc(outbuffermax);
3028                         memcpy(outbuffer, oldbuffer, outbufferpos);
3029                         Z_Free(oldbuffer);
3030                 }
3031                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "newmtl %s\nNs 96.078431\nKa 0 0 0\nKd 0.64 0.64 0.64\nKs 0.5 0.5 0.5\nNi 1\nd 1\nillum 2\nmap_Kd %s%s\n\n", texname, texname, strstr(texname, ".tga") ? "" : ".tga");
3032                 if (l > 0)
3033                         outbufferpos += l;
3034         }
3035
3036         // write the mtllib file
3037         FS_WriteFile(mtlfilename, outbuffer, outbufferpos);
3038
3039         // construct the obj file
3040         outbufferpos = 0;
3041         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "# model exported from %s by darkplaces engine\n# %i vertices, %i faces, %i surfaces\nmtllib %s\n", originalfilename, countvertices, countfaces, countsurfaces, mtlfilename);
3042         if (l > 0)
3043                 outbufferpos += l;
3044
3045         for (vertexindex = 0, v = model->surfmesh.data_vertex3f, vn = model->surfmesh.data_normal3f, vt = model->surfmesh.data_texcoordtexture2f;vertexindex < model->surfmesh.num_vertices;vertexindex++, v += 3, vn += 3, vt += 2)
3046         {
3047                 if (outbufferpos >= outbuffermax >> 1)
3048                 {
3049                         outbuffermax *= 2;
3050                         oldbuffer = outbuffer;
3051                         outbuffer = (char *) Z_Malloc(outbuffermax);
3052                         memcpy(outbuffer, oldbuffer, outbufferpos);
3053                         Z_Free(oldbuffer);
3054                 }
3055                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "v %f %f %f\nvn %f %f %f\nvt %f %f\n", v[0], v[2], v[1], vn[0], vn[2], vn[1], vt[0], 1-vt[1]);
3056                 if (l > 0)
3057                         outbufferpos += l;
3058         }
3059
3060         for (submodelindex = 0;submodelindex < max(1, model->brush.numsubmodels);submodelindex++)
3061         {
3062                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "o %i\n", submodelindex);
3063                 if (l > 0)
3064                         outbufferpos += l;
3065                 submodel = model->brush.numsubmodels ? model->brush.submodels[submodelindex] : model;
3066                 for (surfaceindex = 0;surfaceindex < submodel->nummodelsurfaces;surfaceindex++)
3067                 {
3068                         surface = model->data_surfaces + submodel->sortedmodelsurfaces[surfaceindex];
3069                         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "usemtl %s\n", (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default");
3070                         if (l > 0)
3071                                 outbufferpos += l;
3072                         for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
3073                         {
3074                                 if (outbufferpos >= outbuffermax >> 1)
3075                                 {
3076                                         outbuffermax *= 2;
3077                                         oldbuffer = outbuffer;
3078                                         outbuffer = (char *) Z_Malloc(outbuffermax);
3079                                         memcpy(outbuffer, oldbuffer, outbufferpos);
3080                                         Z_Free(oldbuffer);
3081                                 }
3082                                 a = e[0]+1;
3083                                 b = e[1]+1;
3084                                 c = e[2]+1;
3085                                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "f %i/%i/%i %i/%i/%i %i/%i/%i\n", a,a,a,b,b,b,c,c,c);
3086                                 if (l > 0)
3087                                         outbufferpos += l;
3088                         }
3089                 }
3090         }
3091
3092         // write the obj file
3093         FS_WriteFile(filename, outbuffer, outbufferpos);
3094
3095         // clean up
3096         Z_Free(outbuffer);
3097         Z_Free(texturenames);
3098
3099         // print some stats
3100         Con_Printf("Wrote %s (%i bytes, %i vertices, %i faces, %i surfaces with %i distinct textures)\n", filename, (int)outbufferpos, countvertices, countfaces, countsurfaces, counttextures);
3101 }
3102
3103 static void Mod_Decompile_SMD(dp_model_t *model, const char *filename, int firstpose, int numposes, qboolean writetriangles)
3104 {
3105         int countnodes = 0, counttriangles = 0, countframes = 0;
3106         int surfaceindex;
3107         int triangleindex;
3108         int transformindex;
3109         int poseindex;
3110         int cornerindex;
3111         const int *e;
3112         size_t l;
3113         size_t outbufferpos = 0;
3114         size_t outbuffermax = 0x100000;
3115         char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
3116         const msurface_t *surface;
3117         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "version 1\nnodes\n");
3118         if (l > 0)
3119                 outbufferpos += l;
3120         for (transformindex = 0;transformindex < model->num_bones;transformindex++)
3121         {
3122                 if (outbufferpos >= outbuffermax >> 1)
3123                 {
3124                         outbuffermax *= 2;
3125                         oldbuffer = outbuffer;
3126                         outbuffer = (char *) Z_Malloc(outbuffermax);
3127                         memcpy(outbuffer, oldbuffer, outbufferpos);
3128                         Z_Free(oldbuffer);
3129                 }
3130                 countnodes++;
3131                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i \"%s\" %3i\n", transformindex, model->data_bones[transformindex].name, model->data_bones[transformindex].parent);
3132                 if (l > 0)
3133                         outbufferpos += l;
3134         }
3135         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\nskeleton\n");
3136         if (l > 0)
3137                 outbufferpos += l;
3138         for (poseindex = 0;poseindex < numposes;poseindex++)
3139         {
3140                 countframes++;
3141                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "time %i\n", poseindex);
3142                 if (l > 0)
3143                         outbufferpos += l;
3144                 for (transformindex = 0;transformindex < model->num_bones;transformindex++)
3145                 {
3146                         float angles[3];
3147                         float mtest[4][3];
3148                         matrix4x4_t posematrix;
3149                         if (outbufferpos >= outbuffermax >> 1)
3150                         {
3151                                 outbuffermax *= 2;
3152                                 oldbuffer = outbuffer;
3153                                 outbuffer = (char *) Z_Malloc(outbuffermax);
3154                                 memcpy(outbuffer, oldbuffer, outbufferpos);
3155                                 Z_Free(oldbuffer);
3156                         }
3157
3158                         // strangely the smd angles are for a transposed matrix, so we
3159                         // have to generate a transposed matrix, then convert that...
3160                         Matrix4x4_FromBonePose6s(&posematrix, model->num_posescale, model->data_poses6s + 6*(model->num_bones * poseindex + transformindex));
3161                         Matrix4x4_ToArray12FloatGL(&posematrix, mtest[0]);
3162                         AnglesFromVectors(angles, mtest[0], mtest[2], false);
3163                         if (angles[0] >= 180) angles[0] -= 360;
3164                         if (angles[1] >= 180) angles[1] -= 360;
3165                         if (angles[2] >= 180) angles[2] -= 360;
3166
3167 #if 0
3168 {
3169                         float a = DEG2RAD(angles[ROLL]);
3170                         float b = DEG2RAD(angles[PITCH]);
3171                         float c = DEG2RAD(angles[YAW]);
3172                         float cy, sy, cp, sp, cr, sr;
3173                         float test[4][3];
3174                         // smd matrix construction, for comparing
3175                         sy = sin(c);
3176                         cy = cos(c);
3177                         sp = sin(b);
3178                         cp = cos(b);
3179                         sr = sin(a);
3180                         cr = cos(a);
3181
3182                         test[0][0] = cp*cy;
3183                         test[0][1] = cp*sy;
3184                         test[0][2] = -sp;
3185                         test[1][0] = sr*sp*cy+cr*-sy;
3186                         test[1][1] = sr*sp*sy+cr*cy;
3187                         test[1][2] = sr*cp;
3188                         test[2][0] = (cr*sp*cy+-sr*-sy);
3189                         test[2][1] = (cr*sp*sy+-sr*cy);
3190                         test[2][2] = cr*cp;
3191                         test[3][0] = pose[9];
3192                         test[3][1] = pose[10];
3193                         test[3][2] = pose[11];
3194 }
3195 #endif
3196                         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f\n", transformindex, mtest[3][0], mtest[3][1], mtest[3][2], DEG2RAD(angles[ROLL]), DEG2RAD(angles[PITCH]), DEG2RAD(angles[YAW]));
3197                         if (l > 0)
3198                                 outbufferpos += l;
3199                 }
3200         }
3201         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
3202         if (l > 0)
3203                 outbufferpos += l;
3204         if (writetriangles)
3205         {
3206                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "triangles\n");
3207                 if (l > 0)
3208                         outbufferpos += l;
3209                 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
3210                 {
3211                         for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
3212                         {
3213                                 counttriangles++;
3214                                 if (outbufferpos >= outbuffermax >> 1)
3215                                 {
3216                                         outbuffermax *= 2;
3217                                         oldbuffer = outbuffer;
3218                                         outbuffer = (char *) Z_Malloc(outbuffermax);
3219                                         memcpy(outbuffer, oldbuffer, outbufferpos);
3220                                         Z_Free(oldbuffer);
3221                                 }
3222                                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%s\n", surface->texture && surface->texture->name[0] ? surface->texture->name : "default.bmp");
3223                                 if (l > 0)
3224                                         outbufferpos += l;
3225                                 for (cornerindex = 0;cornerindex < 3;cornerindex++)
3226                                 {
3227                                         const int index = e[2-cornerindex];
3228                                         const float *v = model->surfmesh.data_vertex3f + index * 3;
3229                                         const float *vn = model->surfmesh.data_normal3f + index * 3;
3230                                         const float *vt = model->surfmesh.data_texcoordtexture2f + index * 2;
3231                                         const int b = model->surfmesh.blends[index];
3232                                         if (b < model->num_bones)
3233                                                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f\n"                          , b, v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1]);
3234                                         else
3235                                         {
3236                                                 const blendweights_t *w = model->surfmesh.data_blendweights + b - model->num_bones;
3237                                                 const unsigned char *wi = w->index;
3238                                                 const unsigned char *wf = w->influence;
3239                                             if (wf[3]) l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f 4 %i %f %i %f %i %f %i %f\n", wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1], wi[0], wf[0]/255.0f, wi[1], wf[1]/255.0f, wi[2], wf[2]/255.0f, wi[3], wf[3]/255.0f);
3240                                                 else if (wf[2]) l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f 3 %i %f %i %f %i %f\n"      , wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1], wi[0], wf[0]/255.0f, wi[1], wf[1]/255.0f, wi[2], wf[2]/255.0f);
3241                                                 else if (wf[1]) l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f 2 %i %f %i %f\n"            , wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1], wi[0], wf[0]/255.0f, wi[1], wf[1]/255.0f);
3242                                                 else            l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f\n"                          , wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1]);
3243                                         }
3244                                         if (l > 0)
3245                                                 outbufferpos += l;
3246                                 }
3247                         }
3248                 }
3249                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
3250                 if (l > 0)
3251                         outbufferpos += l;
3252         }
3253
3254         FS_WriteFile(filename, outbuffer, outbufferpos);
3255         Z_Free(outbuffer);
3256
3257         Con_Printf("Wrote %s (%i bytes, %i nodes, %i frames, %i triangles)\n", filename, (int)outbufferpos, countnodes, countframes, counttriangles);
3258 }
3259
3260 /*
3261 ================
3262 Mod_Decompile_f
3263
3264 decompiles a model to editable files
3265 ================
3266 */
3267 static void Mod_Decompile_f(void)
3268 {
3269         int i, j, k, l, first, count;
3270         dp_model_t *mod;
3271         char inname[MAX_QPATH];
3272         char outname[MAX_QPATH];
3273         char mtlname[MAX_QPATH];
3274         char basename[MAX_QPATH];
3275         char animname[MAX_QPATH];
3276         char animname2[MAX_QPATH];
3277         char zymtextbuffer[16384];
3278         char dpmtextbuffer[16384];
3279         char framegroupstextbuffer[16384];
3280         int zymtextsize = 0;
3281         int dpmtextsize = 0;
3282         int framegroupstextsize = 0;
3283         char vabuf[1024];
3284
3285         if (Cmd_Argc() != 2)
3286         {
3287                 Con_Print("usage: modeldecompile <filename>\n");
3288                 return;
3289         }
3290
3291         strlcpy(inname, Cmd_Argv(1), sizeof(inname));
3292         FS_StripExtension(inname, basename, sizeof(basename));
3293
3294         mod = Mod_ForName(inname, false, true, inname[0] == '*' ? cl.model_name[1] : NULL);
3295         if (mod->brush.submodel)
3296         {
3297                 // if we're decompiling a submodel, be sure to give it a proper name based on its parent
3298                 FS_StripExtension(cl.model_name[1], outname, sizeof(outname));
3299                 dpsnprintf(basename, sizeof(basename), "%s/%s", outname, mod->name);
3300                 outname[0] = 0;
3301         }
3302         if (!mod)
3303         {
3304                 Con_Print("No such model\n");
3305                 return;
3306         }
3307         if (!mod->surfmesh.num_triangles)
3308         {
3309                 Con_Print("Empty model (or sprite)\n");
3310                 return;
3311         }
3312
3313         // export OBJ if possible (not on sprites)
3314         if (mod->surfmesh.num_triangles)
3315         {
3316                 dpsnprintf(outname, sizeof(outname), "%s_decompiled.obj", basename);
3317                 dpsnprintf(mtlname, sizeof(mtlname), "%s_decompiled.mtl", basename);
3318                 Mod_Decompile_OBJ(mod, outname, mtlname, inname);
3319         }
3320
3321         // export SMD if possible (only for skeletal models)
3322         if (mod->surfmesh.num_triangles && mod->num_bones)
3323         {
3324                 dpsnprintf(outname, sizeof(outname), "%s_decompiled/ref1.smd", basename);
3325                 Mod_Decompile_SMD(mod, outname, 0, 1, true);
3326                 l = dpsnprintf(zymtextbuffer + zymtextsize, sizeof(zymtextbuffer) - zymtextsize, "output out.zym\nscale 1\norigin 0 0 0\nmesh ref1.smd\n");
3327                 if (l > 0) zymtextsize += l;
3328                 l = dpsnprintf(dpmtextbuffer + dpmtextsize, sizeof(dpmtextbuffer) - dpmtextsize, "outputdir .\nmodel out\nscale 1\norigin 0 0 0\nscene ref1.smd\n");
3329                 if (l > 0) dpmtextsize += l;
3330                 for (i = 0;i < mod->numframes;i = j)
3331                 {
3332                         strlcpy(animname, mod->animscenes[i].name, sizeof(animname));
3333                         first = mod->animscenes[i].firstframe;
3334                         if (mod->animscenes[i].framecount > 1)
3335                         {
3336                                 // framegroup anim
3337                                 count = mod->animscenes[i].framecount;
3338                                 j = i + 1;
3339                         }
3340                         else
3341                         {
3342                                 // individual frame
3343                                 // check for additional frames with same name
3344                                 for (l = 0, k = strlen(animname);animname[l];l++)
3345                                         if(animname[l] < '0' || animname[l] > '9')
3346                                                 k = l + 1;
3347                                 if(k > 0 && animname[k-1] == '_')
3348                                         --k;
3349                                 animname[k] = 0;
3350                                 count = mod->num_poses - first;
3351                                 for (j = i + 1;j < mod->numframes;j++)
3352                                 {
3353                                         strlcpy(animname2, mod->animscenes[j].name, sizeof(animname2));
3354                                         for (l = 0, k = strlen(animname2);animname2[l];l++)
3355                                                 if(animname2[l] < '0' || animname2[l] > '9')
3356                                                         k = l + 1;
3357                                         if(k > 0 && animname[k-1] == '_')
3358                                                 --k;
3359                                         animname2[k] = 0;
3360                                         if (strcmp(animname2, animname) || mod->animscenes[j].framecount > 1)
3361                                         {
3362                                                 count = mod->animscenes[j].firstframe - first;
3363                                                 break;
3364                                         }
3365                                 }
3366                                 // if it's only one frame, use the original frame name
3367                                 if (j == i + 1)
3368                                         strlcpy(animname, mod->animscenes[i].name, sizeof(animname));
3369                                 
3370                         }
3371                         dpsnprintf(outname, sizeof(outname), "%s_decompiled/%s.smd", basename, animname);
3372                         Mod_Decompile_SMD(mod, outname, first, count, false);
3373                         if (zymtextsize < (int)sizeof(zymtextbuffer) - 100)
3374                         {
3375                                 l = dpsnprintf(zymtextbuffer + zymtextsize, sizeof(zymtextbuffer) - zymtextsize, "scene %s.smd fps %g %s\n", animname, mod->animscenes[i].framerate, mod->animscenes[i].loop ? "" : " noloop");
3376                                 if (l > 0) zymtextsize += l;
3377                         }
3378                         if (dpmtextsize < (int)sizeof(dpmtextbuffer) - 100)
3379                         {
3380                                 l = dpsnprintf(dpmtextbuffer + dpmtextsize, sizeof(dpmtextbuffer) - dpmtextsize, "scene %s.smd fps %g %s\n", animname, mod->animscenes[i].framerate, mod->animscenes[i].loop ? "" : " noloop");
3381                                 if (l > 0) dpmtextsize += l;
3382                         }
3383                         if (framegroupstextsize < (int)sizeof(framegroupstextbuffer) - 100)
3384                         {
3385                                 l = dpsnprintf(framegroupstextbuffer + framegroupstextsize, sizeof(framegroupstextbuffer) - framegroupstextsize, "%d %d %f %d // %s\n", first, count, mod->animscenes[i].framerate, mod->animscenes[i].loop, animname);
3386                                 if (l > 0) framegroupstextsize += l;
3387                         }
3388                 }
3389                 if (zymtextsize)
3390                         FS_WriteFile(va(vabuf, sizeof(vabuf), "%s_decompiled/out_zym.txt", basename), zymtextbuffer, (fs_offset_t)zymtextsize);
3391                 if (dpmtextsize)
3392                         FS_WriteFile(va(vabuf, sizeof(vabuf), "%s_decompiled/out_dpm.txt", basename), dpmtextbuffer, (fs_offset_t)dpmtextsize);
3393                 if (framegroupstextsize)
3394                         FS_WriteFile(va(vabuf, sizeof(vabuf), "%s_decompiled.framegroups", basename), framegroupstextbuffer, (fs_offset_t)framegroupstextsize);
3395         }
3396 }
3397
3398 void Mod_AllocLightmap_Init(mod_alloclightmap_state_t *state, int width, int height)
3399 {
3400         int y;
3401         memset(state, 0, sizeof(*state));
3402         state->width = width;
3403         state->height = height;
3404         state->currentY = 0;
3405         state->rows = (mod_alloclightmap_row_t *)Mem_Alloc(loadmodel->mempool, state->height * sizeof(*state->rows));
3406         for (y = 0;y < state->height;y++)
3407         {
3408                 state->rows[y].currentX = 0;
3409                 state->rows[y].rowY = -1;
3410         }
3411 }
3412
3413 void Mod_AllocLightmap_Reset(mod_alloclightmap_state_t *state)
3414 {
3415         int y;
3416         state->currentY = 0;
3417         for (y = 0;y < state->height;y++)
3418         {
3419                 state->rows[y].currentX = 0;
3420                 state->rows[y].rowY = -1;
3421         }
3422 }
3423
3424 void Mod_AllocLightmap_Free(mod_alloclightmap_state_t *state)
3425 {
3426         if (state->rows)
3427                 Mem_Free(state->rows);
3428         memset(state, 0, sizeof(*state));
3429 }
3430
3431 qboolean Mod_AllocLightmap_Block(mod_alloclightmap_state_t *state, int blockwidth, int blockheight, int *outx, int *outy)
3432 {
3433         mod_alloclightmap_row_t *row;
3434         int y;
3435
3436         row = state->rows + blockheight;
3437         if ((row->rowY < 0) || (row->currentX + blockwidth > state->width))
3438         {
3439                 if (state->currentY + blockheight <= state->height)
3440                 {
3441                         // use the current allocation position
3442                         row->rowY = state->currentY;
3443                         row->currentX = 0;
3444                         state->currentY += blockheight;
3445                 }
3446                 else
3447                 {
3448                         // find another position
3449                         for (y = blockheight;y < state->height;y++)
3450                         {
3451                                 if ((state->rows[y].rowY >= 0) && (state->rows[y].currentX + blockwidth <= state->width))
3452                                 {
3453                                         row = state->rows + y;
3454                                         break;
3455                                 }
3456                         }
3457                         if (y == state->height)
3458                                 return false;
3459                 }
3460         }
3461         *outy = row->rowY;
3462         *outx = row->currentX;
3463         row->currentX += blockwidth;
3464
3465         return true;
3466 }
3467
3468 typedef struct lightmapsample_s
3469 {
3470         float pos[3];
3471         float sh1[4][3];
3472         float *vertex_color;
3473         unsigned char *lm_bgr;
3474         unsigned char *lm_dir;
3475 }
3476 lightmapsample_t;
3477
3478 typedef struct lightmapvertex_s
3479 {
3480         int index;
3481         float pos[3];
3482         float normal[3];
3483         float texcoordbase[2];
3484         float texcoordlightmap[2];
3485         float lightcolor[4];
3486 }
3487 lightmapvertex_t;
3488
3489 typedef struct lightmaptriangle_s
3490 {
3491         int triangleindex;
3492         int surfaceindex;
3493         int lightmapindex;
3494         int axis;
3495         int lmoffset[2];
3496         int lmsize[2];
3497         // 2D modelspace coordinates of min corner
3498         // snapped to lightmap grid but not in grid coordinates
3499         float lmbase[2];
3500         // 2D modelspace to lightmap coordinate scale
3501         float lmscale[2];
3502         float vertex[3][3];
3503         float mins[3];
3504         float maxs[3];
3505 }
3506 lightmaptriangle_t;
3507
3508 typedef struct lightmaplight_s
3509 {
3510         float origin[3];
3511         float radius;
3512         float iradius;
3513         float radius2;
3514         float color[3];
3515         svbsp_t svbsp;
3516 }
3517 lightmaplight_t;
3518
3519 lightmaptriangle_t *mod_generatelightmaps_lightmaptriangles;
3520
3521 #define MAX_LIGHTMAPSAMPLES 64
3522 static int mod_generatelightmaps_numoffsets[3];
3523 static float mod_generatelightmaps_offsets[3][MAX_LIGHTMAPSAMPLES][3];
3524
3525 static int mod_generatelightmaps_numlights;
3526 static lightmaplight_t *mod_generatelightmaps_lightinfo;
3527
3528 extern cvar_t r_shadow_lightattenuationdividebias;
3529 extern cvar_t r_shadow_lightattenuationlinearscale;
3530
3531 static void Mod_GenerateLightmaps_LightPoint(dp_model_t *model, const vec3_t pos, vec3_t ambient, vec3_t diffuse, vec3_t lightdir)
3532 {
3533         int i;
3534         int index;
3535         int result;
3536         float relativepoint[3];
3537         float color[3];
3538         float dir[3];
3539         float dist;
3540         float dist2;
3541         float intensity;
3542         float sample[5*3];
3543         float lightorigin[3];
3544         float lightradius;
3545         float lightradius2;
3546         float lightiradius;
3547         float lightcolor[3];
3548         trace_t trace;
3549         for (i = 0;i < 5*3;i++)
3550                 sample[i] = 0.0f;
3551         for (index = 0;;index++)
3552         {
3553                 result = R_Shadow_GetRTLightInfo(index, lightorigin, &lightradius, lightcolor);
3554                 if (result < 0)
3555                         break;
3556                 if (result == 0)
3557                         continue;
3558                 lightradius2 = lightradius * lightradius;
3559                 VectorSubtract(lightorigin, pos, relativepoint);
3560                 dist2 = VectorLength2(relativepoint);
3561                 if (dist2 >= lightradius2)
3562                         continue;
3563                 lightiradius = 1.0f / lightradius;
3564                 dist = sqrt(dist2) * lightiradius;
3565                 intensity = (1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist);
3566                 if (intensity <= 0.0f)
3567                         continue;
3568                 if (model && model->TraceLine)
3569                 {
3570                         model->TraceLine(model, NULL, NULL, &trace, pos, lightorigin, SUPERCONTENTS_VISBLOCKERMASK);
3571                         if (trace.fraction < 1)
3572                                 continue;
3573                 }
3574                 // scale down intensity to add to both ambient and diffuse
3575                 //intensity *= 0.5f;
3576                 VectorNormalize(relativepoint);
3577                 VectorScale(lightcolor, intensity, color);
3578                 VectorMA(sample    , 0.5f            , color, sample    );
3579                 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
3580                 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
3581                 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
3582                 // calculate a weighted average light direction as well
3583                 intensity *= VectorLength(color);
3584                 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
3585         }
3586         // calculate the direction we'll use to reduce the sample to a directional light source
3587         VectorCopy(sample + 12, dir);
3588         //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
3589         VectorNormalize(dir);
3590         // extract the diffuse color along the chosen direction and scale it
3591         diffuse[0] = (dir[0]*sample[3] + dir[1]*sample[6] + dir[2]*sample[ 9] + sample[ 0]);
3592         diffuse[1] = (dir[0]*sample[4] + dir[1]*sample[7] + dir[2]*sample[10] + sample[ 1]);
3593         diffuse[2] = (dir[0]*sample[5] + dir[1]*sample[8] + dir[2]*sample[11] + sample[ 2]);
3594         // subtract some of diffuse from ambient
3595         VectorMA(sample, -0.333f, diffuse, ambient);
3596         // store the normalized lightdir
3597         VectorCopy(dir, lightdir);
3598 }
3599
3600 static void Mod_GenerateLightmaps_CreateLights_ComputeSVBSP_InsertSurfaces(const dp_model_t *model, svbsp_t *svbsp, const float *mins, const float *maxs)
3601 {
3602         int surfaceindex;
3603         int triangleindex;
3604         const msurface_t *surface;
3605         const float *vertex3f = model->surfmesh.data_vertex3f;
3606         const int *element3i = model->surfmesh.data_element3i;
3607         const int *e;
3608         float v2[3][3];
3609         for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->nummodelsurfaces;surfaceindex++, surface++)
3610         {
3611                 if (!BoxesOverlap(surface->mins, surface->maxs, mins, maxs))
3612                         continue;
3613                 if (surface->texture->basematerialflags & MATERIALFLAG_NOSHADOW)
3614                         continue;
3615                 for (triangleindex = 0, e = element3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
3616                 {
3617                         VectorCopy(vertex3f + 3*e[0], v2[0]);
3618                         VectorCopy(vertex3f + 3*e[1], v2[1]);
3619                         VectorCopy(vertex3f + 3*e[2], v2[2]);
3620                         SVBSP_AddPolygon(svbsp, 3, v2[0], true, NULL, NULL, 0);
3621                 }
3622         }
3623 }
3624
3625 static void Mod_GenerateLightmaps_CreateLights_ComputeSVBSP(dp_model_t *model, lightmaplight_t *lightinfo)
3626 {
3627         int maxnodes = 1<<14;
3628         svbsp_node_t *nodes;
3629         float origin[3];
3630         float mins[3];
3631         float maxs[3];
3632         svbsp_t svbsp;
3633         VectorSet(mins, lightinfo->origin[0] - lightinfo->radius, lightinfo->origin[1] - lightinfo->radius, lightinfo->origin[2] - lightinfo->radius);
3634         VectorSet(maxs, lightinfo->origin[0] + lightinfo->radius, lightinfo->origin[1] + lightinfo->radius, lightinfo->origin[2] + lightinfo->radius);
3635         VectorCopy(lightinfo->origin, origin);
3636         nodes = (svbsp_node_t *)Mem_Alloc(tempmempool, maxnodes * sizeof(*nodes));
3637         for (;;)
3638         {
3639                 SVBSP_Init(&svbsp, origin, maxnodes, nodes);
3640                 Mod_GenerateLightmaps_CreateLights_ComputeSVBSP_InsertSurfaces(model, &svbsp, mins, maxs);
3641                 if (svbsp.ranoutofnodes)
3642                 {
3643                         maxnodes *= 16;
3644                         if (maxnodes > 1<<22)
3645                         {
3646                                 Mem_Free(nodes);
3647                                 return;
3648                         }
3649                         Mem_Free(nodes);
3650                         nodes = (svbsp_node_t *)Mem_Alloc(tempmempool, maxnodes * sizeof(*nodes));
3651                 }
3652                 else
3653                         break;
3654         }
3655         if (svbsp.numnodes > 0)
3656         {
3657                 svbsp.nodes = (svbsp_node_t *)Mem_Alloc(tempmempool, svbsp.numnodes * sizeof(*nodes));
3658                 memcpy(svbsp.nodes, nodes, svbsp.numnodes * sizeof(*nodes));
3659                 lightinfo->svbsp = svbsp;
3660         }
3661         Mem_Free(nodes);
3662 }
3663
3664 static void Mod_GenerateLightmaps_CreateLights(dp_model_t *model)
3665 {
3666         int index;
3667         int result;
3668         lightmaplight_t *lightinfo;
3669         float origin[3];
3670         float radius;
3671         float color[3];
3672         mod_generatelightmaps_numlights = 0;
3673         for (index = 0;;index++)
3674         {
3675                 result = R_Shadow_GetRTLightInfo(index, origin, &radius, color);
3676                 if (result < 0)
3677                         break;
3678                 if (result > 0)
3679                         mod_generatelightmaps_numlights++;
3680         }
3681         if (mod_generatelightmaps_numlights > 0)
3682         {
3683                 mod_generatelightmaps_lightinfo = (lightmaplight_t *)Mem_Alloc(tempmempool, mod_generatelightmaps_numlights * sizeof(*mod_generatelightmaps_lightinfo));
3684                 lightinfo = mod_generatelightmaps_lightinfo;
3685                 for (index = 0;;index++)
3686                 {
3687                         result = R_Shadow_GetRTLightInfo(index, lightinfo->origin, &lightinfo->radius, lightinfo->color);
3688                         if (result < 0)
3689                                 break;
3690                         if (result > 0)
3691                                 lightinfo++;
3692                 }
3693         }
3694         for (index = 0, lightinfo = mod_generatelightmaps_lightinfo;index < mod_generatelightmaps_numlights;index++, lightinfo++)
3695         {
3696                 lightinfo->iradius = 1.0f / lightinfo->radius;
3697                 lightinfo->radius2 = lightinfo->radius * lightinfo->radius;
3698                 // TODO: compute svbsp
3699                 Mod_GenerateLightmaps_CreateLights_ComputeSVBSP(model, lightinfo);
3700         }
3701 }
3702
3703 static void Mod_GenerateLightmaps_DestroyLights(dp_model_t *model)
3704 {
3705         int i;
3706         if (mod_generatelightmaps_lightinfo)
3707         {
3708                 for (i = 0;i < mod_generatelightmaps_numlights;i++)
3709                         if (mod_generatelightmaps_lightinfo[i].svbsp.nodes)
3710                                 Mem_Free(mod_generatelightmaps_lightinfo[i].svbsp.nodes);
3711                 Mem_Free(mod_generatelightmaps_lightinfo);
3712         }
3713         mod_generatelightmaps_lightinfo = NULL;
3714         mod_generatelightmaps_numlights = 0;
3715 }
3716
3717 static qboolean Mod_GenerateLightmaps_SamplePoint_SVBSP(const svbsp_t *svbsp, const float *pos)
3718 {
3719         const svbsp_node_t *node;
3720         const svbsp_node_t *nodes = svbsp->nodes;
3721         int num = 0;
3722         while (num >= 0)
3723         {
3724                 node = nodes + num;
3725                 num = node->children[DotProduct(node->plane, pos) < node->plane[3]];
3726         }
3727         return num == -1; // true if empty, false if solid (shadowed)
3728 }
3729
3730 static void Mod_GenerateLightmaps_SamplePoint(const float *pos, const float *normal, float *sample, int numoffsets, const float *offsets)
3731 {
3732         int i;
3733         float relativepoint[3];
3734         float color[3];
3735         float offsetpos[3];
3736         float dist;
3737         float dist2;
3738         float intensity;
3739         int offsetindex;
3740         int hits;
3741         int tests;
3742         const lightmaplight_t *lightinfo;
3743         trace_t trace;
3744         for (i = 0;i < 5*3;i++)
3745                 sample[i] = 0.0f;
3746         for (i = 0, lightinfo = mod_generatelightmaps_lightinfo;i < mod_generatelightmaps_numlights;i++, lightinfo++)
3747         {
3748                 //R_SampleRTLights(pos, sample, numoffsets, offsets);
3749                 VectorSubtract(lightinfo->origin, pos, relativepoint);
3750                 // don't accept light from behind a surface, it causes bad shading
3751                 if (normal && DotProduct(relativepoint, normal) <= 0)
3752                         continue;
3753                 dist2 = VectorLength2(relativepoint);
3754                 if (dist2 >= lightinfo->radius2)
3755                         continue;
3756                 dist = sqrt(dist2) * lightinfo->iradius;
3757                 intensity = dist < 1 ? ((1.0f - dist) * r_shadow_lightattenuationlinearscale.value / (r_shadow_lightattenuationdividebias.value + dist*dist)) : 0;
3758                 if (intensity <= 0)
3759                         continue;
3760                 if (cl.worldmodel && cl.worldmodel->TraceLine && numoffsets > 0)
3761                 {
3762                         hits = 0;
3763                         tests = 1;
3764                         if (Mod_GenerateLightmaps_SamplePoint_SVBSP(&lightinfo->svbsp, pos))
3765                                 hits++;
3766                         for (offsetindex = 1;offsetindex < numoffsets;offsetindex++)
3767                         {
3768                                 VectorAdd(pos, offsets + 3*offsetindex, offsetpos);
3769                                 if (!normal)
3770                                 {
3771                                         // for light grid we'd better check visibility of the offset point
3772                                         cl.worldmodel->TraceLine(cl.worldmodel, NULL, NULL, &trace, pos, offsetpos, SUPERCONTENTS_VISBLOCKERMASK);
3773                                         if (trace.fraction < 1)
3774                                                 VectorLerp(pos, trace.fraction, offsetpos, offsetpos);
3775                                 }
3776                                 tests++;
3777                                 if (Mod_GenerateLightmaps_SamplePoint_SVBSP(&lightinfo->svbsp, offsetpos))
3778                                         hits++;
3779                         }
3780                         if (!hits)
3781                                 continue;
3782                         // scale intensity according to how many rays succeeded
3783                         // we know one test is valid, half of the rest will fail...
3784                         //if (normal && tests > 1)
3785                         //      intensity *= (tests - 1.0f) / tests;
3786                         intensity *= (float)hits / tests;
3787                 }
3788                 // scale down intensity to add to both ambient and diffuse
3789                 //intensity *= 0.5f;
3790                 VectorNormalize(relativepoint);
3791                 VectorScale(lightinfo->color, intensity, color);
3792                 VectorMA(sample    , 0.5f            , color, sample    );
3793                 VectorMA(sample + 3, relativepoint[0], color, sample + 3);
3794                 VectorMA(sample + 6, relativepoint[1], color, sample + 6);
3795                 VectorMA(sample + 9, relativepoint[2], color, sample + 9);
3796                 // calculate a weighted average light direction as well
3797                 intensity *= VectorLength(color);
3798                 VectorMA(sample + 12, intensity, relativepoint, sample + 12);
3799         }
3800 }
3801
3802 static void Mod_GenerateLightmaps_LightmapSample(const float *pos, const float *normal, unsigned char *lm_bgr, unsigned char *lm_dir)
3803 {
3804         float sample[5*3];
3805         float color[3];
3806         float dir[3];
3807         float f;
3808         Mod_GenerateLightmaps_SamplePoint(pos, normal, sample, mod_generatelightmaps_numoffsets[0], mod_generatelightmaps_offsets[0][0]);
3809         //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
3810         VectorCopy(sample + 12, dir);
3811         VectorNormalize(dir);
3812         //VectorAdd(dir, normal, dir);
3813         //VectorNormalize(dir);
3814         f = DotProduct(dir, normal);
3815         f = max(0, f) * 255.0f;
3816         VectorScale(sample, f, color);
3817         //VectorCopy(normal, dir);
3818         VectorSet(dir, (dir[0]+1.0f)*127.5f, (dir[1]+1.0f)*127.5f, (dir[2]+1.0f)*127.5f);
3819         lm_bgr[0] = (unsigned char)bound(0.0f, color[2], 255.0f);
3820         lm_bgr[1] = (unsigned char)bound(0.0f, color[1], 255.0f);
3821         lm_bgr[2] = (unsigned char)bound(0.0f, color[0], 255.0f);
3822         lm_bgr[3] = 255;
3823         lm_dir[0] = (unsigned char)dir[2];
3824         lm_dir[1] = (unsigned char)dir[1];
3825         lm_dir[2] = (unsigned char)dir[0];
3826         lm_dir[3] = 255;
3827 }
3828
3829 static void Mod_GenerateLightmaps_VertexSample(const float *pos, const float *normal, float *vertex_color)
3830 {
3831         float sample[5*3];
3832         Mod_GenerateLightmaps_SamplePoint(pos, normal, sample, mod_generatelightmaps_numoffsets[1], mod_generatelightmaps_offsets[1][0]);
3833         VectorCopy(sample, vertex_color);
3834 }
3835
3836 static void Mod_GenerateLightmaps_GridSample(const float *pos, q3dlightgrid_t *s)
3837 {
3838         float sample[5*3];
3839         float ambient[3];
3840         float diffuse[3];
3841         float dir[3];
3842         Mod_GenerateLightmaps_SamplePoint(pos, NULL, sample, mod_generatelightmaps_numoffsets[2], mod_generatelightmaps_offsets[2][0]);
3843         // calculate the direction we'll use to reduce the sample to a directional light source
3844         VectorCopy(sample + 12, dir);
3845         //VectorSet(dir, sample[3] + sample[4] + sample[5], sample[6] + sample[7] + sample[8], sample[9] + sample[10] + sample[11]);
3846         VectorNormalize(dir);
3847         // extract the diffuse color along the chosen direction and scale it
3848         diffuse[0] = (dir[0]*sample[3] + dir[1]*sample[6] + dir[2]*sample[ 9] + sample[ 0]) * 127.5f;
3849         diffuse[1] = (dir[0]*sample[4] + dir[1]*sample[7] + dir[2]*sample[10] + sample[ 1]) * 127.5f;
3850         diffuse[2] = (dir[0]*sample[5] + dir[1]*sample[8] + dir[2]*sample[11] + sample[ 2]) * 127.5f;
3851         // scale the ambient from 0-2 to 0-255 and subtract some of diffuse
3852         VectorScale(sample, 127.5f, ambient);
3853         VectorMA(ambient, -0.333f, diffuse, ambient);
3854         // encode to the grid format
3855         s->ambientrgb[0] = (unsigned char)bound(0.0f, ambient[0], 255.0f);
3856         s->ambientrgb[1] = (unsigned char)bound(0.0f, ambient[1], 255.0f);
3857         s->ambientrgb[2] = (unsigned char)bound(0.0f, ambient[2], 255.0f);
3858         s->diffusergb[0] = (unsigned char)bound(0.0f, diffuse[0], 255.0f);
3859         s->diffusergb[1] = (unsigned char)bound(0.0f, diffuse[1], 255.0f);
3860         s->diffusergb[2] = (unsigned char)bound(0.0f, diffuse[2], 255.0f);
3861         if (dir[2] >= 0.99f) {s->diffusepitch = 0;s->diffuseyaw = 0;}
3862         else if (dir[2] <= -0.99f) {s->diffusepitch = 128;s->diffuseyaw = 0;}
3863         else {s->diffusepitch = (unsigned char)(acos(dir[2]) * (127.5f/M_PI));s->diffuseyaw = (unsigned char)(atan2(dir[1], dir[0]) * (127.5f/M_PI));}
3864 }
3865
3866 static void Mod_GenerateLightmaps_InitSampleOffsets(dp_model_t *model)
3867 {
3868         float radius[3];
3869         float temp[3];
3870         int i, j;
3871         memset(mod_generatelightmaps_offsets, 0, sizeof(mod_generatelightmaps_offsets));
3872         mod_generatelightmaps_numoffsets[0] = min(MAX_LIGHTMAPSAMPLES, mod_generatelightmaps_lightmapsamples.integer);
3873         mod_generatelightmaps_numoffsets[1] = min(MAX_LIGHTMAPSAMPLES, mod_generatelightmaps_vertexsamples.integer);
3874         mod_generatelightmaps_numoffsets[2] = min(MAX_LIGHTMAPSAMPLES, mod_generatelightmaps_gridsamples.integer);
3875         radius[0] = mod_generatelightmaps_lightmapradius.value;
3876         radius[1] = mod_generatelightmaps_vertexradius.value;
3877         radius[2] = mod_generatelightmaps_gridradius.value;
3878         for (i = 0;i < 3;i++)
3879         {
3880                 for (j = 1;j < mod_generatelightmaps_numoffsets[i];j++)
3881                 {
3882                         VectorRandom(temp);
3883                         VectorScale(temp, radius[i], mod_generatelightmaps_offsets[i][j]);
3884                 }
3885         }
3886 }
3887
3888 static void Mod_GenerateLightmaps_DestroyLightmaps(dp_model_t *model)
3889 {
3890         msurface_t *surface;
3891         int surfaceindex;
3892         int i;
3893         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3894         {
3895                 surface = model->data_surfaces + surfaceindex;
3896                 surface->lightmaptexture = NULL;
3897                 surface->deluxemaptexture = NULL;
3898         }
3899         if (model->brushq3.data_lightmaps)
3900         {
3901                 for (i = 0;i < model->brushq3.num_mergedlightmaps;i++)
3902                         if (model->brushq3.data_lightmaps[i])
3903                                 R_FreeTexture(model->brushq3.data_lightmaps[i]);
3904                 Mem_Free(model->brushq3.data_lightmaps);
3905                 model->brushq3.data_lightmaps = NULL;
3906         }
3907         if (model->brushq3.data_deluxemaps)
3908         {
3909                 for (i = 0;i < model->brushq3.num_mergedlightmaps;i++)
3910                         if (model->brushq3.data_deluxemaps[i])
3911                                 R_FreeTexture(model->brushq3.data_deluxemaps[i]);
3912                 Mem_Free(model->brushq3.data_deluxemaps);
3913                 model->brushq3.data_deluxemaps = NULL;
3914         }
3915 }
3916
3917 static void Mod_GenerateLightmaps_UnweldTriangles(dp_model_t *model)
3918 {
3919         msurface_t *surface;
3920         int surfaceindex;
3921         int vertexindex;
3922         int outvertexindex;
3923         int i;
3924         const int *e;
3925         surfmesh_t oldsurfmesh;
3926         size_t size;
3927         unsigned char *data;
3928         oldsurfmesh = model->surfmesh;
3929         model->surfmesh.num_triangles = oldsurfmesh.num_triangles;
3930         model->surfmesh.num_vertices = oldsurfmesh.num_triangles * 3;
3931         size = 0;
3932         size += model->surfmesh.num_vertices * sizeof(float[3]);
3933         size += model->surfmesh.num_vertices * sizeof(float[3]);
3934         size += model->surfmesh.num_vertices * sizeof(float[3]);
3935         size += model->surfmesh.num_vertices * sizeof(float[3]);
3936         size += model->surfmesh.num_vertices * sizeof(float[2]);
3937         size += model->surfmesh.num_vertices * sizeof(float[2]);
3938         size += model->surfmesh.num_vertices * sizeof(float[4]);
3939         data = (unsigned char *)Mem_Alloc(model->mempool, size);
3940         model->surfmesh.data_vertex3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3941         model->surfmesh.data_normal3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3942         model->surfmesh.data_svector3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3943         model->surfmesh.data_tvector3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3944         model->surfmesh.data_texcoordtexture2f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[2]);
3945         model->surfmesh.data_texcoordlightmap2f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[2]);
3946         model->surfmesh.data_lightmapcolor4f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[4]);
3947         if (model->surfmesh.num_vertices > 65536)
3948                 model->surfmesh.data_element3s = NULL;
3949
3950         if (model->surfmesh.vertexmesh)
3951                 Mem_Free(model->surfmesh.vertexmesh);
3952         model->surfmesh.vertexmesh = NULL;
3953         if (model->surfmesh.vertex3fbuffer)
3954                 R_Mesh_DestroyMeshBuffer(model->surfmesh.vertex3fbuffer);
3955         model->surfmesh.vertex3fbuffer = NULL;
3956         if (model->surfmesh.vertexmeshbuffer)
3957                 R_Mesh_DestroyMeshBuffer(model->surfmesh.vertexmeshbuffer);
3958         model->surfmesh.vertexmeshbuffer = NULL;
3959         if (model->surfmesh.data_element3i_indexbuffer)
3960                 R_Mesh_DestroyMeshBuffer(model->surfmesh.data_element3i_indexbuffer);
3961         model->surfmesh.data_element3i_indexbuffer = NULL;
3962         if (model->surfmesh.data_element3s_indexbuffer)
3963                 R_Mesh_DestroyMeshBuffer(model->surfmesh.data_element3s_indexbuffer);
3964         model->surfmesh.data_element3s_indexbuffer = NULL;
3965         if (model->surfmesh.vbo_vertexbuffer)
3966                 R_Mesh_DestroyMeshBuffer(model->surfmesh.vbo_vertexbuffer);
3967         model->surfmesh.vbo_vertexbuffer = 0;
3968
3969         // convert all triangles to unique vertex data
3970         outvertexindex = 0;
3971         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3972         {
3973                 surface = model->data_surfaces + surfaceindex;
3974                 surface->num_firstvertex = outvertexindex;
3975                 surface->num_vertices = surface->num_triangles*3;
3976                 e = oldsurfmesh.data_element3i + surface->num_firsttriangle*3;
3977                 for (i = 0;i < surface->num_triangles*3;i++)
3978                 {
3979                         vertexindex = e[i];
3980                         model->surfmesh.data_vertex3f[outvertexindex*3+0] = oldsurfmesh.data_vertex3f[vertexindex*3+0];
3981                         model->surfmesh.data_vertex3f[outvertexindex*3+1] = oldsurfmesh.data_vertex3f[vertexindex*3+1];
3982                         model->surfmesh.data_vertex3f[outvertexindex*3+2] = oldsurfmesh.data_vertex3f[vertexindex*3+2];
3983                         model->surfmesh.data_normal3f[outvertexindex*3+0] = oldsurfmesh.data_normal3f[vertexindex*3+0];
3984                         model->surfmesh.data_normal3f[outvertexindex*3+1] = oldsurfmesh.data_normal3f[vertexindex*3+1];
3985                         model->surfmesh.data_normal3f[outvertexindex*3+2] = oldsurfmesh.data_normal3f[vertexindex*3+2];
3986                         model->surfmesh.data_svector3f[outvertexindex*3+0] = oldsurfmesh.data_svector3f[vertexindex*3+0];
3987                         model->surfmesh.data_svector3f[outvertexindex*3+1] = oldsurfmesh.data_svector3f[vertexindex*3+1];
3988                         model->surfmesh.data_svector3f[outvertexindex*3+2] = oldsurfmesh.data_svector3f[vertexindex*3+2];
3989                         model->surfmesh.data_tvector3f[outvertexindex*3+0] = oldsurfmesh.data_tvector3f[vertexindex*3+0];
3990                         model->surfmesh.data_tvector3f[outvertexindex*3+1] = oldsurfmesh.data_tvector3f[vertexindex*3+1];
3991                         model->surfmesh.data_tvector3f[outvertexindex*3+2] = oldsurfmesh.data_tvector3f[vertexindex*3+2];
3992                         model->surfmesh.data_texcoordtexture2f[outvertexindex*2+0] = oldsurfmesh.data_texcoordtexture2f[vertexindex*2+0];
3993                         model->surfmesh.data_texcoordtexture2f[outvertexindex*2+1] = oldsurfmesh.data_texcoordtexture2f[vertexindex*2+1];
3994                         if (oldsurfmesh.data_texcoordlightmap2f)
3995                         {
3996                                 model->surfmesh.data_texcoordlightmap2f[outvertexindex*2+0] = oldsurfmesh.data_texcoordlightmap2f[vertexindex*2+0];
3997                                 model->surfmesh.data_texcoordlightmap2f[outvertexindex*2+1] = oldsurfmesh.data_texcoordlightmap2f[vertexindex*2+1];
3998                         }
3999                         if (oldsurfmesh.data_lightmapcolor4f)
4000                         {
4001                                 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+0] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+0];
4002                                 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+1] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+1];
4003                                 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+2] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+2];
4004                                 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+3] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+3];
4005                         }
4006                         else
4007                                 Vector4Set(model->surfmesh.data_lightmapcolor4f + 4*outvertexindex, 1, 1, 1, 1);
4008                         model->surfmesh.data_element3i[surface->num_firsttriangle*3+i] = outvertexindex;
4009                         outvertexindex++;
4010                 }
4011         }
4012         if (model->surfmesh.data_element3s)
4013                 for (i = 0;i < model->surfmesh.num_triangles*3;i++)
4014                         model->surfmesh.data_element3s[i] = model->surfmesh.data_element3i[i];
4015
4016         // find and update all submodels to use this new surfmesh data
4017         for (i = 0;i < model->brush.numsubmodels;i++)
4018                 model->brush.submodels[i]->surfmesh = model->surfmesh;
4019 }
4020
4021 static void Mod_GenerateLightmaps_CreateTriangleInformation(dp_model_t *model)
4022 {
4023         msurface_t *surface;
4024         int surfaceindex;
4025         int i;
4026         int axis;
4027         float normal[3];
4028         const int *e;
4029         lightmaptriangle_t *triangle;
4030         // generate lightmap triangle structs
4031         mod_generatelightmaps_lightmaptriangles = (lightmaptriangle_t *)Mem_Alloc(model->mempool, model->surfmesh.num_triangles * sizeof(lightmaptriangle_t));
4032         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
4033         {
4034                 surface = model->data_surfaces + surfaceindex;
4035                 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
4036                 for (i = 0;i < surface->num_triangles;i++)
4037                 {
4038                         triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
4039                         triangle->triangleindex = surface->num_firsttriangle+i;
4040                         triangle->surfaceindex = surfaceindex;
4041                         VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+0], triangle->vertex[0]);
4042                         VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+1], triangle->vertex[1]);
4043                         VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+2], triangle->vertex[2]);
4044                         // calculate bounds of triangle
4045                         triangle->mins[0] = min(triangle->vertex[0][0], min(triangle->vertex[1][0], triangle->vertex[2][0]));
4046                         triangle->mins[1] = min(triangle->vertex[0][1], min(triangle->vertex[1][1], triangle->vertex[2][1]));
4047                         triangle->mins[2] = min(triangle->vertex[0][2], min(triangle->vertex[1][2], triangle->vertex[2][2]));
4048                         triangle->maxs[0] = max(triangle->vertex[0][0], max(triangle->vertex[1][0], triangle->vertex[2][0]));
4049                         triangle->maxs[1] = max(triangle->vertex[0][1], max(triangle->vertex[1][1], triangle->vertex[2][1]));
4050                         triangle->maxs[2] = max(triangle->vertex[0][2], max(triangle->vertex[1][2], triangle->vertex[2][2]));
4051                         // pick an axial projection based on the triangle normal
4052                         TriangleNormal(triangle->vertex[0], triangle->vertex[1], triangle->vertex[2], normal);
4053                         axis = 0;
4054                         if (fabs(normal[1]) > fabs(normal[axis]))
4055                                 axis = 1;
4056                         if (fabs(normal[2]) > fabs(normal[axis]))
4057                                 axis = 2;
4058                         triangle->axis = axis;
4059                 }
4060         }
4061 }
4062
4063 static void Mod_GenerateLightmaps_DestroyTriangleInformation(dp_model_t *model)
4064 {
4065         if (mod_generatelightmaps_lightmaptriangles)
4066                 Mem_Free(mod_generatelightmaps_lightmaptriangles);
4067         mod_generatelightmaps_lightmaptriangles = NULL;
4068 }
4069
4070 float lmaxis[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
4071
4072 static void Mod_GenerateLightmaps_CreateLightmaps(dp_model_t *model)
4073 {
4074         msurface_t *surface;
4075         int surfaceindex;
4076         int lightmapindex;
4077         int lightmapnumber;
4078         int i;
4079         int j;
4080         int k;
4081         int x;
4082         int y;
4083         int axis;
4084         int axis1;
4085         int axis2;
4086         int retry;
4087         int pixeloffset;
4088         float trianglenormal[3];
4089         float samplecenter[3];
4090         float samplenormal[3];
4091         float temp[3];
4092         float lmiscale[2];
4093         float slopex;
4094         float slopey;
4095         float slopebase;
4096         float lmscalepixels;
4097         float lmmins;
4098         float lmmaxs;
4099         float lm_basescalepixels;
4100         int lm_borderpixels;
4101         int lm_texturesize;
4102         //int lm_maxpixels;
4103         const int *e;
4104         lightmaptriangle_t *triangle;
4105         unsigned char *lightmappixels;
4106         unsigned char *deluxemappixels;
4107         mod_alloclightmap_state_t lmstate;
4108         char vabuf[1024];
4109
4110         // generate lightmap projection information for all triangles
4111         if (model->texturepool == NULL)
4112                 model->texturepool = R_AllocTexturePool();
4113         lm_basescalepixels = 1.0f / max(0.0001f, mod_generatelightmaps_unitspersample.value);
4114         lm_borderpixels = mod_generatelightmaps_borderpixels.integer;
4115         lm_texturesize = bound(lm_borderpixels*2+1, 64, (int)vid.maxtexturesize_2d);
4116         //lm_maxpixels = lm_texturesize-(lm_borderpixels*2+1);
4117         Mod_AllocLightmap_Init(&lmstate, lm_texturesize, lm_texturesize);
4118         lightmapnumber = 0;
4119         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
4120         {
4121                 surface = model->data_surfaces + surfaceindex;
4122                 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
4123                 lmscalepixels = lm_basescalepixels;
4124                 for (retry = 0;retry < 30;retry++)
4125                 {
4126                         // after a couple failed attempts, degrade quality to make it fit
4127                         if (retry > 1)
4128                                 lmscalepixels *= 0.5f;
4129                         for (i = 0;i < surface->num_triangles;i++)
4130                         {
4131                                 triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
4132                                 triangle->lightmapindex = lightmapnumber;
4133                                 // calculate lightmap bounds in 3D pixel coordinates, limit size,
4134                                 // pick two planar axes for projection
4135                                 // lightmap coordinates here are in pixels
4136                                 // lightmap projections are snapped to pixel grid explicitly, such
4137                                 // that two neighboring triangles sharing an edge and projection
4138                                 // axis will have identical sampl espacing along their shared edge
4139                                 k = 0;
4140                                 for (j = 0;j < 3;j++)
4141                                 {
4142                                         if (j == triangle->axis)
4143                                                 continue;
4144                                         lmmins = floor(triangle->mins[j]*lmscalepixels)-lm_borderpixels;
4145                                         lmmaxs = floor(triangle->maxs[j]*lmscalepixels)+lm_borderpixels;
4146                                         triangle->lmsize[k] = (int)(lmmaxs-lmmins);
4147                                         triangle->lmbase[k] = lmmins/lmscalepixels;
4148                                         triangle->lmscale[k] = lmscalepixels;
4149                                         k++;
4150                                 }
4151                                 if (!Mod_AllocLightmap_Block(&lmstate, triangle->lmsize[0], triangle->lmsize[1], &triangle->lmoffset[0], &triangle->lmoffset[1]))
4152                                         break;
4153                         }
4154                         // if all fit in this texture, we're done with this surface
4155                         if (i == surface->num_triangles)
4156                                 break;
4157                         // if we haven't maxed out the lightmap size yet, we retry the
4158                         // entire surface batch...
4159                         if (lm_texturesize * 2 <= min(mod_generatelightmaps_texturesize.integer, (int)vid.maxtexturesize_2d))
4160                         {
4161                                 lm_texturesize *= 2;
4162                                 surfaceindex = -1;
4163                                 lightmapnumber = 0;
4164                                 Mod_AllocLightmap_Free(&lmstate);
4165                                 Mod_AllocLightmap_Init(&lmstate, lm_texturesize, lm_texturesize);
4166                                 break;
4167                         }
4168                         // if we have maxed out the lightmap size, and this triangle does
4169                         // not fit in the same texture as the rest of the surface, we have
4170                         // to retry the entire surface in a new texture (can only use one)
4171                         // with multiple retries, the lightmap quality degrades until it
4172                         // fits (or gives up)
4173                         if (surfaceindex > 0)
4174                                 lightmapnumber++;
4175                         Mod_AllocLightmap_Reset(&lmstate);
4176                 }
4177         }
4178         lightmapnumber++;
4179         Mod_AllocLightmap_Free(&lmstate);
4180
4181         // now put triangles together into lightmap textures, and do not allow
4182         // triangles of a surface to go into different textures (as that would
4183         // require rewriting the surface list)
4184         model->brushq3.deluxemapping_modelspace = true;
4185         model->brushq3.deluxemapping = true;
4186         model->brushq3.num_mergedlightmaps = lightmapnumber;
4187         model->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(model->mempool, model->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4188         model->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(model->mempool, model->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
4189         lightmappixels = (unsigned char *)Mem_Alloc(tempmempool, model->brushq3.num_mergedlightmaps * lm_texturesize * lm_texturesize * 4);
4190         deluxemappixels = (unsigned char *)Mem_Alloc(tempmempool, model->brushq3.num_mergedlightmaps * lm_texturesize * lm_texturesize * 4);
4191         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
4192         {
4193                 surface = model->data_surfaces + surfaceindex;
4194                 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
4195                 for (i = 0;i < surface->num_triangles;i++)
4196                 {
4197                         triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
4198                         TriangleNormal(triangle->vertex[0], triangle->vertex[1], triangle->vertex[2], trianglenormal);
4199                         VectorNormalize(trianglenormal);
4200                         VectorCopy(trianglenormal, samplenormal); // FIXME: this is supposed to be interpolated per pixel from vertices
4201                         axis = triangle->axis;
4202                         axis1 = axis == 0 ? 1 : 0;
4203                         axis2 = axis == 2 ? 1 : 2;
4204                         lmiscale[0] = 1.0f / triangle->lmscale[0];
4205                         lmiscale[1] = 1.0f / triangle->lmscale[1];
4206                         if (trianglenormal[axis] < 0)
4207                                 VectorNegate(trianglenormal, trianglenormal);
4208                         CrossProduct(lmaxis[axis2], trianglenormal, temp);slopex = temp[axis] / temp[axis1];
4209                         CrossProduct(lmaxis[axis1], trianglenormal, temp);slopey = temp[axis] / temp[axis2];
4210                         slopebase = triangle->vertex[0][axis] - triangle->vertex[0][axis1]*slopex - triangle->vertex[0][axis2]*slopey;
4211                         for (j = 0;j < 3;j++)
4212                         {
4213                                 float *t2f = model->surfmesh.data_texcoordlightmap2f + e[i*3+j]*2;
4214                                 t2f[0] = ((triangle->vertex[j][axis1] - triangle->lmbase[0]) * triangle->lmscale[0] + triangle->lmoffset[0]) / lm_texturesize;
4215                                 t2f[1] = ((triangle->vertex[j][axis2] - triangle->lmbase[1]) * triangle->lmscale[1] + triangle->lmoffset[1]) / lm_texturesize;
4216 #if 0
4217                                 samplecenter[axis1] = (t2f[0]*lm_texturesize-triangle->lmoffset[0])*lmiscale[0] + triangle->lmbase[0];
4218                                 samplecenter[axis2] = (t2f[1]*lm_texturesize-triangle->lmoffset[1])*lmiscale[1] + triangle->lmbase[1];
4219                                 samplecenter[axis] = samplecenter[axis1]*slopex + samplecenter[axis2]*slopey + slopebase;
4220                                 Con_Printf("%f:%f %f:%f %f:%f = %f %f\n", triangle->vertex[j][axis1], samplecenter[axis1], triangle->vertex[j][axis2], samplecenter[axis2], triangle->vertex[j][axis], samplecenter[axis], t2f[0], t2f[1]);
4221 #endif
4222                         }
4223
4224 #if 0
4225                         switch (axis)
4226                         {
4227                         default:
4228                         case 0:
4229                                 forward[0] = 0;
4230                                 forward[1] = 1.0f / triangle->lmscale[0];
4231                                 forward[2] = 0;
4232                                 left[0] = 0;
4233                                 left[1] = 0;
4234                                 left[2] = 1.0f / triangle->lmscale[1];
4235                                 up[0] = 1.0f;
4236                                 up[1] = 0;
4237                                 up[2] = 0;
4238                                 origin[0] = 0;
4239                                 origin[1] = triangle->lmbase[0];
4240                                 origin[2] = triangle->lmbase[1];
4241                                 break;
4242                         case 1:
4243                                 forward[0] = 1.0f / triangle->lmscale[0];
4244                                 forward[1] = 0;
4245                                 forward[2] = 0;
4246                                 left[0] = 0;
4247                                 left[1] = 0;
4248                                 left[2] = 1.0f / triangle->lmscale[1];
4249                                 up[0] = 0;
4250                                 up[1] = 1.0f;
4251                                 up[2] = 0;
4252                                 origin[0] = triangle->lmbase[0];
4253                                 origin[1] = 0;
4254                                 origin[2] = triangle->lmbase[1];
4255                                 break;
4256                         case 2:
4257                                 forward[0] = 1.0f / triangle->lmscale[0];
4258                                 forward[1] = 0;
4259                                 forward[2] = 0;
4260                                 left[0] = 0;
4261                                 left[1] = 1.0f / triangle->lmscale[1];
4262                                 left[2] = 0;
4263                                 up[0] = 0;
4264                                 up[1] = 0;
4265                                 up[2] = 1.0f;
4266                                 origin[0] = triangle->lmbase[0];
4267                                 origin[1] = triangle->lmbase[1];
4268                                 origin[2] = 0;
4269                                 break;
4270                         }
4271                         Matrix4x4_FromVectors(&backmatrix, forward, left, up, origin);
4272 #endif
4273 #define LM_DIST_EPSILON (1.0f / 32.0f)
4274                         for (y = 0;y < triangle->lmsize[1];y++)
4275                         {
4276                                 pixeloffset = ((triangle->lightmapindex * lm_texturesize + y + triangle->lmoffset[1]) * lm_texturesize + triangle->lmoffset[0]) * 4;
4277                                 for (x = 0;x < triangle->lmsize[0];x++, pixeloffset += 4)
4278                                 {
4279                                         samplecenter[axis1] = (x+0.5f)*lmiscale[0] + triangle->lmbase[0];
4280                                         samplecenter[axis2] = (y+0.5f)*lmiscale[1] + triangle->lmbase[1];
4281                                         samplecenter[axis] = samplecenter[axis1]*slopex + samplecenter[axis2]*slopey + slopebase;
4282                                         VectorMA(samplecenter, 0.125f, samplenormal, samplecenter);
4283                                         Mod_GenerateLightmaps_LightmapSample(samplecenter, samplenormal, lightmappixels + pixeloffset, deluxemappixels + pixeloffset);
4284                                 }
4285                         }
4286                 }
4287         }
4288
4289         for (lightmapindex = 0;lightmapindex < model->brushq3.num_mergedlightmaps;lightmapindex++)
4290         {
4291                 model->brushq3.data_lightmaps[lightmapindex] = R_LoadTexture2D(model->texturepool, va(vabuf, sizeof(vabuf), "lightmap%i", lightmapindex), lm_texturesize, lm_texturesize, lightmappixels + lightmapindex * lm_texturesize * lm_texturesize * 4, TEXTYPE_BGRA, TEXF_FORCELINEAR, -1, NULL);
4292                 model->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(model->texturepool, va(vabuf, sizeof(vabuf), "deluxemap%i", lightmapindex), lm_texturesize, lm_texturesize, deluxemappixels + lightmapindex * lm_texturesize * lm_texturesize * 4, TEXTYPE_BGRA, TEXF_FORCELINEAR, -1, NULL);
4293         }
4294
4295         if (lightmappixels)
4296                 Mem_Free(lightmappixels);
4297         if (deluxemappixels)
4298                 Mem_Free(deluxemappixels);
4299
4300         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
4301         {
4302                 surface = model->data_surfaces + surfaceindex;
4303                 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
4304                 if (!surface->num_triangles)
4305                         continue;
4306                 lightmapindex = mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle].lightmapindex;
4307                 surface->lightmaptexture = model->brushq3.data_lightmaps[lightmapindex];
4308                 surface->deluxemaptexture = model->brushq3.data_deluxemaps[lightmapindex];
4309                 surface->lightmapinfo = NULL;
4310         }
4311
4312         model->brush.LightPoint = Mod_GenerateLightmaps_LightPoint;
4313         model->brushq1.lightdata = NULL;
4314         model->brushq1.lightmapupdateflags = NULL;
4315         model->brushq1.firstrender = false;
4316         model->brushq1.num_lightstyles = 0;
4317         model->brushq1.data_lightstyleinfo = NULL;
4318         for (i = 0;i < model->brush.numsubmodels;i++)
4319         {
4320                 model->brush.submodels[i]->brushq1.lightmapupdateflags = NULL;
4321                 model->brush.submodels[i]->brushq1.firstrender = false;
4322                 model->brush.submodels[i]->brushq1.num_lightstyles = 0;
4323                 model->brush.submodels[i]->brushq1.data_lightstyleinfo = NULL;
4324         }
4325 }
4326
4327 static void Mod_GenerateLightmaps_UpdateVertexColors(dp_model_t *model)
4328 {
4329         int i;
4330         for (i = 0;i < model->surfmesh.num_vertices;i++)
4331                 Mod_GenerateLightmaps_VertexSample(model->surfmesh.data_vertex3f + 3*i, model->surfmesh.data_normal3f + 3*i, model->surfmesh.data_lightmapcolor4f + 4*i);
4332 }
4333
4334 static void Mod_GenerateLightmaps_UpdateLightGrid(dp_model_t *model)
4335 {
4336         int x;
4337         int y;
4338         int z;
4339         int index = 0;
4340         float pos[3];
4341         for (z = 0;z < model->brushq3.num_lightgrid_isize[2];z++)
4342         {
4343                 pos[2] = (model->brushq3.num_lightgrid_imins[2] + z + 0.5f) * model->brushq3.num_lightgrid_cellsize[2];
4344                 for (y = 0;y < model->brushq3.num_lightgrid_isize[1];y++)
4345                 {
4346                         pos[1] = (model->brushq3.num_lightgrid_imins[1] + y + 0.5f) * model->brushq3.num_lightgrid_cellsize[1];
4347                         for (x = 0;x < model->brushq3.num_lightgrid_isize[0];x++, index++)
4348                         {
4349                                 pos[0] = (model->brushq3.num_lightgrid_imins[0] + x + 0.5f) * model->brushq3.num_lightgrid_cellsize[0];
4350                                 Mod_GenerateLightmaps_GridSample(pos, model->brushq3.data_lightgrid + index);
4351                         }
4352                 }
4353         }
4354 }
4355
4356 extern cvar_t mod_q3bsp_nolightmaps;
4357 static void Mod_GenerateLightmaps(dp_model_t *model)
4358 {
4359         //lightmaptriangle_t *lightmaptriangles = Mem_Alloc(model->mempool, model->surfmesh.num_triangles * sizeof(lightmaptriangle_t));
4360         dp_model_t *oldloadmodel = loadmodel;
4361         loadmodel = model;
4362
4363         Mod_GenerateLightmaps_InitSampleOffsets(model);
4364         Mod_GenerateLightmaps_DestroyLightmaps(model);
4365         Mod_GenerateLightmaps_UnweldTriangles(model);
4366         Mod_GenerateLightmaps_CreateTriangleInformation(model);
4367         Mod_GenerateLightmaps_CreateLights(model);
4368         if(!mod_q3bsp_nolightmaps.integer)
4369                 Mod_GenerateLightmaps_CreateLightmaps(model);
4370         Mod_GenerateLightmaps_UpdateVertexColors(model);
4371         Mod_GenerateLightmaps_UpdateLightGrid(model);
4372         Mod_GenerateLightmaps_DestroyLights(model);
4373         Mod_GenerateLightmaps_DestroyTriangleInformation(model);
4374
4375         loadmodel = oldloadmodel;
4376 }
4377
4378 static void Mod_GenerateLightmaps_f(void)
4379 {
4380         if (Cmd_Argc() != 1)
4381         {
4382                 Con_Printf("usage: mod_generatelightmaps\n");
4383                 return;
4384         }
4385         if (!cl.worldmodel)
4386         {
4387                 Con_Printf("no worldmodel loaded\n");
4388                 return;
4389         }
4390         Mod_GenerateLightmaps(cl.worldmodel);
4391 }