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