new cvars:
[divverent/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_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"};
31 cvar_t mod_generatelightmaps_unitspersample = {CVAR_SAVE, "mod_generatelightmaps_unitspersample", "8", "lightmap resolution"};
32 cvar_t mod_generatelightmaps_borderpixels = {CVAR_SAVE, "mod_generatelightmaps_borderpixels", "2", "extra space around polygons to prevent sampling artifacts"};
33 cvar_t mod_generatelightmaps_texturesize = {CVAR_SAVE, "mod_generatelightmaps_texturesize", "1024", "size of lightmap textures"};
34 cvar_t mod_generatelightmaps_lightmapsamples = {CVAR_SAVE, "mod_generatelightmaps_lightmapsamples", "16", "number of shadow tests done per lightmap pixel"};
35 cvar_t mod_generatelightmaps_vertexsamples = {CVAR_SAVE, "mod_generatelightmaps_vertexsamples", "16", "number of shadow tests done per vertex"};
36 cvar_t mod_generatelightmaps_gridsamples = {CVAR_SAVE, "mod_generatelightmaps_gridsamples", "64", "number of shadow tests done per lightgrid cell"};
37 cvar_t mod_generatelightmaps_lightmapradius = {CVAR_SAVE, "mod_generatelightmaps_lightmapradius", "16", "sampling area around each lightmap pixel"};
38 cvar_t mod_generatelightmaps_vertexradius = {CVAR_SAVE, "mod_generatelightmaps_vertexradius", "16", "sampling area around each vertex"};
39 cvar_t mod_generatelightmaps_gridradius = {CVAR_SAVE, "mod_generatelightmaps_gridradius", "64", "sampling area around each lightgrid cell center"};
40
41 dp_model_t *loadmodel;
42
43 static mempool_t *mod_mempool;
44 static memexpandablearray_t models;
45
46 static mempool_t* q3shaders_mem;
47 typedef struct q3shader_hash_entry_s
48 {
49   q3shaderinfo_t shader;
50   struct q3shader_hash_entry_s* chain;
51 } q3shader_hash_entry_t;
52 #define Q3SHADER_HASH_SIZE  1021
53 typedef struct q3shader_data_s
54 {
55   memexpandablearray_t hash_entries;
56   q3shader_hash_entry_t hash[Q3SHADER_HASH_SIZE];
57   memexpandablearray_t char_ptrs;
58 } q3shader_data_t;
59 static q3shader_data_t* q3shader_data;
60
61 static void mod_start(void)
62 {
63         int i, count;
64         int nummodels = Mem_ExpandableArray_IndexRange(&models);
65         dp_model_t *mod;
66
67         SCR_PushLoadingScreen(false, "Loading models", 1.0);
68         count = 0;
69         for (i = 0;i < nummodels;i++)
70                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
71                         if (mod->used)
72                                 ++count;
73         for (i = 0;i < nummodels;i++)
74                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
75                         if (mod->used)
76                         {
77                                 SCR_PushLoadingScreen(true, mod->name, 1.0 / count);
78                                 Mod_LoadModel(mod, true, false);
79                                 SCR_PopLoadingScreen(false);
80                         }
81         SCR_PopLoadingScreen(false);
82 }
83
84 static void mod_shutdown(void)
85 {
86         int i;
87         int nummodels = Mem_ExpandableArray_IndexRange(&models);
88         dp_model_t *mod;
89
90         for (i = 0;i < nummodels;i++)
91                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && (mod->loaded || mod->mempool))
92                         Mod_UnloadModel(mod);
93
94         Mod_FreeQ3Shaders();
95         Mod_Skeletal_FreeBuffers();
96 }
97
98 static void mod_newmap(void)
99 {
100         msurface_t *surface;
101         int i, j, k, surfacenum, ssize, tsize;
102         int nummodels = Mem_ExpandableArray_IndexRange(&models);
103         dp_model_t *mod;
104
105         for (i = 0;i < nummodels;i++)
106         {
107                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool)
108                 {
109                         for (j = 0;j < mod->num_textures && mod->data_textures;j++)
110                         {
111                                 for (k = 0;k < mod->data_textures[j].numskinframes;k++)
112                                         R_SkinFrame_MarkUsed(mod->data_textures[j].skinframes[k]);
113                                 for (k = 0;k < mod->data_textures[j].backgroundnumskinframes;k++)
114                                         R_SkinFrame_MarkUsed(mod->data_textures[j].backgroundskinframes[k]);
115                         }
116                         if (mod->brush.solidskyskinframe)
117                                 R_SkinFrame_MarkUsed(mod->brush.solidskyskinframe);
118                         if (mod->brush.alphaskyskinframe)
119                                 R_SkinFrame_MarkUsed(mod->brush.alphaskyskinframe);
120                 }
121         }
122
123         if (!cl_stainmaps_clearonload.integer)
124                 return;
125
126         for (i = 0;i < nummodels;i++)
127         {
128                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool && mod->data_surfaces)
129                 {
130                         for (surfacenum = 0, surface = mod->data_surfaces;surfacenum < mod->num_surfaces;surfacenum++, surface++)
131                         {
132                                 if (surface->lightmapinfo && surface->lightmapinfo->stainsamples)
133                                 {
134                                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
135                                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
136                                         memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
137                                         mod->brushq1.lightmapupdateflags[surfacenum] = true;
138                                 }
139                         }
140                 }
141         }
142 }
143
144 /*
145 ===============
146 Mod_Init
147 ===============
148 */
149 static void Mod_Print(void);
150 static void Mod_Precache (void);
151 static void Mod_Decompile_f(void);
152 static void Mod_GenerateLightmaps_f(void);
153 void Mod_Init (void)
154 {
155         mod_mempool = Mem_AllocPool("modelinfo", 0, NULL);
156         Mem_ExpandableArray_NewArray(&models, mod_mempool, sizeof(dp_model_t), 16);
157
158         Mod_BrushInit();
159         Mod_AliasInit();
160         Mod_SpriteInit();
161
162         Cvar_RegisterVariable(&r_mipskins);
163         Cvar_RegisterVariable(&mod_generatelightmaps_unitspersample);
164         Cvar_RegisterVariable(&mod_generatelightmaps_borderpixels);
165         Cvar_RegisterVariable(&mod_generatelightmaps_texturesize);
166
167         Cvar_RegisterVariable(&mod_generatelightmaps_lightmapsamples);
168         Cvar_RegisterVariable(&mod_generatelightmaps_vertexsamples);
169         Cvar_RegisterVariable(&mod_generatelightmaps_gridsamples);
170         Cvar_RegisterVariable(&mod_generatelightmaps_lightmapradius);
171         Cvar_RegisterVariable(&mod_generatelightmaps_vertexradius);
172         Cvar_RegisterVariable(&mod_generatelightmaps_gridradius);
173
174         Cmd_AddCommand ("modellist", Mod_Print, "prints a list of loaded models");
175         Cmd_AddCommand ("modelprecache", Mod_Precache, "load a model");
176         Cmd_AddCommand ("modeldecompile", Mod_Decompile_f, "exports a model in several formats for editing purposes");
177         Cmd_AddCommand ("mod_generatelightmaps", Mod_GenerateLightmaps_f, "rebuilds lighting on current worldmodel");
178 }
179
180 void Mod_RenderInit(void)
181 {
182         R_RegisterModule("Models", mod_start, mod_shutdown, mod_newmap);
183 }
184
185 void Mod_UnloadModel (dp_model_t *mod)
186 {
187         char name[MAX_QPATH];
188         qboolean used;
189         dp_model_t *parentmodel;
190
191         if (developer_loading.integer)
192                 Con_Printf("unloading model %s\n", mod->name);
193
194         strlcpy(name, mod->name, sizeof(name));
195         parentmodel = mod->brush.parentmodel;
196         used = mod->used;
197         if (mod->mempool)
198         {
199                 if (mod->surfmesh.vertexpositionbuffer)
200                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.vertexpositionbuffer);
201                 mod->surfmesh.vertexpositionbuffer = NULL;
202                 if (mod->surfmesh.vertexmeshbuffer)
203                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.vertexmeshbuffer);
204                 mod->surfmesh.vertexmeshbuffer = NULL;
205                 if (mod->surfmesh.data_element3i_indexbuffer)
206                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.data_element3i_indexbuffer);
207                 mod->surfmesh.data_element3i_indexbuffer = NULL;
208                 if (mod->surfmesh.data_element3s_indexbuffer)
209                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.data_element3s_indexbuffer);
210                 mod->surfmesh.data_element3s_indexbuffer = NULL;
211                 if (mod->surfmesh.vbo_vertexbuffer)
212                         R_Mesh_DestroyMeshBuffer(mod->surfmesh.vbo_vertexbuffer);
213                 mod->surfmesh.vbo_vertexbuffer = NULL;
214         }
215         // free textures/memory attached to the model
216         R_FreeTexturePool(&mod->texturepool);
217         Mem_FreePool(&mod->mempool);
218         // clear the struct to make it available
219         memset(mod, 0, sizeof(dp_model_t));
220         // restore the fields we want to preserve
221         strlcpy(mod->name, name, sizeof(mod->name));
222         mod->brush.parentmodel = parentmodel;
223         mod->used = used;
224         mod->loaded = false;
225 }
226
227 void R_Model_Null_Draw(entity_render_t *ent)
228 {
229         return;
230 }
231
232
233 typedef void (*mod_framegroupify_parsegroups_t) (unsigned int i, int start, int len, float fps, qboolean loop, void *pass);
234
235 int Mod_FrameGroupify_ParseGroups(const char *buf, mod_framegroupify_parsegroups_t cb, void *pass)
236 {
237         const char *bufptr;
238         int start, len;
239         float fps;
240         unsigned int i;
241         qboolean loop;
242
243         bufptr = buf;
244         i = 0;
245         for(;;)
246         {
247                 // an anim scene!
248                 if (!COM_ParseToken_Simple(&bufptr, true, false))
249                         break;
250                 if (!strcmp(com_token, "\n"))
251                         continue; // empty line
252                 start = atoi(com_token);
253                 if (!COM_ParseToken_Simple(&bufptr, true, false))
254                         break;
255                 if (!strcmp(com_token, "\n"))
256                 {
257                         Con_Printf("framegroups file: missing number of frames\n");
258                         continue;
259                 }
260                 len = atoi(com_token);
261                 if (!COM_ParseToken_Simple(&bufptr, true, false))
262                         break;
263                 // we default to looping as it's usually wanted, so to NOT loop you append a 0
264                 if (strcmp(com_token, "\n"))
265                 {
266                         fps = atof(com_token);
267                         if (!COM_ParseToken_Simple(&bufptr, true, false))
268                                 break;
269                         if (strcmp(com_token, "\n"))
270                                 loop = atoi(com_token) != 0;
271                         else
272                                 loop = true;
273                 }
274                 else
275                 {
276                         fps = 20;
277                         loop = true;
278                 }
279
280                 if(cb)
281                         cb(i, start, len, fps, loop, pass);
282                 ++i;
283         }
284
285         return i;
286 }
287
288 void Mod_FrameGroupify_ParseGroups_Count (unsigned int i, int start, int len, float fps, qboolean loop, void *pass)
289 {
290         unsigned int *cnt = (unsigned int *) pass;
291         ++*cnt;
292 }
293
294 void Mod_FrameGroupify_ParseGroups_Store (unsigned int i, int start, int len, float fps, qboolean loop, void *pass)
295 {
296         dp_model_t *mod = (dp_model_t *) pass;
297         animscene_t *anim = &mod->animscenes[i];
298         dpsnprintf(anim->name, sizeof(anim[i].name), "groupified_%d_anim", i);
299         anim->firstframe = bound(0, start, mod->num_poses - 1);
300         anim->framecount = bound(1, len, mod->num_poses - anim->firstframe);
301         anim->framerate = max(1, fps);
302         anim->loop = !!loop;
303         //Con_Printf("frame group %d is %d %d %f %d\n", i, start, len, fps, loop);
304 }
305
306 void Mod_FrameGroupify(dp_model_t *mod, const char *buf)
307 {
308         unsigned int cnt;
309
310         // 0. count
311         cnt = Mod_FrameGroupify_ParseGroups(buf, NULL, NULL);
312         if(!cnt)
313         {
314                 Con_Printf("no scene found in framegroups file, aborting\n");
315                 return;
316         }
317         mod->numframes = cnt;
318
319         // 1. reallocate
320         // (we do not free the previous animscenes, but model unloading will free the pool owning them, so it's okay)
321         mod->animscenes = (animscene_t *) Mem_Alloc(mod->mempool, sizeof(animscene_t) * mod->numframes);
322
323         // 2. parse
324         Mod_FrameGroupify_ParseGroups(buf, Mod_FrameGroupify_ParseGroups_Store, mod);
325 }
326
327 void Mod_FindPotentialDeforms(dp_model_t *mod)
328 {
329         int i, j;
330         texture_t *texture;
331         mod->wantnormals = false;
332         mod->wanttangents = false;
333         for (i = 0;i < mod->num_textures;i++)
334         {
335                 texture = mod->data_textures + i;
336                 if (texture->tcgen.tcgen == Q3TCGEN_ENVIRONMENT)
337                         mod->wantnormals = true;
338                 for (j = 0;j < Q3MAXDEFORMS;j++)
339                 {
340                         if (texture->deforms[j].deform == Q3DEFORM_AUTOSPRITE)
341                         {
342                                 mod->wanttangents = true;
343                                 mod->wantnormals = true;
344                                 break;
345                         }
346                         if (texture->deforms[j].deform != Q3DEFORM_NONE)
347                                 mod->wantnormals = true;
348                 }
349         }
350 }
351
352 /*
353 ==================
354 Mod_LoadModel
355
356 Loads a model
357 ==================
358 */
359 dp_model_t *Mod_LoadModel(dp_model_t *mod, qboolean crash, qboolean checkdisk)
360 {
361         int num;
362         unsigned int crc;
363         void *buf;
364         fs_offset_t filesize;
365
366         mod->used = true;
367
368         if (mod->name[0] == '*') // submodel
369                 return mod;
370         
371         if (!strcmp(mod->name, "null"))
372         {
373                 if(mod->loaded)
374                         return mod;
375
376                 if (mod->loaded || mod->mempool)
377                         Mod_UnloadModel(mod);
378
379                 if (developer_loading.integer)
380                         Con_Printf("loading model %s\n", mod->name);
381
382                 mod->used = true;
383                 mod->crc = (unsigned int)-1;
384                 mod->loaded = false;
385
386                 VectorClear(mod->normalmins);
387                 VectorClear(mod->normalmaxs);
388                 VectorClear(mod->yawmins);
389                 VectorClear(mod->yawmaxs);
390                 VectorClear(mod->rotatedmins);
391                 VectorClear(mod->rotatedmaxs);
392
393                 mod->modeldatatypestring = "null";
394                 mod->type = mod_null;
395                 mod->Draw = R_Model_Null_Draw;
396                 mod->numframes = 2;
397                 mod->numskins = 1;
398
399                 // no fatal errors occurred, so this model is ready to use.
400                 mod->loaded = true;
401
402                 return mod;
403         }
404
405         crc = 0;
406         buf = NULL;
407
408         // even if the model is loaded it still may need reloading...
409
410         // if it is not loaded or checkdisk is true we need to calculate the crc
411         if (!mod->loaded || checkdisk)
412         {
413                 if (checkdisk && mod->loaded)
414                         Con_DPrintf("checking model %s\n", mod->name);
415                 buf = FS_LoadFile (mod->name, tempmempool, false, &filesize);
416                 if (buf)
417                 {
418                         crc = CRC_Block((unsigned char *)buf, filesize);
419                         // we need to reload the model if the crc does not match
420                         if (mod->crc != crc)
421                                 mod->loaded = false;
422                 }
423         }
424
425         // if the model is already loaded and checks passed, just return
426         if (mod->loaded)
427         {
428                 if (buf)
429                         Mem_Free(buf);
430                 return mod;
431         }
432
433         if (developer_loading.integer)
434                 Con_Printf("loading model %s\n", mod->name);
435         
436         SCR_PushLoadingScreen(true, mod->name, 1);
437
438         // LordHavoc: unload the existing model in this slot (if there is one)
439         if (mod->loaded || mod->mempool)
440                 Mod_UnloadModel(mod);
441
442         // load the model
443         mod->used = true;
444         mod->crc = crc;
445         // errors can prevent the corresponding mod->loaded = true;
446         mod->loaded = false;
447
448         // default model radius and bounding box (mainly for missing models)
449         mod->radius = 16;
450         VectorSet(mod->normalmins, -mod->radius, -mod->radius, -mod->radius);
451         VectorSet(mod->normalmaxs, mod->radius, mod->radius, mod->radius);
452         VectorSet(mod->yawmins, -mod->radius, -mod->radius, -mod->radius);
453         VectorSet(mod->yawmaxs, mod->radius, mod->radius, mod->radius);
454         VectorSet(mod->rotatedmins, -mod->radius, -mod->radius, -mod->radius);
455         VectorSet(mod->rotatedmaxs, mod->radius, mod->radius, mod->radius);
456
457         if (!q3shaders_mem)
458         {
459                 // load q3 shaders for the first time, or after a level change
460                 Mod_LoadQ3Shaders();
461         }
462
463         if (buf)
464         {
465                 char *bufend = (char *)buf + filesize;
466
467                 // all models use memory, so allocate a memory pool
468                 mod->mempool = Mem_AllocPool(mod->name, 0, NULL);
469
470                 num = LittleLong(*((int *)buf));
471                 // call the apropriate loader
472                 loadmodel = mod;
473                 if (!strcasecmp(FS_FileExtension(mod->name), "obj")) Mod_OBJ_Load(mod, buf, bufend);
474                 else if (!memcmp(buf, "IDPO", 4)) Mod_IDP0_Load(mod, buf, bufend);
475                 else if (!memcmp(buf, "IDP2", 4)) Mod_IDP2_Load(mod, buf, bufend);
476                 else if (!memcmp(buf, "IDP3", 4)) Mod_IDP3_Load(mod, buf, bufend);
477                 else if (!memcmp(buf, "IDSP", 4)) Mod_IDSP_Load(mod, buf, bufend);
478                 else if (!memcmp(buf, "IDS2", 4)) Mod_IDS2_Load(mod, buf, bufend);
479                 else if (!memcmp(buf, "IBSP", 4)) Mod_IBSP_Load(mod, buf, bufend);
480                 else if (!memcmp(buf, "ZYMOTICMODEL", 12)) Mod_ZYMOTICMODEL_Load(mod, buf, bufend);
481                 else if (!memcmp(buf, "DARKPLACESMODEL", 16)) Mod_DARKPLACESMODEL_Load(mod, buf, bufend);
482                 else if (!memcmp(buf, "ACTRHEAD", 8)) Mod_PSKMODEL_Load(mod, buf, bufend);
483                 else if (!memcmp(buf, "INTERQUAKEMODEL", 16)) Mod_INTERQUAKEMODEL_Load(mod, buf, bufend);
484                 else if (strlen(mod->name) >= 4 && !strcmp(mod->name + strlen(mod->name) - 4, ".map")) Mod_MAP_Load(mod, buf, bufend);
485                 else if (num == BSPVERSION || num == 30) Mod_Q1BSP_Load(mod, buf, bufend);
486                 else Con_Printf("Mod_LoadModel: model \"%s\" is of unknown/unsupported type\n", mod->name);
487                 Mem_Free(buf);
488
489                 Mod_FindPotentialDeforms(mod);
490                                         
491                 buf = FS_LoadFile (va("%s.framegroups", mod->name), tempmempool, false, &filesize);
492                 if(buf)
493                 {
494                         Mod_FrameGroupify(mod, (const char *)buf);
495                         Mem_Free(buf);
496                 }
497
498                 Mod_BuildVBOs();
499         }
500         else if (crash)
501         {
502                 // LordHavoc: Sys_Error was *ANNOYING*
503                 Con_Printf ("Mod_LoadModel: %s not found\n", mod->name);
504         }
505
506         // no fatal errors occurred, so this model is ready to use.
507         mod->loaded = true;
508
509         SCR_PopLoadingScreen(false);
510
511         return mod;
512 }
513
514 void Mod_ClearUsed(void)
515 {
516         int i;
517         int nummodels = Mem_ExpandableArray_IndexRange(&models);
518         dp_model_t *mod;
519         for (i = 0;i < nummodels;i++)
520                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0])
521                         mod->used = false;
522 }
523
524 void Mod_PurgeUnused(void)
525 {
526         int i;
527         int nummodels = Mem_ExpandableArray_IndexRange(&models);
528         dp_model_t *mod;
529         for (i = 0;i < nummodels;i++)
530         {
531                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !mod->used)
532                 {
533                         Mod_UnloadModel(mod);
534                         Mem_ExpandableArray_FreeRecord(&models, mod);
535                 }
536         }
537 }
538
539 /*
540 ==================
541 Mod_FindName
542
543 ==================
544 */
545 dp_model_t *Mod_FindName(const char *name, const char *parentname)
546 {
547         int i;
548         int nummodels;
549         dp_model_t *mod;
550
551         if (!parentname)
552                 parentname = "";
553
554         // if we're not dedicatd, the renderer calls will crash without video
555         Host_StartVideo();
556
557         nummodels = Mem_ExpandableArray_IndexRange(&models);
558
559         if (!name[0])
560                 Host_Error ("Mod_ForName: NULL name");
561
562         // search the currently loaded models
563         for (i = 0;i < nummodels;i++)
564         {
565                 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))))
566                 {
567                         mod->used = true;
568                         return mod;
569                 }
570         }
571
572         // no match found, create a new one
573         mod = (dp_model_t *) Mem_ExpandableArray_AllocRecord(&models);
574         strlcpy(mod->name, name, sizeof(mod->name));
575         if (parentname[0])
576                 mod->brush.parentmodel = Mod_FindName(parentname, NULL);
577         else
578                 mod->brush.parentmodel = NULL;
579         mod->loaded = false;
580         mod->used = true;
581         return mod;
582 }
583
584 /*
585 ==================
586 Mod_ForName
587
588 Loads in a model for the given name
589 ==================
590 */
591 dp_model_t *Mod_ForName(const char *name, qboolean crash, qboolean checkdisk, const char *parentname)
592 {
593         dp_model_t *model;
594         model = Mod_FindName(name, parentname);
595         if (!model->loaded || checkdisk)
596                 Mod_LoadModel(model, crash, checkdisk);
597         return model;
598 }
599
600 /*
601 ==================
602 Mod_Reload
603
604 Reloads all models if they have changed
605 ==================
606 */
607 void Mod_Reload(void)
608 {
609         int i, count;
610         int nummodels = Mem_ExpandableArray_IndexRange(&models);
611         dp_model_t *mod;
612
613         SCR_PushLoadingScreen(false, "Reloading models", 1.0);
614         count = 0;
615         for (i = 0;i < nummodels;i++)
616                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
617                         ++count;
618         for (i = 0;i < nummodels;i++)
619                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
620                 {
621                         SCR_PushLoadingScreen(true, mod->name, 1.0 / count);
622                         Mod_LoadModel(mod, true, true);
623                         SCR_PopLoadingScreen(false);
624                 }
625         SCR_PopLoadingScreen(false);
626 }
627
628 unsigned char *mod_base;
629
630
631 //=============================================================================
632
633 /*
634 ================
635 Mod_Print
636 ================
637 */
638 static void Mod_Print(void)
639 {
640         int i;
641         int nummodels = Mem_ExpandableArray_IndexRange(&models);
642         dp_model_t *mod;
643
644         Con_Print("Loaded models:\n");
645         for (i = 0;i < nummodels;i++)
646         {
647                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
648                 {
649                         if (mod->brush.numsubmodels)
650                                 Con_Printf("%4iK %s (%i submodels)\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name, mod->brush.numsubmodels);
651                         else
652                                 Con_Printf("%4iK %s\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name);
653                 }
654         }
655 }
656
657 /*
658 ================
659 Mod_Precache
660 ================
661 */
662 static void Mod_Precache(void)
663 {
664         if (Cmd_Argc() == 2)
665                 Mod_ForName(Cmd_Argv(1), false, true, Cmd_Argv(1)[0] == '*' ? cl.model_name[1] : NULL);
666         else
667                 Con_Print("usage: modelprecache <filename>\n");
668 }
669
670 int Mod_BuildVertexRemapTableFromElements(int numelements, const int *elements, int numvertices, int *remapvertices)
671 {
672         int i, count;
673         unsigned char *used;
674         used = (unsigned char *)Mem_Alloc(tempmempool, numvertices);
675         memset(used, 0, numvertices);
676         for (i = 0;i < numelements;i++)
677                 used[elements[i]] = 1;
678         for (i = 0, count = 0;i < numvertices;i++)
679                 remapvertices[i] = used[i] ? count++ : -1;
680         Mem_Free(used);
681         return count;
682 }
683
684 #if 1
685 // fast way, using an edge hash
686 #define TRIANGLEEDGEHASH 8192
687 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
688 {
689         int i, j, p, e1, e2, *n, hashindex, count, match;
690         const int *e;
691         typedef struct edgehashentry_s
692         {
693                 struct edgehashentry_s *next;
694                 int triangle;
695                 int element[2];
696         }
697         edgehashentry_t;
698         static edgehashentry_t **edgehash;
699         edgehashentry_t *edgehashentries, *hash;
700         if (!numtriangles)
701                 return;
702         edgehash = Mem_Alloc(tempmempool, TRIANGLEEDGEHASH * sizeof(*edgehash));
703         // if there are too many triangles for the stack array, allocate larger buffer
704         edgehashentries = (edgehashentry_t *)Mem_Alloc(tempmempool, numtriangles * 3 * sizeof(edgehashentry_t));
705         // find neighboring triangles
706         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
707         {
708                 for (j = 0, p = 2;j < 3;p = j, j++)
709                 {
710                         e1 = e[p];
711                         e2 = e[j];
712                         // this hash index works for both forward and backward edges
713                         hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
714                         hash = edgehashentries + i * 3 + j;
715                         hash->next = edgehash[hashindex];
716                         edgehash[hashindex] = hash;
717                         hash->triangle = i;
718                         hash->element[0] = e1;
719                         hash->element[1] = e2;
720                 }
721         }
722         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
723         {
724                 for (j = 0, p = 2;j < 3;p = j, j++)
725                 {
726                         e1 = e[p];
727                         e2 = e[j];
728                         // this hash index works for both forward and backward edges
729                         hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
730                         count = 0;
731                         match = -1;
732                         for (hash = edgehash[hashindex];hash;hash = hash->next)
733                         {
734                                 if (hash->element[0] == e2 && hash->element[1] == e1)
735                                 {
736                                         if (hash->triangle != i)
737                                                 match = hash->triangle;
738                                         count++;
739                                 }
740                                 else if ((hash->element[0] == e1 && hash->element[1] == e2))
741                                         count++;
742                         }
743                         // detect edges shared by three triangles and make them seams
744                         if (count > 2)
745                                 match = -1;
746                         n[p] = match;
747                 }
748
749                 // also send a keepalive here (this can take a while too!)
750                 CL_KeepaliveMessage(false);
751         }
752         // free the allocated buffer
753         Mem_Free(edgehashentries);
754         Mem_Free(edgehash);
755 }
756 #else
757 // very slow but simple way
758 static int Mod_FindTriangleWithEdge(const int *elements, int numtriangles, int start, int end, int ignore)
759 {
760         int i, match, count;
761         count = 0;
762         match = -1;
763         for (i = 0;i < numtriangles;i++, elements += 3)
764         {
765                      if ((elements[0] == start && elements[1] == end)
766                       || (elements[1] == start && elements[2] == end)
767                       || (elements[2] == start && elements[0] == end))
768                 {
769                         if (i != ignore)
770                                 match = i;
771                         count++;
772                 }
773                 else if ((elements[1] == start && elements[0] == end)
774                       || (elements[2] == start && elements[1] == end)
775                       || (elements[0] == start && elements[2] == end))
776                         count++;
777         }
778         // detect edges shared by three triangles and make them seams
779         if (count > 2)
780                 match = -1;
781         return match;
782 }
783
784 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
785 {
786         int i, *n;
787         const int *e;
788         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
789         {
790                 n[0] = Mod_FindTriangleWithEdge(elements, numtriangles, e[1], e[0], i);
791                 n[1] = Mod_FindTriangleWithEdge(elements, numtriangles, e[2], e[1], i);
792                 n[2] = Mod_FindTriangleWithEdge(elements, numtriangles, e[0], e[2], i);
793         }
794 }
795 #endif
796
797 void Mod_ValidateElements(int *elements, int numtriangles, int firstvertex, int numverts, const char *filename, int fileline)
798 {
799         int i, warned = false, endvertex = firstvertex + numverts;
800         for (i = 0;i < numtriangles * 3;i++)
801         {
802                 if (elements[i] < firstvertex || elements[i] >= endvertex)
803                 {
804                         if (!warned)
805                         {
806                                 warned = true;
807                                 Con_Printf("Mod_ValidateElements: out of bounds elements detected at %s:%d\n", filename, fileline);
808                         }
809                         elements[i] = firstvertex;
810                 }
811         }
812 }
813
814 // warning: this is an expensive function!
815 void Mod_BuildNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const int *elements, float *normal3f, qboolean areaweighting)
816 {
817         int i, j;
818         const int *element;
819         float *vectorNormal;
820         float areaNormal[3];
821         // clear the vectors
822         memset(normal3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
823         // process each vertex of each triangle and accumulate the results
824         // use area-averaging, to make triangles with a big area have a bigger
825         // weighting on the vertex normal than triangles with a small area
826         // to do so, just add the 'normals' together (the bigger the area
827         // the greater the length of the normal is
828         element = elements;
829         for (i = 0; i < numtriangles; i++, element += 3)
830         {
831                 TriangleNormal(
832                         vertex3f + element[0] * 3,
833                         vertex3f + element[1] * 3,
834                         vertex3f + element[2] * 3,
835                         areaNormal
836                         );
837
838                 if (!areaweighting)
839                         VectorNormalize(areaNormal);
840
841                 for (j = 0;j < 3;j++)
842                 {
843                         vectorNormal = normal3f + element[j] * 3;
844                         vectorNormal[0] += areaNormal[0];
845                         vectorNormal[1] += areaNormal[1];
846                         vectorNormal[2] += areaNormal[2];
847                 }
848         }
849         // and just normalize the accumulated vertex normal in the end
850         vectorNormal = normal3f + 3 * firstvertex;
851         for (i = 0; i < numvertices; i++, vectorNormal += 3)
852                 VectorNormalize(vectorNormal);
853 }
854
855 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
899 // warning: this is a very expensive function!
900 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)
901 {
902         int i, tnum;
903         float sdir[3], tdir[3], normal[3], *sv, *tv;
904         const float *v0, *v1, *v2, *tc0, *tc1, *tc2, *n;
905         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
906         const int *e;
907         // clear the vectors
908         memset(svector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
909         memset(tvector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
910         // process each vertex of each triangle and accumulate the results
911         for (tnum = 0, e = elements;tnum < numtriangles;tnum++, e += 3)
912         {
913                 v0 = vertex3f + e[0] * 3;
914                 v1 = vertex3f + e[1] * 3;
915                 v2 = vertex3f + e[2] * 3;
916                 tc0 = texcoord2f + e[0] * 2;
917                 tc1 = texcoord2f + e[1] * 2;
918                 tc2 = texcoord2f + e[2] * 2;
919
920                 // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
921                 // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
922
923                 // calculate the edge directions and surface normal
924                 // 6 multiply, 9 subtract
925                 VectorSubtract(v1, v0, v10);
926                 VectorSubtract(v2, v0, v20);
927                 normal[0] = v20[1] * v10[2] - v20[2] * v10[1];
928                 normal[1] = v20[2] * v10[0] - v20[0] * v10[2];
929                 normal[2] = v20[0] * v10[1] - v20[1] * v10[0];
930
931                 // calculate the tangents
932                 // 12 multiply, 10 subtract
933                 tc10[1] = tc1[1] - tc0[1];
934                 tc20[1] = tc2[1] - tc0[1];
935                 sdir[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
936                 sdir[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
937                 sdir[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
938                 tc10[0] = tc1[0] - tc0[0];
939                 tc20[0] = tc2[0] - tc0[0];
940                 tdir[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
941                 tdir[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
942                 tdir[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
943
944                 // if texture is mapped the wrong way (counterclockwise), the tangents
945                 // have to be flipped, this is detected by calculating a normal from the
946                 // two tangents, and seeing if it is opposite the surface normal
947                 // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
948                 CrossProduct(tdir, sdir, tangentcross);
949                 if (DotProduct(tangentcross, normal) < 0)
950                 {
951                         VectorNegate(sdir, sdir);
952                         VectorNegate(tdir, tdir);
953                 }
954
955                 if (!areaweighting)
956                 {
957                         VectorNormalize(sdir);
958                         VectorNormalize(tdir);
959                 }
960                 for (i = 0;i < 3;i++)
961                 {
962                         VectorAdd(svector3f + e[i]*3, sdir, svector3f + e[i]*3);
963                         VectorAdd(tvector3f + e[i]*3, tdir, tvector3f + e[i]*3);
964                 }
965         }
966         // make the tangents completely perpendicular to the surface normal, and
967         // then normalize them
968         // 16 assignments, 2 divide, 2 sqrt, 2 negates, 14 adds, 24 multiplies
969         for (i = 0, sv = svector3f + 3 * firstvertex, tv = tvector3f + 3 * firstvertex, n = normal3f + 3 * firstvertex;i < numvertices;i++, sv += 3, tv += 3, n += 3)
970         {
971                 f = -DotProduct(sv, n);
972                 VectorMA(sv, f, n, sv);
973                 VectorNormalize(sv);
974                 f = -DotProduct(tv, n);
975                 VectorMA(tv, f, n, tv);
976                 VectorNormalize(tv);
977         }
978 }
979
980 void Mod_AllocSurfMesh(mempool_t *mempool, int numvertices, int numtriangles, qboolean lightmapoffsets, qboolean vertexcolors, qboolean neighbors)
981 {
982         unsigned char *data;
983         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));
984         loadmodel->surfmesh.num_vertices = numvertices;
985         loadmodel->surfmesh.num_triangles = numtriangles;
986         if (loadmodel->surfmesh.num_vertices)
987         {
988                 loadmodel->surfmesh.data_vertex3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
989                 loadmodel->surfmesh.data_svector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
990                 loadmodel->surfmesh.data_tvector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
991                 loadmodel->surfmesh.data_normal3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
992                 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
993                 loadmodel->surfmesh.data_texcoordlightmap2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
994                 if (vertexcolors)
995                         loadmodel->surfmesh.data_lightmapcolor4f = (float *)data, data += sizeof(float[4]) * loadmodel->surfmesh.num_vertices;
996                 if (lightmapoffsets)
997                         loadmodel->surfmesh.data_lightmapoffsets = (int *)data, data += sizeof(int) * loadmodel->surfmesh.num_vertices;
998         }
999         if (loadmodel->surfmesh.num_triangles)
1000         {
1001                 loadmodel->surfmesh.data_element3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
1002                 if (neighbors)
1003                         loadmodel->surfmesh.data_neighbor3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
1004                 if (loadmodel->surfmesh.num_vertices <= 65536)
1005                         loadmodel->surfmesh.data_element3s = (unsigned short *)data, data += sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles;
1006         }
1007 }
1008
1009 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)
1010 {
1011         shadowmesh_t *newmesh;
1012         unsigned char *data;
1013         int size;
1014         size = sizeof(shadowmesh_t);
1015         size += maxverts * sizeof(float[3]);
1016         if (light)
1017                 size += maxverts * sizeof(float[11]);
1018         size += maxtriangles * sizeof(int[3]);
1019         if (maxverts <= 65536)
1020                 size += maxtriangles * sizeof(unsigned short[3]);
1021         if (neighbors)
1022                 size += maxtriangles * sizeof(int[3]);
1023         if (expandable)
1024                 size += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *) + maxverts * sizeof(shadowmeshvertexhash_t);
1025         data = (unsigned char *)Mem_Alloc(mempool, size);
1026         newmesh = (shadowmesh_t *)data;data += sizeof(*newmesh);
1027         newmesh->map_diffuse = map_diffuse;
1028         newmesh->map_specular = map_specular;
1029         newmesh->map_normal = map_normal;
1030         newmesh->maxverts = maxverts;
1031         newmesh->maxtriangles = maxtriangles;
1032         newmesh->numverts = 0;
1033         newmesh->numtriangles = 0;
1034         memset(newmesh->sideoffsets, 0, sizeof(newmesh->sideoffsets));
1035         memset(newmesh->sidetotals, 0, sizeof(newmesh->sidetotals));
1036
1037         newmesh->vertex3f = (float *)data;data += maxverts * sizeof(float[3]);
1038         if (light)
1039         {
1040                 newmesh->svector3f = (float *)data;data += maxverts * sizeof(float[3]);
1041                 newmesh->tvector3f = (float *)data;data += maxverts * sizeof(float[3]);
1042                 newmesh->normal3f = (float *)data;data += maxverts * sizeof(float[3]);
1043                 newmesh->texcoord2f = (float *)data;data += maxverts * sizeof(float[2]);
1044         }
1045         newmesh->element3i = (int *)data;data += maxtriangles * sizeof(int[3]);
1046         if (neighbors)
1047         {
1048                 newmesh->neighbor3i = (int *)data;data += maxtriangles * sizeof(int[3]);
1049         }
1050         if (expandable)
1051         {
1052                 newmesh->vertexhashtable = (shadowmeshvertexhash_t **)data;data += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *);
1053                 newmesh->vertexhashentries = (shadowmeshvertexhash_t *)data;data += maxverts * sizeof(shadowmeshvertexhash_t);
1054         }
1055         if (maxverts <= 65536)
1056                 newmesh->element3s = (unsigned short *)data;data += maxtriangles * sizeof(unsigned short[3]);
1057         return newmesh;
1058 }
1059
1060 shadowmesh_t *Mod_ShadowMesh_ReAlloc(mempool_t *mempool, shadowmesh_t *oldmesh, int light, int neighbors)
1061 {
1062         shadowmesh_t *newmesh;
1063         newmesh = Mod_ShadowMesh_Alloc(mempool, oldmesh->numverts, oldmesh->numtriangles, oldmesh->map_diffuse, oldmesh->map_specular, oldmesh->map_normal, light, neighbors, false);
1064         newmesh->numverts = oldmesh->numverts;
1065         newmesh->numtriangles = oldmesh->numtriangles;
1066         memcpy(newmesh->sideoffsets, oldmesh->sideoffsets, sizeof(oldmesh->sideoffsets));
1067         memcpy(newmesh->sidetotals, oldmesh->sidetotals, sizeof(oldmesh->sidetotals));
1068
1069         memcpy(newmesh->vertex3f, oldmesh->vertex3f, oldmesh->numverts * sizeof(float[3]));
1070         if (newmesh->svector3f && oldmesh->svector3f)
1071         {
1072                 memcpy(newmesh->svector3f, oldmesh->svector3f, oldmesh->numverts * sizeof(float[3]));
1073                 memcpy(newmesh->tvector3f, oldmesh->tvector3f, oldmesh->numverts * sizeof(float[3]));
1074                 memcpy(newmesh->normal3f, oldmesh->normal3f, oldmesh->numverts * sizeof(float[3]));
1075                 memcpy(newmesh->texcoord2f, oldmesh->texcoord2f, oldmesh->numverts * sizeof(float[2]));
1076         }
1077         memcpy(newmesh->element3i, oldmesh->element3i, oldmesh->numtriangles * sizeof(int[3]));
1078         if (newmesh->neighbor3i && oldmesh->neighbor3i)
1079                 memcpy(newmesh->neighbor3i, oldmesh->neighbor3i, oldmesh->numtriangles * sizeof(int[3]));
1080         return newmesh;
1081 }
1082
1083 int Mod_ShadowMesh_AddVertex(shadowmesh_t *mesh, float *vertex14f)
1084 {
1085         int hashindex, vnum;
1086         shadowmeshvertexhash_t *hash;
1087         // this uses prime numbers intentionally
1088         hashindex = (unsigned int) (vertex14f[0] * 2003 + vertex14f[1] * 4001 + vertex14f[2] * 7919) % SHADOWMESHVERTEXHASH;
1089         for (hash = mesh->vertexhashtable[hashindex];hash;hash = hash->next)
1090         {
1091                 vnum = (hash - mesh->vertexhashentries);
1092                 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]))
1093                  && (mesh->svector3f == NULL || (mesh->svector3f[vnum * 3 + 0] == vertex14f[3] && mesh->svector3f[vnum * 3 + 1] == vertex14f[4] && mesh->svector3f[vnum * 3 + 2] == vertex14f[5]))
1094                  && (mesh->tvector3f == NULL || (mesh->tvector3f[vnum * 3 + 0] == vertex14f[6] && mesh->tvector3f[vnum * 3 + 1] == vertex14f[7] && mesh->tvector3f[vnum * 3 + 2] == vertex14f[8]))
1095                  && (mesh->normal3f == NULL || (mesh->normal3f[vnum * 3 + 0] == vertex14f[9] && mesh->normal3f[vnum * 3 + 1] == vertex14f[10] && mesh->normal3f[vnum * 3 + 2] == vertex14f[11]))
1096                  && (mesh->texcoord2f == NULL || (mesh->texcoord2f[vnum * 2 + 0] == vertex14f[12] && mesh->texcoord2f[vnum * 2 + 1] == vertex14f[13])))
1097                         return hash - mesh->vertexhashentries;
1098         }
1099         vnum = mesh->numverts++;
1100         hash = mesh->vertexhashentries + vnum;
1101         hash->next = mesh->vertexhashtable[hashindex];
1102         mesh->vertexhashtable[hashindex] = hash;
1103         if (mesh->vertex3f) {mesh->vertex3f[vnum * 3 + 0] = vertex14f[0];mesh->vertex3f[vnum * 3 + 1] = vertex14f[1];mesh->vertex3f[vnum * 3 + 2] = vertex14f[2];}
1104         if (mesh->svector3f) {mesh->svector3f[vnum * 3 + 0] = vertex14f[3];mesh->svector3f[vnum * 3 + 1] = vertex14f[4];mesh->svector3f[vnum * 3 + 2] = vertex14f[5];}
1105         if (mesh->tvector3f) {mesh->tvector3f[vnum * 3 + 0] = vertex14f[6];mesh->tvector3f[vnum * 3 + 1] = vertex14f[7];mesh->tvector3f[vnum * 3 + 2] = vertex14f[8];}
1106         if (mesh->normal3f) {mesh->normal3f[vnum * 3 + 0] = vertex14f[9];mesh->normal3f[vnum * 3 + 1] = vertex14f[10];mesh->normal3f[vnum * 3 + 2] = vertex14f[11];}
1107         if (mesh->texcoord2f) {mesh->texcoord2f[vnum * 2 + 0] = vertex14f[12];mesh->texcoord2f[vnum * 2 + 1] = vertex14f[13];}
1108         return vnum;
1109 }
1110
1111 void Mod_ShadowMesh_AddTriangle(mempool_t *mempool, shadowmesh_t *mesh, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, float *vertex14f)
1112 {
1113         if (mesh->numtriangles == 0)
1114         {
1115                 // set the properties on this empty mesh to be more favorable...
1116                 // (note: this case only occurs for the first triangle added to a new mesh chain)
1117                 mesh->map_diffuse = map_diffuse;
1118                 mesh->map_specular = map_specular;
1119                 mesh->map_normal = map_normal;
1120         }
1121         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)
1122         {
1123                 if (mesh->next == NULL)
1124                         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);
1125                 mesh = mesh->next;
1126         }
1127         mesh->element3i[mesh->numtriangles * 3 + 0] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 0);
1128         mesh->element3i[mesh->numtriangles * 3 + 1] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 1);
1129         mesh->element3i[mesh->numtriangles * 3 + 2] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 2);
1130         mesh->numtriangles++;
1131 }
1132
1133 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)
1134 {
1135         int i, j, e;
1136         float vbuf[3*14], *v;
1137         memset(vbuf, 0, sizeof(vbuf));
1138         for (i = 0;i < numtris;i++)
1139         {
1140                 for (j = 0, v = vbuf;j < 3;j++, v += 14)
1141                 {
1142                         e = *element3i++;
1143                         if (vertex3f)
1144                         {
1145                                 v[0] = vertex3f[e * 3 + 0];
1146                                 v[1] = vertex3f[e * 3 + 1];
1147                                 v[2] = vertex3f[e * 3 + 2];
1148                         }
1149                         if (svector3f)
1150                         {
1151                                 v[3] = svector3f[e * 3 + 0];
1152                                 v[4] = svector3f[e * 3 + 1];
1153                                 v[5] = svector3f[e * 3 + 2];
1154                         }
1155                         if (tvector3f)
1156                         {
1157                                 v[6] = tvector3f[e * 3 + 0];
1158                                 v[7] = tvector3f[e * 3 + 1];
1159                                 v[8] = tvector3f[e * 3 + 2];
1160                         }
1161                         if (normal3f)
1162                         {
1163                                 v[9] = normal3f[e * 3 + 0];
1164                                 v[10] = normal3f[e * 3 + 1];
1165                                 v[11] = normal3f[e * 3 + 2];
1166                         }
1167                         if (texcoord2f)
1168                         {
1169                                 v[12] = texcoord2f[e * 2 + 0];
1170                                 v[13] = texcoord2f[e * 2 + 1];
1171                         }
1172                 }
1173                 Mod_ShadowMesh_AddTriangle(mempool, mesh, map_diffuse, map_specular, map_normal, vbuf);
1174         }
1175
1176         // the triangle calculation can take a while, so let's do a keepalive here
1177         CL_KeepaliveMessage(false);
1178 }
1179
1180 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)
1181 {
1182         // the preparation before shadow mesh initialization can take a while, so let's do a keepalive here
1183         CL_KeepaliveMessage(false);
1184
1185         return Mod_ShadowMesh_Alloc(mempool, maxverts, maxtriangles, map_diffuse, map_specular, map_normal, light, neighbors, expandable);
1186 }
1187
1188 static void Mod_ShadowMesh_CreateVBOs(shadowmesh_t *mesh)
1189 {
1190         if (!mesh->numverts)
1191                 return;
1192
1193         // build r_vertexmesh_t array
1194         // (compressed interleaved array for faster rendering)
1195         if (!mesh->vertexmesh && mesh->texcoord2f)
1196         {
1197                 int vertexindex;
1198                 int numvertices = mesh->numverts;
1199                 r_vertexmesh_t *vertexmesh;
1200                 mesh->vertexmesh = vertexmesh = (r_vertexmesh_t*)Mem_Alloc(loadmodel->mempool, numvertices * sizeof(*mesh->vertexmesh));
1201                 for (vertexindex = 0;vertexindex < numvertices;vertexindex++, vertexmesh++)
1202                 {
1203                         VectorCopy(mesh->vertex3f + 3*vertexindex, vertexmesh->vertex3f);
1204                         VectorScale(mesh->svector3f + 3*vertexindex, 1.0f, vertexmesh->svector3f);
1205                         VectorScale(mesh->tvector3f + 3*vertexindex, 1.0f, vertexmesh->tvector3f);
1206                         VectorScale(mesh->normal3f + 3*vertexindex, 1.0f, vertexmesh->normal3f);
1207                         Vector2Copy(mesh->texcoord2f + 2*vertexindex, vertexmesh->texcoordtexture2f);
1208                 }
1209         }
1210
1211         // build r_vertexposition_t array
1212         if (!mesh->vertexposition)
1213         {
1214                 int vertexindex;
1215                 int numvertices = mesh->numverts;
1216                 r_vertexposition_t *vertexposition;
1217                 mesh->vertexposition = vertexposition = (r_vertexposition_t*)Mem_Alloc(loadmodel->mempool, numvertices * sizeof(*mesh->vertexposition));
1218                 for (vertexindex = 0;vertexindex < numvertices;vertexindex++, vertexposition++)
1219                         VectorCopy(mesh->vertex3f + 3*vertexindex, vertexposition->vertex3f);
1220         }
1221
1222         // upload r_vertexmesh_t array as a buffer
1223         if (mesh->vertexmesh && !mesh->vertexmeshbuffer)
1224                 mesh->vertexmeshbuffer = R_Mesh_CreateMeshBuffer(mesh->vertexmesh, mesh->numverts * sizeof(*mesh->vertexmesh), loadmodel->name, false, false);
1225
1226         // upload r_vertexposition_t array as a buffer
1227         if (mesh->vertexposition && !mesh->vertexpositionbuffer)
1228                 mesh->vertexpositionbuffer = R_Mesh_CreateMeshBuffer(mesh->vertexposition, mesh->numverts * sizeof(*mesh->vertexposition), loadmodel->name, false, false);
1229
1230         // upload short indices as a buffer
1231         if (mesh->element3s && !mesh->element3s_indexbuffer)
1232                 mesh->element3s_indexbuffer = R_Mesh_CreateMeshBuffer(mesh->element3s, mesh->numtriangles * sizeof(short[3]), loadmodel->name, true, false);
1233
1234         // upload int indices as a buffer
1235         if (mesh->element3i && !mesh->element3i_indexbuffer && !mesh->element3s)
1236                 mesh->element3i_indexbuffer = R_Mesh_CreateMeshBuffer(mesh->element3i, mesh->numtriangles * sizeof(int[3]), loadmodel->name, true, false);
1237
1238         // vertex buffer is several arrays and we put them in the same buffer
1239         //
1240         // is this wise?  the texcoordtexture2f array is used with dynamic
1241         // vertex/svector/tvector/normal when rendering animated models, on the
1242         // other hand animated models don't use a lot of vertices anyway...
1243         if (!mesh->vbo_vertexbuffer)
1244         {
1245                 size_t size;
1246                 unsigned char *mem;
1247                 size = 0;
1248                 mesh->vbooffset_vertex3f           = size;if (mesh->vertex3f          ) size += mesh->numverts * sizeof(float[3]);
1249                 mesh->vbooffset_svector3f          = size;if (mesh->svector3f         ) size += mesh->numverts * sizeof(float[3]);
1250                 mesh->vbooffset_tvector3f          = size;if (mesh->tvector3f         ) size += mesh->numverts * sizeof(float[3]);
1251                 mesh->vbooffset_normal3f           = size;if (mesh->normal3f          ) size += mesh->numverts * sizeof(float[3]);
1252                 mesh->vbooffset_texcoord2f         = size;if (mesh->texcoord2f        ) size += mesh->numverts * sizeof(float[2]);
1253                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
1254                 if (mesh->vertex3f          ) memcpy(mem + mesh->vbooffset_vertex3f          , mesh->vertex3f          , mesh->numverts * sizeof(float[3]));
1255                 if (mesh->svector3f         ) memcpy(mem + mesh->vbooffset_svector3f         , mesh->svector3f         , mesh->numverts * sizeof(float[3]));
1256                 if (mesh->tvector3f         ) memcpy(mem + mesh->vbooffset_tvector3f         , mesh->tvector3f         , mesh->numverts * sizeof(float[3]));
1257                 if (mesh->normal3f          ) memcpy(mem + mesh->vbooffset_normal3f          , mesh->normal3f          , mesh->numverts * sizeof(float[3]));
1258                 if (mesh->texcoord2f        ) memcpy(mem + mesh->vbooffset_texcoord2f        , mesh->texcoord2f        , mesh->numverts * sizeof(float[2]));
1259                 mesh->vbo_vertexbuffer = R_Mesh_CreateMeshBuffer(mem, size, "shadowmesh", false, false);
1260                 Mem_Free(mem);
1261         }
1262 }
1263
1264 shadowmesh_t *Mod_ShadowMesh_Finish(mempool_t *mempool, shadowmesh_t *firstmesh, qboolean light, qboolean neighbors, qboolean createvbo)
1265 {
1266         shadowmesh_t *mesh, *newmesh, *nextmesh;
1267         // reallocate meshs to conserve space
1268         for (mesh = firstmesh, firstmesh = NULL;mesh;mesh = nextmesh)
1269         {
1270                 nextmesh = mesh->next;
1271                 if (mesh->numverts >= 3 && mesh->numtriangles >= 1)
1272                 {
1273                         newmesh = Mod_ShadowMesh_ReAlloc(mempool, mesh, light, neighbors);
1274                         newmesh->next = firstmesh;
1275                         firstmesh = newmesh;
1276                         if (newmesh->element3s)
1277                         {
1278                                 int i;
1279                                 for (i = 0;i < newmesh->numtriangles*3;i++)
1280                                         newmesh->element3s[i] = newmesh->element3i[i];
1281                         }
1282                         if (createvbo)
1283                                 Mod_ShadowMesh_CreateVBOs(newmesh);
1284                 }
1285                 Mem_Free(mesh);
1286         }
1287
1288         // this can take a while, so let's do a keepalive here
1289         CL_KeepaliveMessage(false);
1290
1291         return firstmesh;
1292 }
1293
1294 void Mod_ShadowMesh_CalcBBox(shadowmesh_t *firstmesh, vec3_t mins, vec3_t maxs, vec3_t center, float *radius)
1295 {
1296         int i;
1297         shadowmesh_t *mesh;
1298         vec3_t nmins, nmaxs, ncenter, temp;
1299         float nradius2, dist2, *v;
1300         VectorClear(nmins);
1301         VectorClear(nmaxs);
1302         // calculate bbox
1303         for (mesh = firstmesh;mesh;mesh = mesh->next)
1304         {
1305                 if (mesh == firstmesh)
1306                 {
1307                         VectorCopy(mesh->vertex3f, nmins);
1308                         VectorCopy(mesh->vertex3f, nmaxs);
1309                 }
1310                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1311                 {
1312                         if (nmins[0] > v[0]) nmins[0] = v[0];if (nmaxs[0] < v[0]) nmaxs[0] = v[0];
1313                         if (nmins[1] > v[1]) nmins[1] = v[1];if (nmaxs[1] < v[1]) nmaxs[1] = v[1];
1314                         if (nmins[2] > v[2]) nmins[2] = v[2];if (nmaxs[2] < v[2]) nmaxs[2] = v[2];
1315                 }
1316         }
1317         // calculate center and radius
1318         ncenter[0] = (nmins[0] + nmaxs[0]) * 0.5f;
1319         ncenter[1] = (nmins[1] + nmaxs[1]) * 0.5f;
1320         ncenter[2] = (nmins[2] + nmaxs[2]) * 0.5f;
1321         nradius2 = 0;
1322         for (mesh = firstmesh;mesh;mesh = mesh->next)
1323         {
1324                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1325                 {
1326                         VectorSubtract(v, ncenter, temp);
1327                         dist2 = DotProduct(temp, temp);
1328                         if (nradius2 < dist2)
1329                                 nradius2 = dist2;
1330                 }
1331         }
1332         // return data
1333         if (mins)
1334                 VectorCopy(nmins, mins);
1335         if (maxs)
1336                 VectorCopy(nmaxs, maxs);
1337         if (center)
1338                 VectorCopy(ncenter, center);
1339         if (radius)
1340                 *radius = sqrt(nradius2);
1341 }
1342
1343 void Mod_ShadowMesh_Free(shadowmesh_t *mesh)
1344 {
1345         shadowmesh_t *nextmesh;
1346         for (;mesh;mesh = nextmesh)
1347         {
1348                 if (mesh->vertexpositionbuffer)
1349                         R_Mesh_DestroyMeshBuffer(mesh->vertexpositionbuffer);
1350                 if (mesh->vertexmeshbuffer)
1351                         R_Mesh_DestroyMeshBuffer(mesh->vertexmeshbuffer);
1352                 if (mesh->element3i_indexbuffer)
1353                         R_Mesh_DestroyMeshBuffer(mesh->element3i_indexbuffer);
1354                 if (mesh->element3s_indexbuffer)
1355                         R_Mesh_DestroyMeshBuffer(mesh->element3s_indexbuffer);
1356                 if (mesh->vbo_vertexbuffer)
1357                         R_Mesh_DestroyMeshBuffer(mesh->vbo_vertexbuffer);
1358                 nextmesh = mesh->next;
1359                 Mem_Free(mesh);
1360         }
1361 }
1362
1363 void Mod_CreateCollisionMesh(dp_model_t *mod)
1364 {
1365         int k;
1366         int numcollisionmeshtriangles;
1367         const msurface_t *surface;
1368         mempool_t *mempool = mod->mempool;
1369         if (!mempool && mod->brush.parentmodel)
1370                 mempool = mod->brush.parentmodel->mempool;
1371         // make a single combined collision mesh for physics engine use
1372         // TODO rewrite this to use the collision brushes as source, to fix issues with e.g. common/caulk which creates no drawsurface
1373         numcollisionmeshtriangles = 0;
1374         for (k = 0;k < mod->nummodelsurfaces;k++)
1375         {
1376                 surface = mod->data_surfaces + mod->firstmodelsurface + k;
1377                 if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1378                         continue;
1379                 numcollisionmeshtriangles += surface->num_triangles;
1380         }
1381         mod->brush.collisionmesh = Mod_ShadowMesh_Begin(mempool, numcollisionmeshtriangles * 3, numcollisionmeshtriangles, NULL, NULL, NULL, false, false, true);
1382         for (k = 0;k < mod->nummodelsurfaces;k++)
1383         {
1384                 surface = mod->data_surfaces + mod->firstmodelsurface + k;
1385                 if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1386                         continue;
1387                 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));
1388         }
1389         mod->brush.collisionmesh = Mod_ShadowMesh_Finish(mempool, mod->brush.collisionmesh, false, true, false);
1390 }
1391
1392 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)
1393 {
1394         float v[3], tc[3];
1395         v[0] = ix;
1396         v[1] = iy;
1397         if (ix >= 0 && iy >= 0 && ix < imagewidth && iy < imageheight)
1398                 v[2] = (imagepixels[((iy*imagewidth)+ix)*4+0] + imagepixels[((iy*imagewidth)+ix)*4+1] + imagepixels[((iy*imagewidth)+ix)*4+2]) * (1.0f / 765.0f);
1399         else
1400                 v[2] = 0;
1401         Matrix4x4_Transform(pixelstepmatrix, v, vertex3f);
1402         Matrix4x4_Transform(pixeltexturestepmatrix, v, tc);
1403         texcoord2f[0] = tc[0];
1404         texcoord2f[1] = tc[1];
1405 }
1406
1407 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)
1408 {
1409         float vup[3], vdown[3], vleft[3], vright[3];
1410         float tcup[3], tcdown[3], tcleft[3], tcright[3];
1411         float sv[3], tv[3], nl[3];
1412         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, pixelstepmatrix, pixeltexturestepmatrix);
1413         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy - 1, vup, tcup, pixelstepmatrix, pixeltexturestepmatrix);
1414         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy + 1, vdown, tcdown, pixelstepmatrix, pixeltexturestepmatrix);
1415         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix - 1, iy, vleft, tcleft, pixelstepmatrix, pixeltexturestepmatrix);
1416         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix + 1, iy, vright, tcright, pixelstepmatrix, pixeltexturestepmatrix);
1417         Mod_BuildBumpVectors(vertex3f, vup, vright, texcoord2f, tcup, tcright, svector3f, tvector3f, normal3f);
1418         Mod_BuildBumpVectors(vertex3f, vright, vdown, texcoord2f, tcright, tcdown, sv, tv, nl);
1419         VectorAdd(svector3f, sv, svector3f);
1420         VectorAdd(tvector3f, tv, tvector3f);
1421         VectorAdd(normal3f, nl, normal3f);
1422         Mod_BuildBumpVectors(vertex3f, vdown, vleft, texcoord2f, tcdown, tcleft, sv, tv, nl);
1423         VectorAdd(svector3f, sv, svector3f);
1424         VectorAdd(tvector3f, tv, tvector3f);
1425         VectorAdd(normal3f, nl, normal3f);
1426         Mod_BuildBumpVectors(vertex3f, vleft, vup, texcoord2f, tcleft, tcup, sv, tv, nl);
1427         VectorAdd(svector3f, sv, svector3f);
1428         VectorAdd(tvector3f, tv, tvector3f);
1429         VectorAdd(normal3f, nl, normal3f);
1430 }
1431
1432 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)
1433 {
1434         int x, y, ix, iy, *e;
1435         e = element3i;
1436         for (y = 0;y < height;y++)
1437         {
1438                 for (x = 0;x < width;x++)
1439                 {
1440                         e[0] = (y + 1) * (width + 1) + (x + 0);
1441                         e[1] = (y + 0) * (width + 1) + (x + 0);
1442                         e[2] = (y + 1) * (width + 1) + (x + 1);
1443                         e[3] = (y + 0) * (width + 1) + (x + 0);
1444                         e[4] = (y + 0) * (width + 1) + (x + 1);
1445                         e[5] = (y + 1) * (width + 1) + (x + 1);
1446                         e += 6;
1447                 }
1448         }
1449         Mod_BuildTriangleNeighbors(neighbor3i, element3i, width*height*2);
1450         for (y = 0, iy = y1;y < height + 1;y++, iy++)
1451                 for (x = 0, ix = x1;x < width + 1;x++, ix++, vertex3f += 3, texcoord2f += 2, svector3f += 3, tvector3f += 3, normal3f += 3)
1452                         Mod_GetTerrainVertexFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, svector3f, tvector3f, normal3f, pixelstepmatrix, pixeltexturestepmatrix);
1453 }
1454
1455 #if 0
1456 void Mod_Terrain_SurfaceRecurseChunk(dp_model_t *model, int stepsize, int x, int y)
1457 {
1458         float mins[3];
1459         float maxs[3];
1460         float chunkwidth = min(stepsize, model->terrain.width - 1 - x);
1461         float chunkheight = min(stepsize, model->terrain.height - 1 - y);
1462         float viewvector[3];
1463         unsigned int firstvertex;
1464         unsigned int *e;
1465         float *v;
1466         if (chunkwidth < 2 || chunkheight < 2)
1467                 return;
1468         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]);
1469         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]);
1470         viewvector[0] = bound(mins[0], localvieworigin, maxs[0]) - model->terrain.vieworigin[0];
1471         viewvector[1] = bound(mins[1], localvieworigin, maxs[1]) - model->terrain.vieworigin[1];
1472         viewvector[2] = bound(mins[2], localvieworigin, maxs[2]) - model->terrain.vieworigin[2];
1473         if (stepsize > 1 && VectorLength(viewvector) < stepsize*model->terrain.scale[0]*r_terrain_lodscale.value)
1474         {
1475                 // too close for this stepsize, emit as 4 chunks instead
1476                 stepsize /= 2;
1477                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y);
1478                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y);
1479                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y+stepsize);
1480                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y+stepsize);
1481                 return;
1482         }
1483         // emit the geometry at stepsize into our vertex buffer / index buffer
1484         // we add two columns and two rows for skirt
1485         outwidth = chunkwidth+2;
1486         outheight = chunkheight+2;
1487         outwidth2 = outwidth-1;
1488         outheight2 = outheight-1;
1489         outwidth3 = outwidth+1;
1490         outheight3 = outheight+1;
1491         firstvertex = numvertices;
1492         e = model->terrain.element3i + numtriangles;
1493         numtriangles += chunkwidth*chunkheight*2+chunkwidth*2*2+chunkheight*2*2;
1494         v = model->terrain.vertex3f + numvertices;
1495         numvertices += (chunkwidth+1)*(chunkheight+1)+(chunkwidth+1)*2+(chunkheight+1)*2;
1496         // emit the triangles (note: the skirt is treated as two extra rows and two extra columns)
1497         for (ty = 0;ty < outheight;ty++)
1498         {
1499                 for (tx = 0;tx < outwidth;tx++)
1500                 {
1501                         *e++ = firstvertex + (ty  )*outwidth3+(tx  );
1502                         *e++ = firstvertex + (ty  )*outwidth3+(tx+1);
1503                         *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1504                         *e++ = firstvertex + (ty  )*outwidth3+(tx  );
1505                         *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1506                         *e++ = firstvertex + (ty+1)*outwidth3+(tx  );
1507                 }
1508         }
1509         // TODO: emit surface vertices (x+tx*stepsize, y+ty*stepsize)
1510         for (ty = 0;ty <= outheight;ty++)
1511         {
1512                 skirtrow = ty == 0 || ty == outheight;
1513                 ry = y+bound(1, ty, outheight)*stepsize;
1514                 for (tx = 0;tx <= outwidth;tx++)
1515                 {
1516                         skirt = skirtrow || tx == 0 || tx == outwidth;
1517                         rx = x+bound(1, tx, outwidth)*stepsize;
1518                         v[0] = rx*scale[0];
1519                         v[1] = ry*scale[1];
1520                         v[2] = heightmap[ry*terrainwidth+rx]*scale[2];
1521                         v += 3;
1522                 }
1523         }
1524         // TODO: emit skirt vertices
1525 }
1526
1527 void Mod_Terrain_UpdateSurfacesForViewOrigin(dp_model_t *model)
1528 {
1529         for (y = 0;y < model->terrain.size[1];y += model->terrain.
1530         Mod_Terrain_SurfaceRecurseChunk(model, model->terrain.maxstepsize, x, y);
1531         Mod_Terrain_BuildChunk(model, 
1532 }
1533 #endif
1534
1535 q3wavefunc_t Mod_LoadQ3Shaders_EnumerateWaveFunc(const char *s)
1536 {
1537         if (!strcasecmp(s, "sin"))             return Q3WAVEFUNC_SIN;
1538         if (!strcasecmp(s, "square"))          return Q3WAVEFUNC_SQUARE;
1539         if (!strcasecmp(s, "triangle"))        return Q3WAVEFUNC_TRIANGLE;
1540         if (!strcasecmp(s, "sawtooth"))        return Q3WAVEFUNC_SAWTOOTH;
1541         if (!strcasecmp(s, "inversesawtooth")) return Q3WAVEFUNC_INVERSESAWTOOTH;
1542         if (!strcasecmp(s, "noise"))           return Q3WAVEFUNC_NOISE;
1543         Con_DPrintf("Mod_LoadQ3Shaders: unknown wavefunc %s\n", s);
1544         return Q3WAVEFUNC_NONE;
1545 }
1546
1547 void Mod_FreeQ3Shaders(void)
1548 {
1549         Mem_FreePool(&q3shaders_mem);
1550 }
1551
1552 static void Q3Shader_AddToHash (q3shaderinfo_t* shader)
1553 {
1554         unsigned short hash = CRC_Block_CaseInsensitive ((const unsigned char *)shader->name, strlen (shader->name));
1555         q3shader_hash_entry_t* entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
1556         q3shader_hash_entry_t* lastEntry = NULL;
1557         while (entry != NULL)
1558         {
1559                 if (strcasecmp (entry->shader.name, shader->name) == 0)
1560                 {
1561                         unsigned char *start, *end, *start2;
1562                         start = (unsigned char *) (&shader->Q3SHADERINFO_COMPARE_START);
1563                         end = ((unsigned char *) (&shader->Q3SHADERINFO_COMPARE_END)) + sizeof(shader->Q3SHADERINFO_COMPARE_END);
1564                         start2 = (unsigned char *) (&entry->shader.Q3SHADERINFO_COMPARE_START);
1565                         if(memcmp(start, start2, end - start))
1566                                 Con_DPrintf("Shader '%s' already defined, ignoring mismatching redeclaration\n", shader->name);
1567                         else
1568                                 Con_DPrintf("Shader '%s' already defined\n", shader->name);
1569                         return;
1570                 }
1571                 lastEntry = entry;
1572                 entry = entry->chain;
1573         }
1574         if (entry == NULL)
1575         {
1576                 if (lastEntry->shader.name[0] != 0)
1577                 {
1578                         /* Add to chain */
1579                         q3shader_hash_entry_t* newEntry = (q3shader_hash_entry_t*)
1580                           Mem_ExpandableArray_AllocRecord (&q3shader_data->hash_entries);
1581
1582                         while (lastEntry->chain != NULL) lastEntry = lastEntry->chain;
1583                         lastEntry->chain = newEntry;
1584                         newEntry->chain = NULL;
1585                         lastEntry = newEntry;
1586                 }
1587                 /* else: head of chain, in hash entry array */
1588                 entry = lastEntry;
1589         }
1590         memcpy (&entry->shader, shader, sizeof (q3shaderinfo_t));
1591 }
1592
1593 extern cvar_t mod_q3shader_default_offsetmapping;
1594 void Mod_LoadQ3Shaders(void)
1595 {
1596         int j;
1597         int fileindex;
1598         fssearch_t *search;
1599         char *f;
1600         const char *text;
1601         q3shaderinfo_t shader;
1602         q3shaderinfo_layer_t *layer;
1603         int numparameters;
1604         char parameter[TEXTURE_MAXFRAMES + 4][Q3PATHLENGTH];
1605         char *custsurfaceparmnames[256]; // VorteX: q3map2 has 64 but well, someone will need more
1606         unsigned long custsurfaceparms[256]; 
1607         int numcustsurfaceparms;
1608
1609         Mod_FreeQ3Shaders();
1610
1611         q3shaders_mem = Mem_AllocPool("q3shaders", 0, NULL);
1612         q3shader_data = (q3shader_data_t*)Mem_Alloc (q3shaders_mem,
1613                 sizeof (q3shader_data_t));
1614         Mem_ExpandableArray_NewArray (&q3shader_data->hash_entries,
1615                 q3shaders_mem, sizeof (q3shader_hash_entry_t), 256);
1616         Mem_ExpandableArray_NewArray (&q3shader_data->char_ptrs,
1617                 q3shaders_mem, sizeof (char**), 256);
1618
1619         // parse custinfoparms.txt
1620         numcustsurfaceparms = 0;
1621         if (text = f = (char *)FS_LoadFile("scripts/custinfoparms.txt", tempmempool, false, NULL))
1622         {
1623                 if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1624                         Con_DPrintf("scripts/custinfoparms.txt: contentflags section parsing error - expected \"{\", found \"%s\"\n", com_token);
1625                 else
1626                 {
1627                         while (COM_ParseToken_QuakeC(&text, false))
1628                                 if (!strcasecmp(com_token, "}"))
1629                                         break;
1630                         // custom surfaceflags section
1631                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1632                                 Con_DPrintf("scripts/custinfoparms.txt: surfaceflags section parsing error - expected \"{\", found \"%s\"\n", com_token);
1633                         else
1634                         {
1635                                 while(COM_ParseToken_QuakeC(&text, false))
1636                                 {
1637                                         if (!strcasecmp(com_token, "}"))
1638                                                 break;  
1639                                         // register surfaceflag
1640                                         if (numcustsurfaceparms >= 256)
1641                                         {
1642                                                 Con_Printf("scripts/custinfoparms.txt: surfaceflags section parsing error - max 256 surfaceflags exceeded\n");
1643                                                 break;
1644                                         }
1645                                         // name
1646                                         j = strlen(com_token)+1;
1647                                         custsurfaceparmnames[numcustsurfaceparms] = (char *)Mem_Alloc(tempmempool, j);
1648                                         strlcpy(custsurfaceparmnames[numcustsurfaceparms], com_token, j+1);
1649                                         // value
1650                                         if (COM_ParseToken_QuakeC(&text, false))
1651                                                 custsurfaceparms[numcustsurfaceparms] = strtol(com_token, NULL, 0);
1652                                         else
1653                                                 custsurfaceparms[numcustsurfaceparms] = 0;
1654                                         numcustsurfaceparms++;
1655                                 }
1656                         }
1657                 }
1658                 Mem_Free(f);
1659         }
1660
1661         // parse shaders
1662         search = FS_Search("scripts/*.shader", true, false);
1663         if (!search)
1664                 return;
1665         for (fileindex = 0;fileindex < search->numfilenames;fileindex++)
1666         {
1667                 text = f = (char *)FS_LoadFile(search->filenames[fileindex], tempmempool, false, NULL);
1668                 if (!f)
1669                         continue;
1670                 while (COM_ParseToken_QuakeC(&text, false))
1671                 {
1672                         memset (&shader, 0, sizeof(shader));
1673                         shader.reflectmin = 0;
1674                         shader.reflectmax = 1;
1675                         shader.refractfactor = 1;
1676                         Vector4Set(shader.refractcolor4f, 1, 1, 1, 1);
1677                         shader.reflectfactor = 1;
1678                         Vector4Set(shader.reflectcolor4f, 1, 1, 1, 1);
1679                         shader.r_water_wateralpha = 1;
1680                         shader.offsetmapping = (mod_q3shader_default_offsetmapping.value) ? OFFSETMAPPING_DEFAULT : OFFSETMAPPING_OFF;
1681                         shader.offsetscale = 1;
1682                         shader.specularscalemod = 1;
1683                         shader.specularpowermod = 1;
1684
1685                         strlcpy(shader.name, com_token, sizeof(shader.name));
1686                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1687                         {
1688                                 Con_DPrintf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[fileindex], com_token);
1689                                 break;
1690                         }
1691                         while (COM_ParseToken_QuakeC(&text, false))
1692                         {
1693                                 if (!strcasecmp(com_token, "}"))
1694                                         break;
1695                                 if (!strcasecmp(com_token, "{"))
1696                                 {
1697                                         static q3shaderinfo_layer_t dummy;
1698                                         if (shader.numlayers < Q3SHADER_MAXLAYERS)
1699                                         {
1700                                                 layer = shader.layers + shader.numlayers++;
1701                                         }
1702                                         else
1703                                         {
1704                                                 // parse and process it anyway, just don't store it (so a map $lightmap or such stuff still is found)
1705                                                 memset(&dummy, 0, sizeof(dummy));
1706                                                 layer = &dummy;
1707                                         }
1708                                         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1709                                         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1710                                         layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1711                                         layer->blendfunc[0] = GL_ONE;
1712                                         layer->blendfunc[1] = GL_ZERO;
1713                                         while (COM_ParseToken_QuakeC(&text, false))
1714                                         {
1715                                                 if (!strcasecmp(com_token, "}"))
1716                                                         break;
1717                                                 if (!strcasecmp(com_token, "\n"))
1718                                                         continue;
1719                                                 numparameters = 0;
1720                                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1721                                                 {
1722                                                         if (j < TEXTURE_MAXFRAMES + 4)
1723                                                         {
1724                                                                 // remap dp_water to dpwater, dp_reflect to dpreflect, etc.
1725                                                                 if(j == 0 && !strncasecmp(com_token, "dp_", 3))
1726                                                                         dpsnprintf(parameter[j], sizeof(parameter[j]), "dp%s", &com_token[3]);
1727                                                                 else
1728                                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1729                                                                 numparameters = j + 1;
1730                                                         }
1731                                                         if (!COM_ParseToken_QuakeC(&text, true))
1732                                                                 break;
1733                                                 }
1734                                                 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1735                                                 //      parameter[j][0] = 0;
1736                                                 if (developer_insane.integer)
1737                                                 {
1738                                                         Con_DPrintf("%s %i: ", shader.name, shader.numlayers - 1);
1739                                                         for (j = 0;j < numparameters;j++)
1740                                                                 Con_DPrintf(" %s", parameter[j]);
1741                                                         Con_DPrint("\n");
1742                                                 }
1743                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "blendfunc"))
1744                                                 {
1745                                                         if (numparameters == 2)
1746                                                         {
1747                                                                 if (!strcasecmp(parameter[1], "add"))
1748                                                                 {
1749                                                                         layer->blendfunc[0] = GL_ONE;
1750                                                                         layer->blendfunc[1] = GL_ONE;
1751                                                                 }
1752                                                                 else if (!strcasecmp(parameter[1], "filter"))
1753                                                                 {
1754                                                                         layer->blendfunc[0] = GL_DST_COLOR;
1755                                                                         layer->blendfunc[1] = GL_ZERO;
1756                                                                 }
1757                                                                 else if (!strcasecmp(parameter[1], "blend"))
1758                                                                 {
1759                                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1760                                                                         layer->blendfunc[1] = GL_ONE_MINUS_SRC_ALPHA;
1761                                                                 }
1762                                                         }
1763                                                         else if (numparameters == 3)
1764                                                         {
1765                                                                 int k;
1766                                                                 for (k = 0;k < 2;k++)
1767                                                                 {
1768                                                                         if (!strcasecmp(parameter[k+1], "GL_ONE"))
1769                                                                                 layer->blendfunc[k] = GL_ONE;
1770                                                                         else if (!strcasecmp(parameter[k+1], "GL_ZERO"))
1771                                                                                 layer->blendfunc[k] = GL_ZERO;
1772                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_COLOR"))
1773                                                                                 layer->blendfunc[k] = GL_SRC_COLOR;
1774                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_ALPHA"))
1775                                                                                 layer->blendfunc[k] = GL_SRC_ALPHA;
1776                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_COLOR"))
1777                                                                                 layer->blendfunc[k] = GL_DST_COLOR;
1778                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_ALPHA"))
1779                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1780                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_COLOR"))
1781                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_COLOR;
1782                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_ALPHA"))
1783                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_ALPHA;
1784                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_COLOR"))
1785                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_COLOR;
1786                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_ALPHA"))
1787                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1788                                                                         else
1789                                                                                 layer->blendfunc[k] = GL_ONE; // default in case of parsing error
1790                                                                 }
1791                                                         }
1792                                                 }
1793                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
1794                                                         layer->alphatest = true;
1795                                                 if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
1796                                                 {
1797                                                         if (!strcasecmp(parameter[0], "clampmap"))
1798                                                                 layer->clampmap = true;
1799                                                         layer->numframes = 1;
1800                                                         layer->framerate = 1;
1801                                                         layer->texturename = (char**)Mem_ExpandableArray_AllocRecord (
1802                                                                 &q3shader_data->char_ptrs);
1803                                                         layer->texturename[0] = Mem_strdup (q3shaders_mem, parameter[1]);
1804                                                         if (!strcasecmp(parameter[1], "$lightmap"))
1805                                                                 shader.lighting = true;
1806                                                 }
1807                                                 else if (numparameters >= 3 && (!strcasecmp(parameter[0], "animmap") || !strcasecmp(parameter[0], "animclampmap")))
1808                                                 {
1809                                                         int i;
1810                                                         layer->numframes = min(numparameters - 2, TEXTURE_MAXFRAMES);
1811                                                         layer->framerate = atof(parameter[1]);
1812                                                         layer->texturename = (char **) Mem_Alloc (q3shaders_mem, sizeof (char*) * layer->numframes);
1813                                                         for (i = 0;i < layer->numframes;i++)
1814                                                                 layer->texturename[i] = Mem_strdup (q3shaders_mem, parameter[i + 2]);
1815                                                 }
1816                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "rgbgen"))
1817                                                 {
1818                                                         int i;
1819                                                         for (i = 0;i < numparameters - 2 && i < Q3RGBGEN_MAXPARMS;i++)
1820                                                                 layer->rgbgen.parms[i] = atof(parameter[i+2]);
1821                                                              if (!strcasecmp(parameter[1], "identity"))         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1822                                                         else if (!strcasecmp(parameter[1], "const"))            layer->rgbgen.rgbgen = Q3RGBGEN_CONST;
1823                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->rgbgen.rgbgen = Q3RGBGEN_ENTITY;
1824                                                         else if (!strcasecmp(parameter[1], "exactvertex"))      layer->rgbgen.rgbgen = Q3RGBGEN_EXACTVERTEX;
1825                                                         else if (!strcasecmp(parameter[1], "identitylighting")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITYLIGHTING;
1826                                                         else if (!strcasecmp(parameter[1], "lightingdiffuse"))  layer->rgbgen.rgbgen = Q3RGBGEN_LIGHTINGDIFFUSE;
1827                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSENTITY;
1828                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSVERTEX;
1829                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->rgbgen.rgbgen = Q3RGBGEN_VERTEX;
1830                                                         else if (!strcasecmp(parameter[1], "wave"))
1831                                                         {
1832                                                                 layer->rgbgen.rgbgen = Q3RGBGEN_WAVE;
1833                                                                 layer->rgbgen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1834                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1835                                                                         layer->rgbgen.waveparms[i] = atof(parameter[i+3]);
1836                                                         }
1837                                                         else Con_DPrintf("%s parsing warning: unknown rgbgen %s\n", search->filenames[fileindex], parameter[1]);
1838                                                 }
1839                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphagen"))
1840                                                 {
1841                                                         int i;
1842                                                         for (i = 0;i < numparameters - 2 && i < Q3ALPHAGEN_MAXPARMS;i++)
1843                                                                 layer->alphagen.parms[i] = atof(parameter[i+2]);
1844                                                              if (!strcasecmp(parameter[1], "identity"))         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1845                                                         else if (!strcasecmp(parameter[1], "const"))            layer->alphagen.alphagen = Q3ALPHAGEN_CONST;
1846                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->alphagen.alphagen = Q3ALPHAGEN_ENTITY;
1847                                                         else if (!strcasecmp(parameter[1], "lightingspecular")) layer->alphagen.alphagen = Q3ALPHAGEN_LIGHTINGSPECULAR;
1848                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSENTITY;
1849                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSVERTEX;
1850                                                         else if (!strcasecmp(parameter[1], "portal"))           layer->alphagen.alphagen = Q3ALPHAGEN_PORTAL;
1851                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->alphagen.alphagen = Q3ALPHAGEN_VERTEX;
1852                                                         else if (!strcasecmp(parameter[1], "wave"))
1853                                                         {
1854                                                                 layer->alphagen.alphagen = Q3ALPHAGEN_WAVE;
1855                                                                 layer->alphagen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1856                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1857                                                                         layer->alphagen.waveparms[i] = atof(parameter[i+3]);
1858                                                         }
1859                                                         else Con_DPrintf("%s parsing warning: unknown alphagen %s\n", search->filenames[fileindex], parameter[1]);
1860                                                 }
1861                                                 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "texgen") || !strcasecmp(parameter[0], "tcgen")))
1862                                                 {
1863                                                         int i;
1864                                                         // observed values: tcgen environment
1865                                                         // no other values have been observed in real shaders
1866                                                         for (i = 0;i < numparameters - 2 && i < Q3TCGEN_MAXPARMS;i++)
1867                                                                 layer->tcgen.parms[i] = atof(parameter[i+2]);
1868                                                              if (!strcasecmp(parameter[1], "base"))        layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1869                                                         else if (!strcasecmp(parameter[1], "texture"))     layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1870                                                         else if (!strcasecmp(parameter[1], "environment")) layer->tcgen.tcgen = Q3TCGEN_ENVIRONMENT;
1871                                                         else if (!strcasecmp(parameter[1], "lightmap"))    layer->tcgen.tcgen = Q3TCGEN_LIGHTMAP;
1872                                                         else if (!strcasecmp(parameter[1], "vector"))      layer->tcgen.tcgen = Q3TCGEN_VECTOR;
1873                                                         else Con_DPrintf("%s parsing warning: unknown tcgen mode %s\n", search->filenames[fileindex], parameter[1]);
1874                                                 }
1875                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "tcmod"))
1876                                                 {
1877                                                         int i, tcmodindex;
1878                                                         // observed values:
1879                                                         // tcmod rotate #
1880                                                         // tcmod scale # #
1881                                                         // tcmod scroll # #
1882                                                         // tcmod stretch sin # # # #
1883                                                         // tcmod stretch triangle # # # #
1884                                                         // tcmod transform # # # # # #
1885                                                         // tcmod turb # # # #
1886                                                         // tcmod turb sin # # # #  (this is bogus)
1887                                                         // no other values have been observed in real shaders
1888                                                         for (tcmodindex = 0;tcmodindex < Q3MAXTCMODS;tcmodindex++)
1889                                                                 if (!layer->tcmods[tcmodindex].tcmod)
1890                                                                         break;
1891                                                         if (tcmodindex < Q3MAXTCMODS)
1892                                                         {
1893                                                                 for (i = 0;i < numparameters - 2 && i < Q3TCMOD_MAXPARMS;i++)
1894                                                                         layer->tcmods[tcmodindex].parms[i] = atof(parameter[i+2]);
1895                                                                          if (!strcasecmp(parameter[1], "entitytranslate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ENTITYTRANSLATE;
1896                                                                 else if (!strcasecmp(parameter[1], "rotate"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ROTATE;
1897                                                                 else if (!strcasecmp(parameter[1], "scale"))           layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCALE;
1898                                                                 else if (!strcasecmp(parameter[1], "scroll"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCROLL;
1899                                                                 else if (!strcasecmp(parameter[1], "page"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_PAGE;
1900                                                                 else if (!strcasecmp(parameter[1], "stretch"))
1901                                                                 {
1902                                                                         layer->tcmods[tcmodindex].tcmod = Q3TCMOD_STRETCH;
1903                                                                         layer->tcmods[tcmodindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1904                                                                         for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1905                                                                                 layer->tcmods[tcmodindex].waveparms[i] = atof(parameter[i+3]);
1906                                                                 }
1907                                                                 else if (!strcasecmp(parameter[1], "transform"))       layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TRANSFORM;
1908                                                                 else if (!strcasecmp(parameter[1], "turb"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TURBULENT;
1909                                                                 else Con_DPrintf("%s parsing warning: unknown tcmod mode %s\n", search->filenames[fileindex], parameter[1]);
1910                                                         }
1911                                                         else
1912                                                                 Con_DPrintf("%s parsing warning: too many tcmods on one layer\n", search->filenames[fileindex]);
1913                                                 }
1914                                                 // break out a level if it was a closing brace (not using the character here to not confuse vim)
1915                                                 if (!strcasecmp(com_token, "}"))
1916                                                         break;
1917                                         }
1918                                         if (layer->rgbgen.rgbgen == Q3RGBGEN_LIGHTINGDIFFUSE || layer->rgbgen.rgbgen == Q3RGBGEN_VERTEX)
1919                                                 shader.lighting = true;
1920                                         if (layer->alphagen.alphagen == Q3ALPHAGEN_VERTEX)
1921                                         {
1922                                                 if (layer == shader.layers + 0)
1923                                                 {
1924                                                         // vertex controlled transparency
1925                                                         shader.vertexalpha = true;
1926                                                 }
1927                                                 else
1928                                                 {
1929                                                         // multilayer terrain shader or similar
1930                                                         shader.textureblendalpha = true;
1931                                                 }
1932                                         }
1933                                         layer->texflags = TEXF_ALPHA;
1934                                         if (!(shader.surfaceparms & Q3SURFACEPARM_NOMIPMAPS))
1935                                                 layer->texflags |= TEXF_MIPMAP;
1936                                         if (!(shader.textureflags & Q3TEXTUREFLAG_NOPICMIP))
1937                                                 layer->texflags |= TEXF_PICMIP | TEXF_COMPRESS;
1938                                         if (layer->clampmap)
1939                                                 layer->texflags |= TEXF_CLAMP;
1940                                         continue;
1941                                 }
1942                                 numparameters = 0;
1943                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1944                                 {
1945                                         if (j < TEXTURE_MAXFRAMES + 4)
1946                                         {
1947                                                 // remap dp_water to dpwater, dp_reflect to dpreflect, etc.
1948                                                 if(j == 0 && !strncasecmp(com_token, "dp_", 3))
1949                                                         dpsnprintf(parameter[j], sizeof(parameter[j]), "dp%s", &com_token[3]);
1950                                                 else
1951                                                         strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1952                                                 numparameters = j + 1;
1953                                         }
1954                                         if (!COM_ParseToken_QuakeC(&text, true))
1955                                                 break;
1956                                 }
1957                                 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1958                                 //      parameter[j][0] = 0;
1959                                 if (fileindex == 0 && !strcasecmp(com_token, "}"))
1960                                         break;
1961                                 if (developer_insane.integer)
1962                                 {
1963                                         Con_DPrintf("%s: ", shader.name);
1964                                         for (j = 0;j < numparameters;j++)
1965                                                 Con_DPrintf(" %s", parameter[j]);
1966                                         Con_DPrint("\n");
1967                                 }
1968                                 if (numparameters < 1)
1969                                         continue;
1970                                 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
1971                                 {
1972                                         if (!strcasecmp(parameter[1], "alphashadow"))
1973                                                 shader.surfaceparms |= Q3SURFACEPARM_ALPHASHADOW;
1974                                         else if (!strcasecmp(parameter[1], "areaportal"))
1975                                                 shader.surfaceparms |= Q3SURFACEPARM_AREAPORTAL;
1976                                         else if (!strcasecmp(parameter[1], "botclip"))
1977                                                 shader.surfaceparms |= Q3SURFACEPARM_BOTCLIP;
1978                                         else if (!strcasecmp(parameter[1], "clusterportal"))
1979                                                 shader.surfaceparms |= Q3SURFACEPARM_CLUSTERPORTAL;
1980                                         else if (!strcasecmp(parameter[1], "detail"))
1981                                                 shader.surfaceparms |= Q3SURFACEPARM_DETAIL;
1982                                         else if (!strcasecmp(parameter[1], "donotenter"))
1983                                                 shader.surfaceparms |= Q3SURFACEPARM_DONOTENTER;
1984                                         else if (!strcasecmp(parameter[1], "dust"))
1985                                                 shader.surfaceparms |= Q3SURFACEPARM_DUST;
1986                                         else if (!strcasecmp(parameter[1], "hint"))
1987                                                 shader.surfaceparms |= Q3SURFACEPARM_HINT;
1988                                         else if (!strcasecmp(parameter[1], "fog"))
1989                                                 shader.surfaceparms |= Q3SURFACEPARM_FOG;
1990                                         else if (!strcasecmp(parameter[1], "lava"))
1991                                                 shader.surfaceparms |= Q3SURFACEPARM_LAVA;
1992                                         else if (!strcasecmp(parameter[1], "lightfilter"))
1993                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTFILTER;
1994                                         else if (!strcasecmp(parameter[1], "lightgrid"))
1995                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTGRID;
1996                                         else if (!strcasecmp(parameter[1], "metalsteps"))
1997                                                 shader.surfaceparms |= Q3SURFACEPARM_METALSTEPS;
1998                                         else if (!strcasecmp(parameter[1], "nodamage"))
1999                                                 shader.surfaceparms |= Q3SURFACEPARM_NODAMAGE;
2000                                         else if (!strcasecmp(parameter[1], "nodlight"))
2001                                                 shader.surfaceparms |= Q3SURFACEPARM_NODLIGHT;
2002                                         else if (!strcasecmp(parameter[1], "nodraw"))
2003                                                 shader.surfaceparms |= Q3SURFACEPARM_NODRAW;
2004                                         else if (!strcasecmp(parameter[1], "nodrop"))
2005                                                 shader.surfaceparms |= Q3SURFACEPARM_NODROP;
2006                                         else if (!strcasecmp(parameter[1], "noimpact"))
2007                                                 shader.surfaceparms |= Q3SURFACEPARM_NOIMPACT;
2008                                         else if (!strcasecmp(parameter[1], "nolightmap"))
2009                                                 shader.surfaceparms |= Q3SURFACEPARM_NOLIGHTMAP;
2010                                         else if (!strcasecmp(parameter[1], "nomarks"))
2011                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMARKS;
2012                                         else if (!strcasecmp(parameter[1], "nomipmaps"))
2013                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
2014                                         else if (!strcasecmp(parameter[1], "nonsolid"))
2015                                                 shader.surfaceparms |= Q3SURFACEPARM_NONSOLID;
2016                                         else if (!strcasecmp(parameter[1], "origin"))
2017                                                 shader.surfaceparms |= Q3SURFACEPARM_ORIGIN;
2018                                         else if (!strcasecmp(parameter[1], "playerclip"))
2019                                                 shader.surfaceparms |= Q3SURFACEPARM_PLAYERCLIP;
2020                                         else if (!strcasecmp(parameter[1], "sky"))
2021                                                 shader.surfaceparms |= Q3SURFACEPARM_SKY;
2022                                         else if (!strcasecmp(parameter[1], "slick"))
2023                                                 shader.surfaceparms |= Q3SURFACEPARM_SLICK;
2024                                         else if (!strcasecmp(parameter[1], "slime"))
2025                                                 shader.surfaceparms |= Q3SURFACEPARM_SLIME;
2026                                         else if (!strcasecmp(parameter[1], "structural"))
2027                                                 shader.surfaceparms |= Q3SURFACEPARM_STRUCTURAL;
2028                                         else if (!strcasecmp(parameter[1], "trans"))
2029                                                 shader.surfaceparms |= Q3SURFACEPARM_TRANS;
2030                                         else if (!strcasecmp(parameter[1], "water"))
2031                                                 shader.surfaceparms |= Q3SURFACEPARM_WATER;
2032                                         else if (!strcasecmp(parameter[1], "pointlight"))
2033                                                 shader.surfaceparms |= Q3SURFACEPARM_POINTLIGHT;
2034                                         else if (!strcasecmp(parameter[1], "antiportal"))
2035                                                 shader.surfaceparms |= Q3SURFACEPARM_ANTIPORTAL;
2036                                         else
2037                                         {
2038                                                 // try custom surfaceparms
2039                                                 for (j = 0; j < numcustsurfaceparms; j++)
2040                                                 {
2041                                                         if (!strcasecmp(custsurfaceparmnames[j], parameter[1]))
2042                                                         {
2043                                                                 shader.surfaceparms |= custsurfaceparms[j];
2044                                                                 break;
2045                                                         }
2046                                                 }
2047                                                 // failed all
2048                                                 if (j == numcustsurfaceparms)
2049                                                         Con_DPrintf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[fileindex], parameter[1]);
2050                                         }
2051                                 }
2052                                 else if (!strcasecmp(parameter[0], "dpshadow"))
2053                                         shader.dpshadow = true;
2054                                 else if (!strcasecmp(parameter[0], "dpnoshadow"))
2055                                         shader.dpnoshadow = true;
2056                                 else if (!strcasecmp(parameter[0], "dpreflectcube"))
2057                                         strlcpy(shader.dpreflectcube, parameter[1], sizeof(shader.dpreflectcube));
2058                                 else if (!strcasecmp(parameter[0], "dpmeshcollisions"))
2059                                         shader.dpmeshcollisions = true;
2060                                 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
2061                                 {
2062                                         // some q3 skies don't have the sky parm set
2063                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
2064                                         strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
2065                                 }
2066                                 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
2067                                 {
2068                                         // some q3 skies don't have the sky parm set
2069                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
2070                                         if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
2071                                                 strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
2072                                 }
2073                                 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
2074                                 {
2075                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
2076                                                 shader.textureflags |= Q3TEXTUREFLAG_TWOSIDED;
2077                                 }
2078                                 else if (!strcasecmp(parameter[0], "nomipmaps"))
2079                                         shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
2080                                 else if (!strcasecmp(parameter[0], "nopicmip"))
2081                                         shader.textureflags |= Q3TEXTUREFLAG_NOPICMIP;
2082                                 else if (!strcasecmp(parameter[0], "polygonoffset"))
2083                                         shader.textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
2084                                 else if (!strcasecmp(parameter[0], "dprefract") && numparameters >= 5)
2085                                 {
2086                                         shader.textureflags |= Q3TEXTUREFLAG_REFRACTION;
2087                                         shader.refractfactor = atof(parameter[1]);
2088                                         Vector4Set(shader.refractcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), 1);
2089                                 }
2090                                 else if (!strcasecmp(parameter[0], "dpreflect") && numparameters >= 6)
2091                                 {
2092                                         shader.textureflags |= Q3TEXTUREFLAG_REFLECTION;
2093                                         shader.reflectfactor = atof(parameter[1]);
2094                                         Vector4Set(shader.reflectcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), atof(parameter[5]));
2095                                 }
2096                                 else if (!strcasecmp(parameter[0], "dpcamera"))
2097                                 {
2098                                         shader.textureflags |= Q3TEXTUREFLAG_CAMERA;
2099                                 }
2100                                 else if (!strcasecmp(parameter[0], "dpwater") && numparameters >= 12)
2101                                 {
2102                                         shader.textureflags |= Q3TEXTUREFLAG_WATERSHADER;
2103                                         shader.reflectmin = atof(parameter[1]);
2104                                         shader.reflectmax = atof(parameter[2]);
2105                                         shader.refractfactor = atof(parameter[3]);
2106                                         shader.reflectfactor = atof(parameter[4]);
2107                                         Vector4Set(shader.refractcolor4f, atof(parameter[5]), atof(parameter[6]), atof(parameter[7]), 1);
2108                                         Vector4Set(shader.reflectcolor4f, atof(parameter[8]), atof(parameter[9]), atof(parameter[10]), 1);
2109                                         shader.r_water_wateralpha = atof(parameter[11]);
2110                                 }
2111                                 else if (!strcasecmp(parameter[0], "dpglossintensitymod") && numparameters >= 2)
2112                                 {
2113                                         shader.specularscalemod = atof(parameter[1]);
2114                                 }
2115                                 else if (!strcasecmp(parameter[0], "dpglossexponentmod") && numparameters >= 2)
2116                                 {
2117                                         shader.specularpowermod = atof(parameter[1]);
2118                                 }
2119                                 else if (!strcasecmp(parameter[0], "dpoffsetmapping") && numparameters >= 3)
2120                                 {
2121                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "off"))
2122                                                 shader.offsetmapping = OFFSETMAPPING_OFF;
2123                                         else if (!strcasecmp(parameter[1], "default"))
2124                                                 shader.offsetmapping = OFFSETMAPPING_DEFAULT;
2125                                         else if (!strcasecmp(parameter[1], "linear"))
2126                                                 shader.offsetmapping = OFFSETMAPPING_LINEAR;
2127                                         else if (!strcasecmp(parameter[1], "relief"))
2128                                                 shader.offsetmapping = OFFSETMAPPING_RELIEF;
2129                                         shader.offsetscale = atof(parameter[2]);
2130                                 }
2131                                 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
2132                                 {
2133                                         int i, deformindex;
2134                                         for (deformindex = 0;deformindex < Q3MAXDEFORMS;deformindex++)
2135                                                 if (!shader.deforms[deformindex].deform)
2136                                                         break;
2137                                         if (deformindex < Q3MAXDEFORMS)
2138                                         {
2139                                                 for (i = 0;i < numparameters - 2 && i < Q3DEFORM_MAXPARMS;i++)
2140                                                         shader.deforms[deformindex].parms[i] = atof(parameter[i+2]);
2141                                                      if (!strcasecmp(parameter[1], "projectionshadow")) shader.deforms[deformindex].deform = Q3DEFORM_PROJECTIONSHADOW;
2142                                                 else if (!strcasecmp(parameter[1], "autosprite"      )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE;
2143                                                 else if (!strcasecmp(parameter[1], "autosprite2"     )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE2;
2144                                                 else if (!strcasecmp(parameter[1], "text0"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT0;
2145                                                 else if (!strcasecmp(parameter[1], "text1"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT1;
2146                                                 else if (!strcasecmp(parameter[1], "text2"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT2;
2147                                                 else if (!strcasecmp(parameter[1], "text3"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT3;
2148                                                 else if (!strcasecmp(parameter[1], "text4"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT4;
2149                                                 else if (!strcasecmp(parameter[1], "text5"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT5;
2150                                                 else if (!strcasecmp(parameter[1], "text6"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT6;
2151                                                 else if (!strcasecmp(parameter[1], "text7"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT7;
2152                                                 else if (!strcasecmp(parameter[1], "bulge"           )) shader.deforms[deformindex].deform = Q3DEFORM_BULGE;
2153                                                 else if (!strcasecmp(parameter[1], "normal"          )) shader.deforms[deformindex].deform = Q3DEFORM_NORMAL;
2154                                                 else if (!strcasecmp(parameter[1], "wave"            ))
2155                                                 {
2156                                                         shader.deforms[deformindex].deform = Q3DEFORM_WAVE;
2157                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[3]);
2158                                                         for (i = 0;i < numparameters - 4 && i < Q3WAVEPARMS;i++)
2159                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+4]);
2160                                                 }
2161                                                 else if (!strcasecmp(parameter[1], "move"            ))
2162                                                 {
2163                                                         shader.deforms[deformindex].deform = Q3DEFORM_MOVE;
2164                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[5]);
2165                                                         for (i = 0;i < numparameters - 6 && i < Q3WAVEPARMS;i++)
2166                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+6]);
2167                                                 }
2168                                         }
2169                                 }
2170                         }
2171                         // pick the primary layer to render with
2172                         if (shader.numlayers)
2173                         {
2174                                 shader.backgroundlayer = -1;
2175                                 shader.primarylayer = 0;
2176                                 // if lightmap comes first this is definitely an ordinary texture
2177                                 // if the first two layers have the correct blendfuncs and use vertex alpha, it is a blended terrain shader
2178                                 if ((shader.layers[shader.primarylayer].texturename != NULL)
2179                                   && !strcasecmp(shader.layers[shader.primarylayer].texturename[0], "$lightmap"))
2180                                 {
2181                                         shader.backgroundlayer = -1;
2182                                         shader.primarylayer = 1;
2183                                 }
2184                                 else if (shader.numlayers >= 2
2185                                 &&   shader.layers[1].alphagen.alphagen == Q3ALPHAGEN_VERTEX
2186                                 &&  (shader.layers[0].blendfunc[0] == GL_ONE       && shader.layers[0].blendfunc[1] == GL_ZERO                && !shader.layers[0].alphatest)
2187                                 && ((shader.layers[1].blendfunc[0] == GL_SRC_ALPHA && shader.layers[1].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2188                                 ||  (shader.layers[1].blendfunc[0] == GL_ONE       && shader.layers[1].blendfunc[1] == GL_ZERO                &&  shader.layers[1].alphatest)))
2189                                 {
2190                                         // terrain blending or other effects
2191                                         shader.backgroundlayer = 0;
2192                                         shader.primarylayer = 1;
2193                                 }
2194                         }
2195                         // fix up multiple reflection types
2196                         if(shader.textureflags & Q3TEXTUREFLAG_WATERSHADER)
2197                                 shader.textureflags &= ~(Q3TEXTUREFLAG_REFRACTION | Q3TEXTUREFLAG_REFLECTION | Q3TEXTUREFLAG_CAMERA);
2198
2199                         Q3Shader_AddToHash (&shader);
2200                 }
2201                 Mem_Free(f);
2202         }
2203         FS_FreeSearch(search);
2204         // free custinfoparm values
2205         for (j = 0; j < numcustsurfaceparms; j++)
2206                 Mem_Free(custsurfaceparmnames[j]);
2207 }
2208
2209 q3shaderinfo_t *Mod_LookupQ3Shader(const char *name)
2210 {
2211         unsigned short hash;
2212         q3shader_hash_entry_t* entry;
2213         if (!q3shaders_mem)
2214                 Mod_LoadQ3Shaders();
2215         hash = CRC_Block_CaseInsensitive ((const unsigned char *)name, strlen (name));
2216         entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
2217         while (entry != NULL)
2218         {
2219                 if (strcasecmp (entry->shader.name, name) == 0)
2220                         return &entry->shader;
2221                 entry = entry->chain;
2222         }
2223         return NULL;
2224 }
2225
2226 qboolean Mod_LoadTextureFromQ3Shader(texture_t *texture, const char *name, qboolean warnmissing, qboolean fallback, int defaulttexflags)
2227 {
2228         int j;
2229         int texflagsmask;
2230         qboolean success = true;
2231         q3shaderinfo_t *shader;
2232         if (!name)
2233                 name = "";
2234         strlcpy(texture->name, name, sizeof(texture->name));
2235         shader = name[0] ? Mod_LookupQ3Shader(name) : NULL;
2236
2237         texflagsmask = ~0;
2238         if(!(defaulttexflags & TEXF_PICMIP))
2239                 texflagsmask &= ~TEXF_PICMIP;
2240         if(!(defaulttexflags & TEXF_COMPRESS))
2241                 texflagsmask &= ~TEXF_COMPRESS;
2242         // unless later loaded from the shader
2243         texture->offsetmapping = (mod_q3shader_default_offsetmapping.value) ? OFFSETMAPPING_DEFAULT : OFFSETMAPPING_OFF;
2244         texture->offsetscale = 1;
2245         texture->specularscalemod = 1;
2246         texture->specularpowermod = 1; 
2247         // WHEN ADDING DEFAULTS HERE, REMEMBER TO SYNC TO SHADER LOADING ABOVE
2248         // HERE, AND Q1BSP LOADING
2249         // JUST GREP FOR "specularscalemod = 1".
2250
2251         if (shader)
2252         {
2253                 if (developer_loading.integer)
2254                         Con_Printf("%s: loaded shader for %s\n", loadmodel->name, name);
2255                 texture->surfaceparms = shader->surfaceparms;
2256
2257                 // allow disabling of picmip or compression by defaulttexflags
2258                 texture->textureflags = shader->textureflags & texflagsmask;
2259
2260                 if (shader->surfaceparms & Q3SURFACEPARM_SKY)
2261                 {
2262                         texture->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2263                         if (shader->skyboxname[0])
2264                         {
2265                                 // quake3 seems to append a _ to the skybox name, so this must do so as well
2266                                 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", shader->skyboxname);
2267                         }
2268                 }
2269                 else if ((texture->surfaceflags & Q3SURFACEFLAG_NODRAW) || shader->numlayers == 0)
2270                         texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2271                 else
2272                         texture->basematerialflags = MATERIALFLAG_WALL;
2273
2274                 if (shader->layers[0].alphatest)
2275                         texture->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
2276                 if (shader->textureflags & Q3TEXTUREFLAG_TWOSIDED)
2277                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
2278                 if (shader->textureflags & Q3TEXTUREFLAG_POLYGONOFFSET)
2279                         texture->biaspolygonoffset -= 2;
2280                 if (shader->textureflags & Q3TEXTUREFLAG_REFRACTION)
2281                         texture->basematerialflags |= MATERIALFLAG_REFRACTION;
2282                 if (shader->textureflags & Q3TEXTUREFLAG_REFLECTION)
2283                         texture->basematerialflags |= MATERIALFLAG_REFLECTION;
2284                 if (shader->textureflags & Q3TEXTUREFLAG_WATERSHADER)
2285                         texture->basematerialflags |= MATERIALFLAG_WATERSHADER;
2286                 if (shader->textureflags & Q3TEXTUREFLAG_CAMERA)
2287                         texture->basematerialflags |= MATERIALFLAG_CAMERA;
2288                 texture->customblendfunc[0] = GL_ONE;
2289                 texture->customblendfunc[1] = GL_ZERO;
2290                 if (shader->numlayers > 0)
2291                 {
2292                         texture->customblendfunc[0] = shader->layers[0].blendfunc[0];
2293                         texture->customblendfunc[1] = shader->layers[0].blendfunc[1];
2294 /*
2295 Q3 shader blendfuncs actually used in the game (* = supported by DP)
2296 * additive               GL_ONE GL_ONE
2297 additive weird         GL_ONE GL_SRC_ALPHA
2298 additive weird 2       GL_ONE GL_ONE_MINUS_SRC_ALPHA
2299 * alpha                  GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
2300 alpha inverse          GL_ONE_MINUS_SRC_ALPHA GL_SRC_ALPHA
2301 brighten               GL_DST_COLOR GL_ONE
2302 brighten               GL_ONE GL_SRC_COLOR
2303 brighten weird         GL_DST_COLOR GL_ONE_MINUS_DST_ALPHA
2304 brighten weird 2       GL_DST_COLOR GL_SRC_ALPHA
2305 * modulate               GL_DST_COLOR GL_ZERO
2306 * modulate               GL_ZERO GL_SRC_COLOR
2307 modulate inverse       GL_ZERO GL_ONE_MINUS_SRC_COLOR
2308 modulate inverse alpha GL_ZERO GL_SRC_ALPHA
2309 modulate weird inverse GL_ONE_MINUS_DST_COLOR GL_ZERO
2310 * modulate x2            GL_DST_COLOR GL_SRC_COLOR
2311 * no blend               GL_ONE GL_ZERO
2312 nothing                GL_ZERO GL_ONE
2313 */
2314                         // if not opaque, figure out what blendfunc to use
2315                         if (shader->layers[0].blendfunc[0] != GL_ONE || shader->layers[0].blendfunc[1] != GL_ZERO)
2316                         {
2317                                 if (shader->layers[0].blendfunc[0] == GL_ONE && shader->layers[0].blendfunc[1] == GL_ONE)
2318                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2319                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE)
2320                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2321                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2322                                         texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2323                                 else
2324                                         texture->basematerialflags |= MATERIALFLAG_CUSTOMBLEND | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2325                         }
2326                 }
2327                 if (!shader->lighting)
2328                         texture->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
2329                 if (shader->primarylayer >= 0)
2330                 {
2331                         q3shaderinfo_layer_t* primarylayer = shader->layers + shader->primarylayer;
2332                         // copy over many primarylayer parameters
2333                         texture->rgbgen = primarylayer->rgbgen;
2334                         texture->alphagen = primarylayer->alphagen;
2335                         texture->tcgen = primarylayer->tcgen;
2336                         memcpy(texture->tcmods, primarylayer->tcmods, sizeof(texture->tcmods));
2337                         // load the textures
2338                         texture->numskinframes = primarylayer->numframes;
2339                         texture->skinframerate = primarylayer->framerate;
2340                         for (j = 0;j < primarylayer->numframes;j++)
2341                         {
2342                                 if(cls.state == ca_dedicated)
2343                                 {
2344                                         texture->skinframes[j] = NULL;
2345                                 }
2346                                 else if (!(texture->skinframes[j] = R_SkinFrame_LoadExternal(primarylayer->texturename[j], primarylayer->texflags & texflagsmask, false)))
2347                                 {
2348                                         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);
2349                                         texture->skinframes[j] = R_SkinFrame_LoadMissing();
2350                                 }
2351                         }
2352                 }
2353                 if (shader->backgroundlayer >= 0)
2354                 {
2355                         q3shaderinfo_layer_t* backgroundlayer = shader->layers + shader->backgroundlayer;
2356                         // copy over one secondarylayer parameter
2357                         memcpy(texture->backgroundtcmods, backgroundlayer->tcmods, sizeof(texture->backgroundtcmods));
2358                         // load the textures
2359                         texture->backgroundnumskinframes = backgroundlayer->numframes;
2360                         texture->backgroundskinframerate = backgroundlayer->framerate;
2361                         for (j = 0;j < backgroundlayer->numframes;j++)
2362                         {
2363                                 if(cls.state == ca_dedicated)
2364                                 {
2365                                         texture->skinframes[j] = NULL;
2366                                 }
2367                                 else if (!(texture->backgroundskinframes[j] = R_SkinFrame_LoadExternal(backgroundlayer->texturename[j], backgroundlayer->texflags & texflagsmask, false)))
2368                                 {
2369                                         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);
2370                                         texture->backgroundskinframes[j] = R_SkinFrame_LoadMissing();
2371                                 }
2372                         }
2373                 }
2374                 if (shader->dpshadow)
2375                         texture->basematerialflags &= ~MATERIALFLAG_NOSHADOW;
2376                 if (shader->dpnoshadow)
2377                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW;
2378                 memcpy(texture->deforms, shader->deforms, sizeof(texture->deforms));
2379                 texture->reflectmin = shader->reflectmin;
2380                 texture->reflectmax = shader->reflectmax;
2381                 texture->refractfactor = shader->refractfactor;
2382                 Vector4Copy(shader->refractcolor4f, texture->refractcolor4f);
2383                 texture->reflectfactor = shader->reflectfactor;
2384                 Vector4Copy(shader->reflectcolor4f, texture->reflectcolor4f);
2385                 texture->r_water_wateralpha = shader->r_water_wateralpha;
2386                 texture->offsetmapping = shader->offsetmapping;
2387                 texture->offsetscale = shader->offsetscale;
2388                 texture->specularscalemod = shader->specularscalemod;
2389                 texture->specularpowermod = shader->specularpowermod;
2390                 if (shader->dpreflectcube[0])
2391                         texture->reflectcubetexture = R_GetCubemap(shader->dpreflectcube);
2392
2393                 // set up default supercontents (on q3bsp this is overridden by the q3bsp loader)
2394                 texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2395                 if (shader->surfaceparms & Q3SURFACEPARM_LAVA         ) texture->supercontents  = SUPERCONTENTS_LAVA         ;
2396                 if (shader->surfaceparms & Q3SURFACEPARM_SLIME        ) texture->supercontents  = SUPERCONTENTS_SLIME        ;
2397                 if (shader->surfaceparms & Q3SURFACEPARM_WATER        ) texture->supercontents  = SUPERCONTENTS_WATER        ;
2398                 if (shader->surfaceparms & Q3SURFACEPARM_NONSOLID     ) texture->supercontents  = 0                          ;
2399                 if (shader->surfaceparms & Q3SURFACEPARM_PLAYERCLIP   ) texture->supercontents  = SUPERCONTENTS_PLAYERCLIP   ;
2400                 if (shader->surfaceparms & Q3SURFACEPARM_BOTCLIP      ) texture->supercontents  = SUPERCONTENTS_MONSTERCLIP  ;
2401                 if (shader->surfaceparms & Q3SURFACEPARM_SKY          ) texture->supercontents  = SUPERCONTENTS_SKY          ;
2402
2403         //      if (shader->surfaceparms & Q3SURFACEPARM_ALPHASHADOW  ) texture->supercontents |= SUPERCONTENTS_ALPHASHADOW  ;
2404         //      if (shader->surfaceparms & Q3SURFACEPARM_AREAPORTAL   ) texture->supercontents |= SUPERCONTENTS_AREAPORTAL   ;
2405         //      if (shader->surfaceparms & Q3SURFACEPARM_CLUSTERPORTAL) texture->supercontents |= SUPERCONTENTS_CLUSTERPORTAL;
2406         //      if (shader->surfaceparms & Q3SURFACEPARM_DETAIL       ) texture->supercontents |= SUPERCONTENTS_DETAIL       ;
2407                 if (shader->surfaceparms & Q3SURFACEPARM_DONOTENTER   ) texture->supercontents |= SUPERCONTENTS_DONOTENTER   ;
2408         //      if (shader->surfaceparms & Q3SURFACEPARM_FOG          ) texture->supercontents |= SUPERCONTENTS_FOG          ;
2409                 if (shader->surfaceparms & Q3SURFACEPARM_LAVA         ) texture->supercontents |= SUPERCONTENTS_LAVA         ;
2410         //      if (shader->surfaceparms & Q3SURFACEPARM_LIGHTFILTER  ) texture->supercontents |= SUPERCONTENTS_LIGHTFILTER  ;
2411         //      if (shader->surfaceparms & Q3SURFACEPARM_METALSTEPS   ) texture->supercontents |= SUPERCONTENTS_METALSTEPS   ;
2412         //      if (shader->surfaceparms & Q3SURFACEPARM_NODAMAGE     ) texture->supercontents |= SUPERCONTENTS_NODAMAGE     ;
2413         //      if (shader->surfaceparms & Q3SURFACEPARM_NODLIGHT     ) texture->supercontents |= SUPERCONTENTS_NODLIGHT     ;
2414         //      if (shader->surfaceparms & Q3SURFACEPARM_NODRAW       ) texture->supercontents |= SUPERCONTENTS_NODRAW       ;
2415                 if (shader->surfaceparms & Q3SURFACEPARM_NODROP       ) texture->supercontents |= SUPERCONTENTS_NODROP       ;
2416         //      if (shader->surfaceparms & Q3SURFACEPARM_NOIMPACT     ) texture->supercontents |= SUPERCONTENTS_NOIMPACT     ;
2417         //      if (shader->surfaceparms & Q3SURFACEPARM_NOLIGHTMAP   ) texture->supercontents |= SUPERCONTENTS_NOLIGHTMAP   ;
2418         //      if (shader->surfaceparms & Q3SURFACEPARM_NOMARKS      ) texture->supercontents |= SUPERCONTENTS_NOMARKS      ;
2419         //      if (shader->surfaceparms & Q3SURFACEPARM_NOMIPMAPS    ) texture->supercontents |= SUPERCONTENTS_NOMIPMAPS    ;
2420                 if (shader->surfaceparms & Q3SURFACEPARM_NONSOLID     ) texture->supercontents &=~SUPERCONTENTS_SOLID        ;
2421         //      if (shader->surfaceparms & Q3SURFACEPARM_ORIGIN       ) texture->supercontents |= SUPERCONTENTS_ORIGIN       ;
2422                 if (shader->surfaceparms & Q3SURFACEPARM_PLAYERCLIP   ) texture->supercontents |= SUPERCONTENTS_PLAYERCLIP   ;
2423                 if (shader->surfaceparms & Q3SURFACEPARM_SKY          ) texture->supercontents |= SUPERCONTENTS_SKY          ;
2424         //      if (shader->surfaceparms & Q3SURFACEPARM_SLICK        ) texture->supercontents |= SUPERCONTENTS_SLICK        ;
2425                 if (shader->surfaceparms & Q3SURFACEPARM_SLIME        ) texture->supercontents |= SUPERCONTENTS_SLIME        ;
2426         //      if (shader->surfaceparms & Q3SURFACEPARM_STRUCTURAL   ) texture->supercontents |= SUPERCONTENTS_STRUCTURAL   ;
2427         //      if (shader->surfaceparms & Q3SURFACEPARM_TRANS        ) texture->supercontents |= SUPERCONTENTS_TRANS        ;
2428                 if (shader->surfaceparms & Q3SURFACEPARM_WATER        ) texture->supercontents |= SUPERCONTENTS_WATER        ;
2429         //      if (shader->surfaceparms & Q3SURFACEPARM_POINTLIGHT   ) texture->supercontents |= SUPERCONTENTS_POINTLIGHT   ;
2430         //      if (shader->surfaceparms & Q3SURFACEPARM_HINT         ) texture->supercontents |= SUPERCONTENTS_HINT         ;
2431         //      if (shader->surfaceparms & Q3SURFACEPARM_DUST         ) texture->supercontents |= SUPERCONTENTS_DUST         ;
2432                 if (shader->surfaceparms & Q3SURFACEPARM_BOTCLIP      ) texture->supercontents |= SUPERCONTENTS_BOTCLIP      | SUPERCONTENTS_MONSTERCLIP;
2433         //      if (shader->surfaceparms & Q3SURFACEPARM_LIGHTGRID    ) texture->supercontents |= SUPERCONTENTS_LIGHTGRID    ;
2434         //      if (shader->surfaceparms & Q3SURFACEPARM_ANTIPORTAL   ) texture->supercontents |= SUPERCONTENTS_ANTIPORTAL   ;
2435
2436                 if (shader->dpmeshcollisions)
2437                         texture->basematerialflags |= MATERIALFLAG_MESHCOLLISIONS;
2438         }
2439         else if (!strcmp(texture->name, "noshader") || !texture->name[0])
2440         {
2441                 if (developer_extra.integer)
2442                         Con_DPrintf("^1%s:^7 using fallback noshader material for ^3\"%s\"\n", loadmodel->name, name);
2443                 texture->surfaceparms = 0;
2444                 texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2445         }
2446         else if (!strcmp(texture->name, "common/nodraw") || !strcmp(texture->name, "textures/common/nodraw"))
2447         {
2448                 if (developer_extra.integer)
2449                         Con_DPrintf("^1%s:^7 using fallback nodraw material for ^3\"%s\"\n", loadmodel->name, name);
2450                 texture->surfaceparms = 0;
2451                 texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2452                 texture->supercontents = SUPERCONTENTS_SOLID;
2453         }
2454         else
2455         {
2456                 if (developer_extra.integer)
2457                         Con_DPrintf("^1%s:^7 No shader found for texture ^3\"%s\"\n", loadmodel->name, texture->name);
2458                 texture->surfaceparms = 0;
2459                 if (texture->surfaceflags & Q3SURFACEFLAG_NODRAW)
2460                 {
2461                         texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2462                         texture->supercontents = SUPERCONTENTS_SOLID;
2463                 }
2464                 else if (texture->surfaceflags & Q3SURFACEFLAG_SKY)
2465                 {
2466                         texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2467                         texture->supercontents = SUPERCONTENTS_SKY;
2468                 }
2469                 else
2470                 {
2471                         texture->basematerialflags |= MATERIALFLAG_WALL;
2472                         texture->supercontents = SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
2473                 }
2474                 texture->numskinframes = 1;
2475                 if(cls.state == ca_dedicated)
2476                 {
2477                         texture->skinframes[0] = NULL;
2478                 }
2479                 else
2480                 {
2481                         if (fallback)
2482                         {
2483                                 if ((texture->skinframes[0] = R_SkinFrame_LoadExternal(texture->name, defaulttexflags, false)))
2484                                 {
2485                                         if(texture->skinframes[0]->hasalpha)
2486                                                 texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2487                                 }
2488                                 else
2489                                         success = false;
2490                         }
2491                         else
2492                                 success = false;
2493                         if (!success && warnmissing)
2494                                 Con_Printf("^1%s:^7 could not load texture ^3\"%s\"\n", loadmodel->name, texture->name);
2495                 }
2496         }
2497         // init the animation variables
2498         texture->currentframe = texture;
2499         if (texture->numskinframes < 1)
2500                 texture->numskinframes = 1;
2501         if (!texture->skinframes[0])
2502                 texture->skinframes[0] = R_SkinFrame_LoadMissing();
2503         texture->currentskinframe = texture->skinframes[0];
2504         texture->backgroundcurrentskinframe = texture->backgroundskinframes[0];
2505         return success;
2506 }
2507
2508 skinfile_t *Mod_LoadSkinFiles(void)
2509 {
2510         int i, words, line, wordsoverflow;
2511         char *text;
2512         const char *data;
2513         skinfile_t *skinfile = NULL, *first = NULL;
2514         skinfileitem_t *skinfileitem;
2515         char word[10][MAX_QPATH];
2516
2517 /*
2518 sample file:
2519 U_bodyBox,models/players/Legoman/BikerA2.tga
2520 U_RArm,models/players/Legoman/BikerA1.tga
2521 U_LArm,models/players/Legoman/BikerA1.tga
2522 U_armor,common/nodraw
2523 U_sword,common/nodraw
2524 U_shield,common/nodraw
2525 U_homb,common/nodraw
2526 U_backpack,common/nodraw
2527 U_colcha,common/nodraw
2528 tag_head,
2529 tag_weapon,
2530 tag_torso,
2531 */
2532         memset(word, 0, sizeof(word));
2533         for (i = 0;i < 256 && (data = text = (char *)FS_LoadFile(va("%s_%i.skin", loadmodel->name, i), tempmempool, true, NULL));i++)
2534         {
2535                 // If it's the first file we parse
2536                 if (skinfile == NULL)
2537                 {
2538                         skinfile = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2539                         first = skinfile;
2540                 }
2541                 else
2542                 {
2543                         skinfile->next = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2544                         skinfile = skinfile->next;
2545                 }
2546                 skinfile->next = NULL;
2547
2548                 for(line = 0;;line++)
2549                 {
2550                         // parse line
2551                         if (!COM_ParseToken_QuakeC(&data, true))
2552                                 break;
2553                         if (!strcmp(com_token, "\n"))
2554                                 continue;
2555                         words = 0;
2556                         wordsoverflow = false;
2557                         do
2558                         {
2559                                 if (words < 10)
2560                                         strlcpy(word[words++], com_token, sizeof (word[0]));
2561                                 else
2562                                         wordsoverflow = true;
2563                         }
2564                         while (COM_ParseToken_QuakeC(&data, true) && strcmp(com_token, "\n"));
2565                         if (wordsoverflow)
2566                         {
2567                                 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);
2568                                 continue;
2569                         }
2570                         // words is always >= 1
2571                         if (!strcmp(word[0], "replace"))
2572                         {
2573                                 if (words == 3)
2574                                 {
2575                                         if (developer_loading.integer)
2576                                                 Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[1], word[2]);
2577                                         skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2578                                         skinfileitem->next = skinfile->items;
2579                                         skinfile->items = skinfileitem;
2580                                         strlcpy (skinfileitem->name, word[1], sizeof (skinfileitem->name));
2581                                         strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2582                                 }
2583                                 else
2584                                         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]);
2585                         }
2586                         else if (words >= 2 && !strncmp(word[0], "tag_", 4))
2587                         {
2588                                 // tag name, like "tag_weapon,"
2589                                 // not used for anything (not even in Quake3)
2590                         }
2591                         else if (words >= 2 && !strcmp(word[1], ","))
2592                         {
2593                                 // mesh shader name, like "U_RArm,models/players/Legoman/BikerA1.tga"
2594                                 if (developer_loading.integer)
2595                                         Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[0], word[2]);
2596                                 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2597                                 skinfileitem->next = skinfile->items;
2598                                 skinfile->items = skinfileitem;
2599                                 strlcpy (skinfileitem->name, word[0], sizeof (skinfileitem->name));
2600                                 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2601                         }
2602                         else
2603                                 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);
2604                 }
2605                 Mem_Free(text);
2606         }
2607         if (i)
2608                 loadmodel->numskins = i;
2609         return first;
2610 }
2611
2612 void Mod_FreeSkinFiles(skinfile_t *skinfile)
2613 {
2614         skinfile_t *next;
2615         skinfileitem_t *skinfileitem, *nextitem;
2616         for (;skinfile;skinfile = next)
2617         {
2618                 next = skinfile->next;
2619                 for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = nextitem)
2620                 {
2621                         nextitem = skinfileitem->next;
2622                         Mem_Free(skinfileitem);
2623                 }
2624                 Mem_Free(skinfile);
2625         }
2626 }
2627
2628 int Mod_CountSkinFiles(skinfile_t *skinfile)
2629 {
2630         int i;
2631         for (i = 0;skinfile;skinfile = skinfile->next, i++);
2632         return i;
2633 }
2634
2635 void Mod_SnapVertices(int numcomponents, int numvertices, float *vertices, float snap)
2636 {
2637         int i;
2638         double isnap = 1.0 / snap;
2639         for (i = 0;i < numvertices*numcomponents;i++)
2640                 vertices[i] = floor(vertices[i]*isnap)*snap;
2641 }
2642
2643 int Mod_RemoveDegenerateTriangles(int numtriangles, const int *inelement3i, int *outelement3i, const float *vertex3f)
2644 {
2645         int i, outtriangles;
2646         float edgedir1[3], edgedir2[3], temp[3];
2647         // a degenerate triangle is one with no width (thickness, surface area)
2648         // these are characterized by having all 3 points colinear (along a line)
2649         // or having two points identical
2650         // the simplest check is to calculate the triangle's area
2651         for (i = 0, outtriangles = 0;i < numtriangles;i++, inelement3i += 3)
2652         {
2653                 // calculate first edge
2654                 VectorSubtract(vertex3f + inelement3i[1] * 3, vertex3f + inelement3i[0] * 3, edgedir1);
2655                 VectorSubtract(vertex3f + inelement3i[2] * 3, vertex3f + inelement3i[0] * 3, edgedir2);
2656                 CrossProduct(edgedir1, edgedir2, temp);
2657                 if (VectorLength2(temp) < 0.001f)
2658                         continue; // degenerate triangle (no area)
2659                 // valid triangle (has area)
2660                 VectorCopy(inelement3i, outelement3i);
2661                 outelement3i += 3;
2662                 outtriangles++;
2663         }
2664         return outtriangles;
2665 }
2666
2667 void Mod_VertexRangeFromElements(int numelements, const int *elements, int *firstvertexpointer, int *lastvertexpointer)
2668 {
2669         int i, e;
2670         int firstvertex, lastvertex;
2671         if (numelements > 0 && elements)
2672         {
2673                 firstvertex = lastvertex = elements[0];
2674                 for (i = 1;i < numelements;i++)
2675                 {
2676                         e = elements[i];
2677                         firstvertex = min(firstvertex, e);
2678                         lastvertex = max(lastvertex, e);
2679                 }
2680         }
2681         else
2682                 firstvertex = lastvertex = 0;
2683         if (firstvertexpointer)
2684                 *firstvertexpointer = firstvertex;
2685         if (lastvertexpointer)
2686                 *lastvertexpointer = lastvertex;
2687 }
2688
2689 void Mod_MakeSortedSurfaces(dp_model_t *mod)
2690 {
2691         // make an optimal set of texture-sorted batches to draw...
2692         int j, t;
2693         int *firstsurfacefortexture;
2694         int *numsurfacesfortexture;
2695         if (!mod->sortedmodelsurfaces)
2696                 mod->sortedmodelsurfaces = (int *) Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
2697         firstsurfacefortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*firstsurfacefortexture));
2698         numsurfacesfortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*numsurfacesfortexture));
2699         memset(numsurfacesfortexture, 0, mod->num_textures * sizeof(*numsurfacesfortexture));
2700         for (j = 0;j < mod->nummodelsurfaces;j++)
2701         {