changed texture formats from RGBA to BGRA, yes this is a massive change,
[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
29 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"};
30
31 model_t *loadmodel;
32
33 static mempool_t *mod_mempool;
34 static memexpandablearray_t models;
35
36 // FIXME: make this a memexpandablearray_t
37 #define Q3SHADER_MAXSHADERS 16384
38 static int q3shaders_numshaders = 0;
39 static q3shaderinfo_t q3shaders_shaders[Q3SHADER_MAXSHADERS];
40
41 static void mod_start(void)
42 {
43         int i;
44         int nummodels = Mem_ExpandableArray_IndexRange(&models);
45         model_t *mod;
46
47         // parse the Q3 shader files
48         Mod_LoadQ3Shaders();
49
50         for (i = 0;i < nummodels;i++)
51                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
52                         if (mod->used)
53                                 Mod_LoadModel(mod, true, false, mod->isworldmodel);
54 }
55
56 static void mod_shutdown(void)
57 {
58         int i;
59         int nummodels = Mem_ExpandableArray_IndexRange(&models);
60         model_t *mod;
61
62         for (i = 0;i < nummodels;i++)
63                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && (mod->loaded || mod->mempool))
64                         Mod_UnloadModel(mod);
65 }
66
67 static void mod_newmap(void)
68 {
69         msurface_t *surface;
70         int i, j, k, surfacenum, ssize, tsize;
71         int nummodels = Mem_ExpandableArray_IndexRange(&models);
72         model_t *mod;
73
74         R_SkinFrame_PrepareForPurge();
75         for (i = 0;i < nummodels;i++)
76         {
77                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool && mod->data_textures)
78                 {
79                         for (j = 0;j < mod->num_textures;j++)
80                         {
81                                 for (k = 0;k < mod->data_textures[j].numskinframes;k++)
82                                         R_SkinFrame_MarkUsed(mod->data_textures[j].skinframes[k]);
83                                 for (k = 0;k < mod->data_textures[j].backgroundnumskinframes;k++)
84                                         R_SkinFrame_MarkUsed(mod->data_textures[j].backgroundskinframes[k]);
85                         }
86                 }
87         }
88         R_SkinFrame_Purge();
89
90         if (!cl_stainmaps_clearonload.integer)
91                 return;
92
93         for (i = 0;i < nummodels;i++)
94         {
95                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool && mod->data_surfaces)
96                 {
97                         for (surfacenum = 0, surface = mod->data_surfaces;surfacenum < mod->num_surfaces;surfacenum++, surface++)
98                         {
99                                 if (surface->lightmapinfo && surface->lightmapinfo->stainsamples)
100                                 {
101                                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
102                                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
103                                         memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
104                                         surface->cached_dlight = true;
105                                 }
106                         }
107                 }
108         }
109 }
110
111 /*
112 ===============
113 Mod_Init
114 ===============
115 */
116 static void Mod_Print(void);
117 static void Mod_Precache (void);
118 static void Mod_BuildVBOs(void);
119 void Mod_Init (void)
120 {
121         mod_mempool = Mem_AllocPool("modelinfo", 0, NULL);
122         Mem_ExpandableArray_NewArray(&models, mod_mempool, sizeof(model_t), 16);
123
124         Mod_BrushInit();
125         Mod_AliasInit();
126         Mod_SpriteInit();
127
128         Cvar_RegisterVariable(&r_mipskins);
129         Cmd_AddCommand ("modellist", Mod_Print, "prints a list of loaded models");
130         Cmd_AddCommand ("modelprecache", Mod_Precache, "load a model");
131 }
132
133 void Mod_RenderInit(void)
134 {
135         R_RegisterModule("Models", mod_start, mod_shutdown, mod_newmap);
136 }
137
138 void Mod_UnloadModel (model_t *mod)
139 {
140         char name[MAX_QPATH];
141         qboolean isworldmodel;
142         qboolean used;
143         strlcpy(name, mod->name, sizeof(name));
144         isworldmodel = mod->isworldmodel;
145         used = mod->used;
146         if (mod->surfmesh.ebo)
147                 R_Mesh_DestroyBufferObject(mod->surfmesh.ebo);
148         if (mod->surfmesh.vbo)
149                 R_Mesh_DestroyBufferObject(mod->surfmesh.vbo);
150         // free textures/memory attached to the model
151         R_FreeTexturePool(&mod->texturepool);
152         Mem_FreePool(&mod->mempool);
153         // clear the struct to make it available
154         memset(mod, 0, sizeof(model_t));
155         // restore the fields we want to preserve
156         strlcpy(mod->name, name, sizeof(mod->name));
157         mod->isworldmodel = isworldmodel;
158         mod->used = used;
159         mod->loaded = false;
160 }
161
162 /*
163 ==================
164 Mod_LoadModel
165
166 Loads a model
167 ==================
168 */
169 model_t *Mod_LoadModel(model_t *mod, qboolean crash, qboolean checkdisk, qboolean isworldmodel)
170 {
171         int num;
172         unsigned int crc;
173         void *buf;
174         fs_offset_t filesize;
175
176         mod->used = true;
177
178         if (mod->name[0] == '*') // submodel
179                 return mod;
180
181         crc = 0;
182         buf = NULL;
183
184         // even if the model is loaded it still may need reloading...
185
186         // if the model is a worldmodel and is being referred to as a
187         // non-worldmodel here, then it needs reloading to get rid of the
188         // submodels
189         if (mod->isworldmodel != isworldmodel)
190                 mod->loaded = false;
191
192         // if it is not loaded or checkdisk is true we need to calculate the crc
193         if (!mod->loaded || checkdisk)
194         {
195                 if (checkdisk && mod->loaded)
196                         Con_DPrintf("checking model %s\n", mod->name);
197                 buf = FS_LoadFile (mod->name, tempmempool, false, &filesize);
198                 if (buf)
199                 {
200                         crc = CRC_Block((unsigned char *)buf, filesize);
201                         // we need to reload the model if the crc does not match
202                         if (mod->crc != crc)
203                                 mod->loaded = false;
204                 }
205         }
206
207         // if the model is already loaded and checks passed, just return
208         if (mod->loaded)
209         {
210                 if (buf)
211                         Mem_Free(buf);
212                 return mod;
213         }
214
215         Con_DPrintf("loading model %s\n", mod->name);
216         // LordHavoc: unload the existing model in this slot (if there is one)
217         if (mod->loaded || mod->mempool)
218                 Mod_UnloadModel(mod);
219
220         // load the model
221         mod->isworldmodel = isworldmodel;
222         mod->used = true;
223         mod->crc = crc;
224         // errors can prevent the corresponding mod->loaded = true;
225         mod->loaded = false;
226
227         // default model radius and bounding box (mainly for missing models)
228         mod->radius = 16;
229         VectorSet(mod->normalmins, -mod->radius, -mod->radius, -mod->radius);
230         VectorSet(mod->normalmaxs, mod->radius, mod->radius, mod->radius);
231         VectorSet(mod->yawmins, -mod->radius, -mod->radius, -mod->radius);
232         VectorSet(mod->yawmaxs, mod->radius, mod->radius, mod->radius);
233         VectorSet(mod->rotatedmins, -mod->radius, -mod->radius, -mod->radius);
234         VectorSet(mod->rotatedmaxs, mod->radius, mod->radius, mod->radius);
235
236         if (buf)
237         {
238                 char *bufend = (char *)buf + filesize;
239
240                 // all models use memory, so allocate a memory pool
241                 mod->mempool = Mem_AllocPool(mod->name, 0, NULL);
242
243                 num = LittleLong(*((int *)buf));
244                 // call the apropriate loader
245                 loadmodel = mod;
246                      if (!memcmp(buf, "IDPO", 4)) Mod_IDP0_Load(mod, buf, bufend);
247                 else if (!memcmp(buf, "IDP2", 4)) Mod_IDP2_Load(mod, buf, bufend);
248                 else if (!memcmp(buf, "IDP3", 4)) Mod_IDP3_Load(mod, buf, bufend);
249                 else if (!memcmp(buf, "IDSP", 4)) Mod_IDSP_Load(mod, buf, bufend);
250                 else if (!memcmp(buf, "IDS2", 4)) Mod_IDS2_Load(mod, buf, bufend);
251                 else if (!memcmp(buf, "IBSP", 4)) Mod_IBSP_Load(mod, buf, bufend);
252                 else if (!memcmp(buf, "ZYMOTICMODEL", 12)) Mod_ZYMOTICMODEL_Load(mod, buf, bufend);
253                 else if (!memcmp(buf, "DARKPLACESMODEL", 16)) Mod_DARKPLACESMODEL_Load(mod, buf, bufend);
254                 else if (!memcmp(buf, "ACTRHEAD", 8)) Mod_PSKMODEL_Load(mod, buf, bufend);
255                 else if (strlen(mod->name) >= 4 && !strcmp(mod->name - 4, ".map")) Mod_MAP_Load(mod, buf, bufend);
256                 else if (!memcmp(buf, "MCBSPpad", 8)) Mod_Q1BSP_Load(mod, buf, bufend);
257                 else if (num == BSPVERSION || num == 30) Mod_Q1BSP_Load(mod, buf, bufend);
258                 else Con_Printf("Mod_LoadModel: model \"%s\" is of unknown/unsupported type\n", mod->name);
259                 Mem_Free(buf);
260
261                 Mod_BuildVBOs();
262
263                 // no fatal errors occurred, so this model is ready to use.
264                 mod->loaded = true;
265         }
266         else if (crash)
267         {
268                 // LordHavoc: Sys_Error was *ANNOYING*
269                 Con_Printf ("Mod_LoadModel: %s not found\n", mod->name);
270         }
271         return mod;
272 }
273
274 void Mod_ClearUsed(void)
275 {
276         int i;
277         int nummodels = Mem_ExpandableArray_IndexRange(&models);
278         model_t *mod;
279         for (i = 0;i < nummodels;i++)
280                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0])
281                         mod->used = false;
282 }
283
284 void Mod_PurgeUnused(void)
285 {
286         int i;
287         int nummodels = Mem_ExpandableArray_IndexRange(&models);
288         model_t *mod;
289         for (i = 0;i < nummodels;i++)
290         {
291                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !mod->used)
292                 {
293                         Mod_UnloadModel(mod);
294                         Mem_ExpandableArray_FreeRecord(&models, mod);
295                 }
296         }
297 }
298
299 // only used during loading!
300 void Mod_RemoveStaleWorldModels(model_t *skip)
301 {
302         int i;
303         int nummodels = Mem_ExpandableArray_IndexRange(&models);
304         model_t *mod;
305         for (i = 0;i < nummodels;i++)
306         {
307                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->isworldmodel && mod->loaded && skip != mod)
308                 {
309                         Mod_UnloadModel(mod);
310                         mod->isworldmodel = false;
311                         mod->used = false;
312                 }
313         }
314 }
315
316 /*
317 ==================
318 Mod_FindName
319
320 ==================
321 */
322 model_t *Mod_FindName(const char *name)
323 {
324         int i;
325         int nummodels = Mem_ExpandableArray_IndexRange(&models);
326         model_t *mod;
327
328         if (!name[0])
329                 Host_Error ("Mod_ForName: NULL name");
330
331         // search the currently loaded models
332         for (i = 0;i < nummodels;i++)
333         {
334                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !strcmp(mod->name, name))
335                 {
336                         mod->used = true;
337                         return mod;
338                 }
339         }
340
341         // no match found, create a new one
342         mod = Mem_ExpandableArray_AllocRecord(&models);
343         strlcpy(mod->name, name, sizeof(mod->name));
344         mod->loaded = false;
345         mod->used = true;
346         return mod;
347 }
348
349 /*
350 ==================
351 Mod_ForName
352
353 Loads in a model for the given name
354 ==================
355 */
356 model_t *Mod_ForName(const char *name, qboolean crash, qboolean checkdisk, qboolean isworldmodel)
357 {
358         model_t *model;
359         model = Mod_FindName(name);
360         if (model->name[0] != '*' && (!model->loaded || checkdisk))
361                 Mod_LoadModel(model, crash, checkdisk, isworldmodel);
362         return model;
363 }
364
365 /*
366 ==================
367 Mod_Reload
368
369 Reloads all models if they have changed
370 ==================
371 */
372 void Mod_Reload(void)
373 {
374         int i;
375         int nummodels = Mem_ExpandableArray_IndexRange(&models);
376         model_t *mod;
377         for (i = 0;i < nummodels;i++)
378                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
379                         Mod_LoadModel(mod, true, true, mod->isworldmodel);
380 }
381
382 unsigned char *mod_base;
383
384
385 //=============================================================================
386
387 /*
388 ================
389 Mod_Print
390 ================
391 */
392 static void Mod_Print(void)
393 {
394         int i;
395         int nummodels = Mem_ExpandableArray_IndexRange(&models);
396         model_t *mod;
397
398         Con_Print("Loaded models:\n");
399         for (i = 0;i < nummodels;i++)
400                 if ((mod = Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0])
401                         Con_Printf("%4iK %s\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name);
402 }
403
404 /*
405 ================
406 Mod_Precache
407 ================
408 */
409 static void Mod_Precache(void)
410 {
411         if (Cmd_Argc() == 2)
412                 Mod_ForName(Cmd_Argv(1), false, true, cl.worldmodel && !strcasecmp(Cmd_Argv(1), cl.worldmodel->name));
413         else
414                 Con_Print("usage: modelprecache <filename>\n");
415 }
416
417 int Mod_BuildVertexRemapTableFromElements(int numelements, const int *elements, int numvertices, int *remapvertices)
418 {
419         int i, count;
420         unsigned char *used;
421         used = (unsigned char *)Mem_Alloc(tempmempool, numvertices);
422         memset(used, 0, numvertices);
423         for (i = 0;i < numelements;i++)
424                 used[elements[i]] = 1;
425         for (i = 0, count = 0;i < numvertices;i++)
426                 remapvertices[i] = used[i] ? count++ : -1;
427         Mem_Free(used);
428         return count;
429 }
430
431 #if 1
432 // fast way, using an edge hash
433 #define TRIANGLEEDGEHASH 8192
434 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
435 {
436         int i, j, p, e1, e2, *n, hashindex, count, match;
437         const int *e;
438         typedef struct edgehashentry_s
439         {
440                 struct edgehashentry_s *next;
441                 int triangle;
442                 int element[2];
443         }
444         edgehashentry_t;
445         edgehashentry_t *edgehash[TRIANGLEEDGEHASH], *edgehashentries, edgehashentriesbuffer[TRIANGLEEDGEHASH*3], *hash;
446         memset(edgehash, 0, sizeof(edgehash));
447         edgehashentries = edgehashentriesbuffer;
448         // if there are too many triangles for the stack array, allocate larger buffer
449         if (numtriangles > TRIANGLEEDGEHASH)
450                 edgehashentries = (edgehashentry_t *)Mem_Alloc(tempmempool, numtriangles * 3 * sizeof(edgehashentry_t));
451         // find neighboring triangles
452         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
453         {
454                 for (j = 0, p = 2;j < 3;p = j, j++)
455                 {
456                         e1 = e[p];
457                         e2 = e[j];
458                         // this hash index works for both forward and backward edges
459                         hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
460                         hash = edgehashentries + i * 3 + j;
461                         hash->next = edgehash[hashindex];
462                         edgehash[hashindex] = hash;
463                         hash->triangle = i;
464                         hash->element[0] = e1;
465                         hash->element[1] = e2;
466                 }
467         }
468         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
469         {
470                 for (j = 0, p = 2;j < 3;p = j, j++)
471                 {
472                         e1 = e[p];
473                         e2 = e[j];
474                         // this hash index works for both forward and backward edges
475                         hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
476                         count = 0;
477                         match = -1;
478                         for (hash = edgehash[hashindex];hash;hash = hash->next)
479                         {
480                                 if (hash->element[0] == e2 && hash->element[1] == e1)
481                                 {
482                                         if (hash->triangle != i)
483                                                 match = hash->triangle;
484                                         count++;
485                                 }
486                                 else if ((hash->element[0] == e1 && hash->element[1] == e2))
487                                         count++;
488                         }
489                         // detect edges shared by three triangles and make them seams
490                         if (count > 2)
491                                 match = -1;
492                         n[p] = match;
493                 }
494         }
495         // free the allocated buffer
496         if (edgehashentries != edgehashentriesbuffer)
497                 Mem_Free(edgehashentries);
498 }
499 #else
500 // very slow but simple way
501 static int Mod_FindTriangleWithEdge(const int *elements, int numtriangles, int start, int end, int ignore)
502 {
503         int i, match, count;
504         count = 0;
505         match = -1;
506         for (i = 0;i < numtriangles;i++, elements += 3)
507         {
508                      if ((elements[0] == start && elements[1] == end)
509                       || (elements[1] == start && elements[2] == end)
510                       || (elements[2] == start && elements[0] == end))
511                 {
512                         if (i != ignore)
513                                 match = i;
514                         count++;
515                 }
516                 else if ((elements[1] == start && elements[0] == end)
517                       || (elements[2] == start && elements[1] == end)
518                       || (elements[0] == start && elements[2] == end))
519                         count++;
520         }
521         // detect edges shared by three triangles and make them seams
522         if (count > 2)
523                 match = -1;
524         return match;
525 }
526
527 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
528 {
529         int i, *n;
530         const int *e;
531         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
532         {
533                 n[0] = Mod_FindTriangleWithEdge(elements, numtriangles, e[1], e[0], i);
534                 n[1] = Mod_FindTriangleWithEdge(elements, numtriangles, e[2], e[1], i);
535                 n[2] = Mod_FindTriangleWithEdge(elements, numtriangles, e[0], e[2], i);
536         }
537 }
538 #endif
539
540 void Mod_ValidateElements(int *elements, int numtriangles, int firstvertex, int numverts, const char *filename, int fileline)
541 {
542         int i, warned = false, endvertex = firstvertex + numverts;
543         for (i = 0;i < numtriangles * 3;i++)
544         {
545                 if (elements[i] < firstvertex || elements[i] >= endvertex)
546                 {
547                         if (!warned)
548                         {
549                                 warned = true;
550                                 Con_Printf("Mod_ValidateElements: out of bounds elements detected at %s:%d\n", filename, fileline);
551                         }
552                         elements[i] = firstvertex;
553                 }
554         }
555 }
556
557 // warning: this is an expensive function!
558 void Mod_BuildNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const int *elements, float *normal3f, qboolean areaweighting)
559 {
560         int i, j;
561         const int *element;
562         float *vectorNormal;
563         float areaNormal[3];
564         // clear the vectors
565         memset(normal3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
566         // process each vertex of each triangle and accumulate the results
567         // use area-averaging, to make triangles with a big area have a bigger
568         // weighting on the vertex normal than triangles with a small area
569         // to do so, just add the 'normals' together (the bigger the area
570         // the greater the length of the normal is
571         element = elements;
572         for (i = 0; i < numtriangles; i++, element += 3)
573         {
574                 TriangleNormal(
575                         vertex3f + element[0] * 3,
576                         vertex3f + element[1] * 3,
577                         vertex3f + element[2] * 3,
578                         areaNormal
579                         );
580
581                 if (!areaweighting)
582                         VectorNormalize(areaNormal);
583
584                 for (j = 0;j < 3;j++)
585                 {
586                         vectorNormal = normal3f + element[j] * 3;
587                         vectorNormal[0] += areaNormal[0];
588                         vectorNormal[1] += areaNormal[1];
589                         vectorNormal[2] += areaNormal[2];
590                 }
591         }
592         // and just normalize the accumulated vertex normal in the end
593         vectorNormal = normal3f + 3 * firstvertex;
594         for (i = 0; i < numvertices; i++, vectorNormal += 3)
595                 VectorNormalize(vectorNormal);
596 }
597
598 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)
599 {
600         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
601         // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
602         // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
603
604         // 6 multiply, 9 subtract
605         VectorSubtract(v1, v0, v10);
606         VectorSubtract(v2, v0, v20);
607         normal3f[0] = v20[1] * v10[2] - v20[2] * v10[1];
608         normal3f[1] = v20[2] * v10[0] - v20[0] * v10[2];
609         normal3f[2] = v20[0] * v10[1] - v20[1] * v10[0];
610         // 12 multiply, 10 subtract
611         tc10[1] = tc1[1] - tc0[1];
612         tc20[1] = tc2[1] - tc0[1];
613         svector3f[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
614         svector3f[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
615         svector3f[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
616         tc10[0] = tc1[0] - tc0[0];
617         tc20[0] = tc2[0] - tc0[0];
618         tvector3f[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
619         tvector3f[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
620         tvector3f[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
621         // 12 multiply, 4 add, 6 subtract
622         f = DotProduct(svector3f, normal3f);
623         svector3f[0] -= f * normal3f[0];
624         svector3f[1] -= f * normal3f[1];
625         svector3f[2] -= f * normal3f[2];
626         f = DotProduct(tvector3f, normal3f);
627         tvector3f[0] -= f * normal3f[0];
628         tvector3f[1] -= f * normal3f[1];
629         tvector3f[2] -= f * normal3f[2];
630         // if texture is mapped the wrong way (counterclockwise), the tangents
631         // have to be flipped, this is detected by calculating a normal from the
632         // two tangents, and seeing if it is opposite the surface normal
633         // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
634         CrossProduct(tvector3f, svector3f, tangentcross);
635         if (DotProduct(tangentcross, normal3f) < 0)
636         {
637                 VectorNegate(svector3f, svector3f);
638                 VectorNegate(tvector3f, tvector3f);
639         }
640 }
641
642 // warning: this is a very expensive function!
643 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)
644 {
645         int i, tnum;
646         float sdir[3], tdir[3], normal[3], *sv, *tv;
647         const float *v0, *v1, *v2, *tc0, *tc1, *tc2, *n;
648         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
649         const int *e;
650         // clear the vectors
651         memset(svector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
652         memset(tvector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
653         // process each vertex of each triangle and accumulate the results
654         for (tnum = 0, e = elements;tnum < numtriangles;tnum++, e += 3)
655         {
656                 v0 = vertex3f + e[0] * 3;
657                 v1 = vertex3f + e[1] * 3;
658                 v2 = vertex3f + e[2] * 3;
659                 tc0 = texcoord2f + e[0] * 2;
660                 tc1 = texcoord2f + e[1] * 2;
661                 tc2 = texcoord2f + e[2] * 2;
662
663                 // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
664                 // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
665
666                 // calculate the edge directions and surface normal
667                 // 6 multiply, 9 subtract
668                 VectorSubtract(v1, v0, v10);
669                 VectorSubtract(v2, v0, v20);
670                 normal[0] = v20[1] * v10[2] - v20[2] * v10[1];
671                 normal[1] = v20[2] * v10[0] - v20[0] * v10[2];
672                 normal[2] = v20[0] * v10[1] - v20[1] * v10[0];
673
674                 // calculate the tangents
675                 // 12 multiply, 10 subtract
676                 tc10[1] = tc1[1] - tc0[1];
677                 tc20[1] = tc2[1] - tc0[1];
678                 sdir[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
679                 sdir[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
680                 sdir[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
681                 tc10[0] = tc1[0] - tc0[0];
682                 tc20[0] = tc2[0] - tc0[0];
683                 tdir[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
684                 tdir[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
685                 tdir[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
686
687                 // if texture is mapped the wrong way (counterclockwise), the tangents
688                 // have to be flipped, this is detected by calculating a normal from the
689                 // two tangents, and seeing if it is opposite the surface normal
690                 // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
691                 CrossProduct(tdir, sdir, tangentcross);
692                 if (DotProduct(tangentcross, normal) < 0)
693                 {
694                         VectorNegate(sdir, sdir);
695                         VectorNegate(tdir, tdir);
696                 }
697
698                 if (!areaweighting)
699                 {
700                         VectorNormalize(sdir);
701                         VectorNormalize(tdir);
702                 }
703                 for (i = 0;i < 3;i++)
704                 {
705                         VectorAdd(svector3f + e[i]*3, sdir, svector3f + e[i]*3);
706                         VectorAdd(tvector3f + e[i]*3, tdir, tvector3f + e[i]*3);
707                 }
708         }
709         // make the tangents completely perpendicular to the surface normal, and
710         // then normalize them
711         // 16 assignments, 2 divide, 2 sqrt, 2 negates, 14 adds, 24 multiplies
712         for (i = 0, sv = svector3f + 3 * firstvertex, tv = tvector3f + 3 * firstvertex, n = normal3f + 3 * firstvertex;i < numvertices;i++, sv += 3, tv += 3, n += 3)
713         {
714                 f = -DotProduct(sv, n);
715                 VectorMA(sv, f, n, sv);
716                 VectorNormalize(sv);
717                 f = -DotProduct(tv, n);
718                 VectorMA(tv, f, n, tv);
719                 VectorNormalize(tv);
720         }
721 }
722
723 void Mod_AllocSurfMesh(mempool_t *mempool, int numvertices, int numtriangles, qboolean lightmapoffsets, qboolean vertexcolors, qboolean neighbors)
724 {
725         unsigned char *data;
726         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));
727         loadmodel->surfmesh.num_vertices = numvertices;
728         loadmodel->surfmesh.num_triangles = numtriangles;
729         if (loadmodel->surfmesh.num_vertices)
730         {
731                 loadmodel->surfmesh.data_vertex3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
732                 loadmodel->surfmesh.data_svector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
733                 loadmodel->surfmesh.data_tvector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
734                 loadmodel->surfmesh.data_normal3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
735                 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
736                 loadmodel->surfmesh.data_texcoordlightmap2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
737                 if (vertexcolors)
738                         loadmodel->surfmesh.data_lightmapcolor4f = (float *)data, data += sizeof(float[4]) * loadmodel->surfmesh.num_vertices;
739                 if (lightmapoffsets)
740                         loadmodel->surfmesh.data_lightmapoffsets = (int *)data, data += sizeof(int) * loadmodel->surfmesh.num_vertices;
741         }
742         if (loadmodel->surfmesh.num_triangles)
743         {
744                 loadmodel->surfmesh.data_element3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
745                 if (neighbors)
746                         loadmodel->surfmesh.data_neighbor3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
747         }
748 }
749
750 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)
751 {
752         shadowmesh_t *newmesh;
753         unsigned char *data;
754         int size;
755         size = sizeof(shadowmesh_t);
756         size += maxverts * sizeof(float[3]);
757         if (light)
758                 size += maxverts * sizeof(float[11]);
759         size += maxtriangles * sizeof(int[3]);
760         if (neighbors)
761                 size += maxtriangles * sizeof(int[3]);
762         if (expandable)
763                 size += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *) + maxverts * sizeof(shadowmeshvertexhash_t);
764         data = (unsigned char *)Mem_Alloc(mempool, size);
765         newmesh = (shadowmesh_t *)data;data += sizeof(*newmesh);
766         newmesh->map_diffuse = map_diffuse;
767         newmesh->map_specular = map_specular;
768         newmesh->map_normal = map_normal;
769         newmesh->maxverts = maxverts;
770         newmesh->maxtriangles = maxtriangles;
771         newmesh->numverts = 0;
772         newmesh->numtriangles = 0;
773
774         newmesh->vertex3f = (float *)data;data += maxverts * sizeof(float[3]);
775         if (light)
776         {
777                 newmesh->svector3f = (float *)data;data += maxverts * sizeof(float[3]);
778                 newmesh->tvector3f = (float *)data;data += maxverts * sizeof(float[3]);
779                 newmesh->normal3f = (float *)data;data += maxverts * sizeof(float[3]);
780                 newmesh->texcoord2f = (float *)data;data += maxverts * sizeof(float[2]);
781         }
782         newmesh->element3i = (int *)data;data += maxtriangles * sizeof(int[3]);
783         if (neighbors)
784         {
785                 newmesh->neighbor3i = (int *)data;data += maxtriangles * sizeof(int[3]);
786         }
787         if (expandable)
788         {
789                 newmesh->vertexhashtable = (shadowmeshvertexhash_t **)data;data += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *);
790                 newmesh->vertexhashentries = (shadowmeshvertexhash_t *)data;data += maxverts * sizeof(shadowmeshvertexhash_t);
791         }
792         return newmesh;
793 }
794
795 shadowmesh_t *Mod_ShadowMesh_ReAlloc(mempool_t *mempool, shadowmesh_t *oldmesh, int light, int neighbors)
796 {
797         shadowmesh_t *newmesh;
798         newmesh = Mod_ShadowMesh_Alloc(mempool, oldmesh->numverts, oldmesh->numtriangles, oldmesh->map_diffuse, oldmesh->map_specular, oldmesh->map_normal, light, neighbors, false);
799         newmesh->numverts = oldmesh->numverts;
800         newmesh->numtriangles = oldmesh->numtriangles;
801
802         memcpy(newmesh->vertex3f, oldmesh->vertex3f, oldmesh->numverts * sizeof(float[3]));
803         if (newmesh->svector3f && oldmesh->svector3f)
804         {
805                 memcpy(newmesh->svector3f, oldmesh->svector3f, oldmesh->numverts * sizeof(float[3]));
806                 memcpy(newmesh->tvector3f, oldmesh->tvector3f, oldmesh->numverts * sizeof(float[3]));
807                 memcpy(newmesh->normal3f, oldmesh->normal3f, oldmesh->numverts * sizeof(float[3]));
808                 memcpy(newmesh->texcoord2f, oldmesh->texcoord2f, oldmesh->numverts * sizeof(float[2]));
809         }
810         memcpy(newmesh->element3i, oldmesh->element3i, oldmesh->numtriangles * sizeof(int[3]));
811         if (newmesh->neighbor3i && oldmesh->neighbor3i)
812                 memcpy(newmesh->neighbor3i, oldmesh->neighbor3i, oldmesh->numtriangles * sizeof(int[3]));
813         return newmesh;
814 }
815
816 int Mod_ShadowMesh_AddVertex(shadowmesh_t *mesh, float *vertex14f)
817 {
818         int hashindex, vnum;
819         shadowmeshvertexhash_t *hash;
820         // this uses prime numbers intentionally
821         hashindex = (unsigned int) (vertex14f[0] * 2003 + vertex14f[1] * 4001 + vertex14f[2] * 7919) % SHADOWMESHVERTEXHASH;
822         for (hash = mesh->vertexhashtable[hashindex];hash;hash = hash->next)
823         {
824                 vnum = (hash - mesh->vertexhashentries);
825                 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]))
826                  && (mesh->svector3f == NULL || (mesh->svector3f[vnum * 3 + 0] == vertex14f[3] && mesh->svector3f[vnum * 3 + 1] == vertex14f[4] && mesh->svector3f[vnum * 3 + 2] == vertex14f[5]))
827                  && (mesh->tvector3f == NULL || (mesh->tvector3f[vnum * 3 + 0] == vertex14f[6] && mesh->tvector3f[vnum * 3 + 1] == vertex14f[7] && mesh->tvector3f[vnum * 3 + 2] == vertex14f[8]))
828                  && (mesh->normal3f == NULL || (mesh->normal3f[vnum * 3 + 0] == vertex14f[9] && mesh->normal3f[vnum * 3 + 1] == vertex14f[10] && mesh->normal3f[vnum * 3 + 2] == vertex14f[11]))
829                  && (mesh->texcoord2f == NULL || (mesh->texcoord2f[vnum * 2 + 0] == vertex14f[12] && mesh->texcoord2f[vnum * 2 + 1] == vertex14f[13])))
830                         return hash - mesh->vertexhashentries;
831         }
832         vnum = mesh->numverts++;
833         hash = mesh->vertexhashentries + vnum;
834         hash->next = mesh->vertexhashtable[hashindex];
835         mesh->vertexhashtable[hashindex] = hash;
836         if (mesh->vertex3f) {mesh->vertex3f[vnum * 3 + 0] = vertex14f[0];mesh->vertex3f[vnum * 3 + 1] = vertex14f[1];mesh->vertex3f[vnum * 3 + 2] = vertex14f[2];}
837         if (mesh->svector3f) {mesh->svector3f[vnum * 3 + 0] = vertex14f[3];mesh->svector3f[vnum * 3 + 1] = vertex14f[4];mesh->svector3f[vnum * 3 + 2] = vertex14f[5];}
838         if (mesh->tvector3f) {mesh->tvector3f[vnum * 3 + 0] = vertex14f[6];mesh->tvector3f[vnum * 3 + 1] = vertex14f[7];mesh->tvector3f[vnum * 3 + 2] = vertex14f[8];}
839         if (mesh->normal3f) {mesh->normal3f[vnum * 3 + 0] = vertex14f[9];mesh->normal3f[vnum * 3 + 1] = vertex14f[10];mesh->normal3f[vnum * 3 + 2] = vertex14f[11];}
840         if (mesh->texcoord2f) {mesh->texcoord2f[vnum * 2 + 0] = vertex14f[12];mesh->texcoord2f[vnum * 2 + 1] = vertex14f[13];}
841         return vnum;
842 }
843
844 void Mod_ShadowMesh_AddTriangle(mempool_t *mempool, shadowmesh_t *mesh, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, float *vertex14f)
845 {
846         if (mesh->numtriangles == 0)
847         {
848                 // set the properties on this empty mesh to be more favorable...
849                 // (note: this case only occurs for the first triangle added to a new mesh chain)
850                 mesh->map_diffuse = map_diffuse;
851                 mesh->map_specular = map_specular;
852                 mesh->map_normal = map_normal;
853         }
854         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)
855         {
856                 if (mesh->next == NULL)
857                         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);
858                 mesh = mesh->next;
859         }
860         mesh->element3i[mesh->numtriangles * 3 + 0] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 0);
861         mesh->element3i[mesh->numtriangles * 3 + 1] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 1);
862         mesh->element3i[mesh->numtriangles * 3 + 2] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 2);
863         mesh->numtriangles++;
864 }
865
866 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)
867 {
868         int i, j, e;
869         float vbuf[3*14], *v;
870         memset(vbuf, 0, sizeof(vbuf));
871         for (i = 0;i < numtris;i++)
872         {
873                 for (j = 0, v = vbuf;j < 3;j++, v += 14)
874                 {
875                         e = *element3i++;
876                         if (vertex3f)
877                         {
878                                 v[0] = vertex3f[e * 3 + 0];
879                                 v[1] = vertex3f[e * 3 + 1];
880                                 v[2] = vertex3f[e * 3 + 2];
881                         }
882                         if (svector3f)
883                         {
884                                 v[3] = svector3f[e * 3 + 0];
885                                 v[4] = svector3f[e * 3 + 1];
886                                 v[5] = svector3f[e * 3 + 2];
887                         }
888                         if (tvector3f)
889                         {
890                                 v[6] = tvector3f[e * 3 + 0];
891                                 v[7] = tvector3f[e * 3 + 1];
892                                 v[8] = tvector3f[e * 3 + 2];
893                         }
894                         if (normal3f)
895                         {
896                                 v[9] = normal3f[e * 3 + 0];
897                                 v[10] = normal3f[e * 3 + 1];
898                                 v[11] = normal3f[e * 3 + 2];
899                         }
900                         if (texcoord2f)
901                         {
902                                 v[12] = texcoord2f[e * 2 + 0];
903                                 v[13] = texcoord2f[e * 2 + 1];
904                         }
905                 }
906                 Mod_ShadowMesh_AddTriangle(mempool, mesh, map_diffuse, map_specular, map_normal, vbuf);
907         }
908 }
909
910 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)
911 {
912         return Mod_ShadowMesh_Alloc(mempool, maxverts, maxtriangles, map_diffuse, map_specular, map_normal, light, neighbors, expandable);
913 }
914
915 static void Mod_ShadowMesh_CreateVBOs(shadowmesh_t *mesh)
916 {
917         if (!gl_support_arb_vertex_buffer_object)
918                 return;
919
920         // element buffer is easy because it's just one array
921         if (mesh->numtriangles)
922                 mesh->ebo = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, mesh->element3i, mesh->numtriangles * sizeof(int[3]), "shadowmesh");
923
924         // vertex buffer is several arrays and we put them in the same buffer
925         //
926         // is this wise?  the texcoordtexture2f array is used with dynamic
927         // vertex/svector/tvector/normal when rendering animated models, on the
928         // other hand animated models don't use a lot of vertices anyway...
929         if (mesh->numverts)
930         {
931                 size_t size;
932                 unsigned char *mem;
933                 size = 0;
934                 mesh->vbooffset_vertex3f           = size;if (mesh->vertex3f          ) size += mesh->numverts * sizeof(float[3]);
935                 mesh->vbooffset_svector3f          = size;if (mesh->svector3f         ) size += mesh->numverts * sizeof(float[3]);
936                 mesh->vbooffset_tvector3f          = size;if (mesh->tvector3f         ) size += mesh->numverts * sizeof(float[3]);
937                 mesh->vbooffset_normal3f           = size;if (mesh->normal3f          ) size += mesh->numverts * sizeof(float[3]);
938                 mesh->vbooffset_texcoord2f         = size;if (mesh->texcoord2f        ) size += mesh->numverts * sizeof(float[2]);
939                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
940                 if (mesh->vertex3f          ) memcpy(mem + mesh->vbooffset_vertex3f          , mesh->vertex3f          , mesh->numverts * sizeof(float[3]));
941                 if (mesh->svector3f         ) memcpy(mem + mesh->vbooffset_svector3f         , mesh->svector3f         , mesh->numverts * sizeof(float[3]));
942                 if (mesh->tvector3f         ) memcpy(mem + mesh->vbooffset_tvector3f         , mesh->tvector3f         , mesh->numverts * sizeof(float[3]));
943                 if (mesh->normal3f          ) memcpy(mem + mesh->vbooffset_normal3f          , mesh->normal3f          , mesh->numverts * sizeof(float[3]));
944                 if (mesh->texcoord2f        ) memcpy(mem + mesh->vbooffset_texcoord2f        , mesh->texcoord2f        , mesh->numverts * sizeof(float[2]));
945                 mesh->vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, "shadowmesh");
946                 Mem_Free(mem);
947         }
948 }
949
950 shadowmesh_t *Mod_ShadowMesh_Finish(mempool_t *mempool, shadowmesh_t *firstmesh, qboolean light, qboolean neighbors, qboolean createvbo)
951 {
952         shadowmesh_t *mesh, *newmesh, *nextmesh;
953         // reallocate meshs to conserve space
954         for (mesh = firstmesh, firstmesh = NULL;mesh;mesh = nextmesh)
955         {
956                 nextmesh = mesh->next;
957                 if (mesh->numverts >= 3 && mesh->numtriangles >= 1)
958                 {
959                         newmesh = Mod_ShadowMesh_ReAlloc(mempool, mesh, light, neighbors);
960                         newmesh->next = firstmesh;
961                         firstmesh = newmesh;
962                         if (createvbo)
963                                 Mod_ShadowMesh_CreateVBOs(newmesh);
964                 }
965                 Mem_Free(mesh);
966         }
967         return firstmesh;
968 }
969
970 void Mod_ShadowMesh_CalcBBox(shadowmesh_t *firstmesh, vec3_t mins, vec3_t maxs, vec3_t center, float *radius)
971 {
972         int i;
973         shadowmesh_t *mesh;
974         vec3_t nmins, nmaxs, ncenter, temp;
975         float nradius2, dist2, *v;
976         VectorClear(nmins);
977         VectorClear(nmaxs);
978         // calculate bbox
979         for (mesh = firstmesh;mesh;mesh = mesh->next)
980         {
981                 if (mesh == firstmesh)
982                 {
983                         VectorCopy(mesh->vertex3f, nmins);
984                         VectorCopy(mesh->vertex3f, nmaxs);
985                 }
986                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
987                 {
988                         if (nmins[0] > v[0]) nmins[0] = v[0];if (nmaxs[0] < v[0]) nmaxs[0] = v[0];
989                         if (nmins[1] > v[1]) nmins[1] = v[1];if (nmaxs[1] < v[1]) nmaxs[1] = v[1];
990                         if (nmins[2] > v[2]) nmins[2] = v[2];if (nmaxs[2] < v[2]) nmaxs[2] = v[2];
991                 }
992         }
993         // calculate center and radius
994         ncenter[0] = (nmins[0] + nmaxs[0]) * 0.5f;
995         ncenter[1] = (nmins[1] + nmaxs[1]) * 0.5f;
996         ncenter[2] = (nmins[2] + nmaxs[2]) * 0.5f;
997         nradius2 = 0;
998         for (mesh = firstmesh;mesh;mesh = mesh->next)
999         {
1000                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1001                 {
1002                         VectorSubtract(v, ncenter, temp);
1003                         dist2 = DotProduct(temp, temp);
1004                         if (nradius2 < dist2)
1005                                 nradius2 = dist2;
1006                 }
1007         }
1008         // return data
1009         if (mins)
1010                 VectorCopy(nmins, mins);
1011         if (maxs)
1012                 VectorCopy(nmaxs, maxs);
1013         if (center)
1014                 VectorCopy(ncenter, center);
1015         if (radius)
1016                 *radius = sqrt(nradius2);
1017 }
1018
1019 void Mod_ShadowMesh_Free(shadowmesh_t *mesh)
1020 {
1021         shadowmesh_t *nextmesh;
1022         for (;mesh;mesh = nextmesh)
1023         {
1024                 if (mesh->ebo)
1025                         R_Mesh_DestroyBufferObject(mesh->ebo);
1026                 if (mesh->vbo)
1027                         R_Mesh_DestroyBufferObject(mesh->vbo);
1028                 nextmesh = mesh->next;
1029                 Mem_Free(mesh);
1030         }
1031 }
1032
1033 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)
1034 {
1035         float v[3], tc[3];
1036         v[0] = ix;
1037         v[1] = iy;
1038         if (ix >= 0 && iy >= 0 && ix < imagewidth && iy < imageheight)
1039                 v[2] = (imagepixels[((iy*imagewidth)+ix)*4+0] + imagepixels[((iy*imagewidth)+ix)*4+1] + imagepixels[((iy*imagewidth)+ix)*4+2]) * (1.0f / 765.0f);
1040         else
1041                 v[2] = 0;
1042         Matrix4x4_Transform(pixelstepmatrix, v, vertex3f);
1043         Matrix4x4_Transform(pixeltexturestepmatrix, v, tc);
1044         texcoord2f[0] = tc[0];
1045         texcoord2f[1] = tc[1];
1046 }
1047
1048 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)
1049 {
1050         float vup[3], vdown[3], vleft[3], vright[3];
1051         float tcup[3], tcdown[3], tcleft[3], tcright[3];
1052         float sv[3], tv[3], nl[3];
1053         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, pixelstepmatrix, pixeltexturestepmatrix);
1054         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy - 1, vup, tcup, pixelstepmatrix, pixeltexturestepmatrix);
1055         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy + 1, vdown, tcdown, pixelstepmatrix, pixeltexturestepmatrix);
1056         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix - 1, iy, vleft, tcleft, pixelstepmatrix, pixeltexturestepmatrix);
1057         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix + 1, iy, vright, tcright, pixelstepmatrix, pixeltexturestepmatrix);
1058         Mod_BuildBumpVectors(vertex3f, vup, vright, texcoord2f, tcup, tcright, svector3f, tvector3f, normal3f);
1059         Mod_BuildBumpVectors(vertex3f, vright, vdown, texcoord2f, tcright, tcdown, sv, tv, nl);
1060         VectorAdd(svector3f, sv, svector3f);
1061         VectorAdd(tvector3f, tv, tvector3f);
1062         VectorAdd(normal3f, nl, normal3f);
1063         Mod_BuildBumpVectors(vertex3f, vdown, vleft, texcoord2f, tcdown, tcleft, sv, tv, nl);
1064         VectorAdd(svector3f, sv, svector3f);
1065         VectorAdd(tvector3f, tv, tvector3f);
1066         VectorAdd(normal3f, nl, normal3f);
1067         Mod_BuildBumpVectors(vertex3f, vleft, vup, texcoord2f, tcleft, tcup, sv, tv, nl);
1068         VectorAdd(svector3f, sv, svector3f);
1069         VectorAdd(tvector3f, tv, tvector3f);
1070         VectorAdd(normal3f, nl, normal3f);
1071 }
1072
1073 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)
1074 {
1075         int x, y, ix, iy, *e;
1076         e = element3i;
1077         for (y = 0;y < height;y++)
1078         {
1079                 for (x = 0;x < width;x++)
1080                 {
1081                         e[0] = (y + 1) * (width + 1) + (x + 0);
1082                         e[1] = (y + 0) * (width + 1) + (x + 0);
1083                         e[2] = (y + 1) * (width + 1) + (x + 1);
1084                         e[3] = (y + 0) * (width + 1) + (x + 0);
1085                         e[4] = (y + 0) * (width + 1) + (x + 1);
1086                         e[5] = (y + 1) * (width + 1) + (x + 1);
1087                         e += 6;
1088                 }
1089         }
1090         Mod_BuildTriangleNeighbors(neighbor3i, element3i, width*height*2);
1091         for (y = 0, iy = y1;y < height + 1;y++, iy++)
1092                 for (x = 0, ix = x1;x < width + 1;x++, ix++, vertex3f += 3, texcoord2f += 2, svector3f += 3, tvector3f += 3, normal3f += 3)
1093                         Mod_GetTerrainVertexFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, svector3f, tvector3f, normal3f, pixelstepmatrix, pixeltexturestepmatrix);
1094 }
1095
1096 q3wavefunc_t Mod_LoadQ3Shaders_EnumerateWaveFunc(const char *s)
1097 {
1098         if (!strcasecmp(s, "sin"))             return Q3WAVEFUNC_SIN;
1099         if (!strcasecmp(s, "square"))          return Q3WAVEFUNC_SQUARE;
1100         if (!strcasecmp(s, "triangle"))        return Q3WAVEFUNC_TRIANGLE;
1101         if (!strcasecmp(s, "sawtooth"))        return Q3WAVEFUNC_SAWTOOTH;
1102         if (!strcasecmp(s, "inversesawtooth")) return Q3WAVEFUNC_INVERSESAWTOOTH;
1103         if (!strcasecmp(s, "noise"))           return Q3WAVEFUNC_NOISE;
1104         Con_DPrintf("Mod_LoadQ3Shaders: unknown wavefunc %s\n", s);
1105         return Q3WAVEFUNC_NONE;
1106 }
1107
1108 void Mod_LoadQ3Shaders(void)
1109 {
1110         int j;
1111         int fileindex;
1112         fssearch_t *search;
1113         char *f;
1114         const char *text;
1115         q3shaderinfo_t *shader;
1116         q3shaderinfo_layer_t *layer;
1117         int numparameters;
1118         char parameter[TEXTURE_MAXFRAMES + 4][Q3PATHLENGTH];
1119         q3shaders_numshaders = 0;
1120         search = FS_Search("scripts/*.shader", true, false);
1121         if (!search)
1122                 return;
1123         for (fileindex = 0;fileindex < search->numfilenames;fileindex++)
1124         {
1125                 text = f = (char *)FS_LoadFile(search->filenames[fileindex], tempmempool, false, NULL);
1126                 if (!f)
1127                         continue;
1128                 while (COM_ParseToken_QuakeC(&text, false))
1129                 {
1130                         if (q3shaders_numshaders >= Q3SHADER_MAXSHADERS)
1131                         {
1132                                 Con_Printf("Mod_LoadQ3Shaders: too many shaders!\n");
1133                                 break;
1134                         }
1135                         shader = q3shaders_shaders + q3shaders_numshaders++;
1136
1137                         memset(shader, 0, sizeof(*shader));
1138                         shader->reflectmin = 0;
1139                         shader->reflectmax = 1;
1140                         shader->refractfactor = 1;
1141                         Vector4Set(shader->refractcolor4f, 1, 1, 1, 1);
1142                         shader->reflectfactor = 1;
1143                         Vector4Set(shader->reflectcolor4f, 1, 1, 1, 1);
1144
1145                         strlcpy(shader->name, com_token, sizeof(shader->name));
1146                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1147                         {
1148                                 Con_Printf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[fileindex], com_token);
1149                                 break;
1150                         }
1151                         while (COM_ParseToken_QuakeC(&text, false))
1152                         {
1153                                 if (!strcasecmp(com_token, "}"))
1154                                         break;
1155                                 if (!strcasecmp(com_token, "{"))
1156                                 {
1157                                         static q3shaderinfo_layer_t dummy;
1158                                         if (shader->numlayers < Q3SHADER_MAXLAYERS)
1159                                         {
1160                                                 layer = shader->layers + shader->numlayers++;
1161                                         }
1162                                         else
1163                                         {
1164                                                 // parse and process it anyway, just don't store it (so a map $lightmap or such stuff still is found)
1165                                                 memset(&dummy, 0, sizeof(dummy));
1166                                                 layer = &dummy;
1167                                         }
1168                                         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1169                                         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1170                                         layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1171                                         layer->blendfunc[0] = GL_ONE;
1172                                         layer->blendfunc[1] = GL_ZERO;
1173                                         while (COM_ParseToken_QuakeC(&text, false))
1174                                         {
1175                                                 if (!strcasecmp(com_token, "}"))
1176                                                         break;
1177                                                 if (!strcasecmp(com_token, "\n"))
1178                                                         continue;
1179                                                 numparameters = 0;
1180                                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1181                                                 {
1182                                                         if (j < TEXTURE_MAXFRAMES + 4)
1183                                                         {
1184                                                                 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1185                                                                 numparameters = j + 1;
1186                                                         }
1187                                                         if (!COM_ParseToken_QuakeC(&text, true))
1188                                                                 break;
1189                                                 }
1190                                                 for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1191                                                         parameter[j][0] = 0;
1192                                                 if (developer.integer >= 100)
1193                                                 {
1194                                                         Con_Printf("%s %i: ", shader->name, shader->numlayers - 1);
1195                                                         for (j = 0;j < numparameters;j++)
1196                                                                 Con_Printf(" %s", parameter[j]);
1197                                                         Con_Print("\n");
1198                                                 }
1199                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "blendfunc"))
1200                                                 {
1201                                                         if (numparameters == 2)
1202                                                         {
1203                                                                 if (!strcasecmp(parameter[1], "add"))
1204                                                                 {
1205                                                                         layer->blendfunc[0] = GL_ONE;
1206                                                                         layer->blendfunc[1] = GL_ONE;
1207                                                                 }
1208                                                                 else if (!strcasecmp(parameter[1], "filter"))
1209                                                                 {
1210                                                                         layer->blendfunc[0] = GL_DST_COLOR;
1211                                                                         layer->blendfunc[1] = GL_ZERO;
1212                                                                 }
1213                                                                 else if (!strcasecmp(parameter[1], "blend"))
1214                                                                 {
1215                                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1216                                                                         layer->blendfunc[1] = GL_ONE_MINUS_SRC_ALPHA;
1217                                                                 }
1218                                                         }
1219                                                         else if (numparameters == 3)
1220                                                         {
1221                                                                 int k;
1222                                                                 for (k = 0;k < 2;k++)
1223                                                                 {
1224                                                                         if (!strcasecmp(parameter[k+1], "GL_ONE"))
1225                                                                                 layer->blendfunc[k] = GL_ONE;
1226                                                                         else if (!strcasecmp(parameter[k+1], "GL_ZERO"))
1227                                                                                 layer->blendfunc[k] = GL_ZERO;
1228                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_COLOR"))
1229                                                                                 layer->blendfunc[k] = GL_SRC_COLOR;
1230                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_ALPHA"))
1231                                                                                 layer->blendfunc[k] = GL_SRC_ALPHA;
1232                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_COLOR"))
1233                                                                                 layer->blendfunc[k] = GL_DST_COLOR;
1234                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_ALPHA"))
1235                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1236                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_COLOR"))
1237                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_COLOR;
1238                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_ALPHA"))
1239                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_ALPHA;
1240                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_COLOR"))
1241                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_COLOR;
1242                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_ALPHA"))
1243                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1244                                                                         else
1245                                                                                 layer->blendfunc[k] = GL_ONE; // default in case of parsing error
1246                                                                 }
1247                                                         }
1248                                                 }
1249                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
1250                                                         layer->alphatest = true;
1251                                                 if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
1252                                                 {
1253                                                         if (!strcasecmp(parameter[0], "clampmap"))
1254                                                                 layer->clampmap = true;
1255                                                         layer->numframes = 1;
1256                                                         layer->framerate = 1;
1257                                                         strlcpy(layer->texturename[0], parameter[1], sizeof(layer->texturename));
1258                                                         if (!strcasecmp(parameter[1], "$lightmap"))
1259                                                                 shader->lighting = true;
1260                                                 }
1261                                                 else if (numparameters >= 3 && (!strcasecmp(parameter[0], "animmap") || !strcasecmp(parameter[0], "animclampmap")))
1262                                                 {
1263                                                         int i;
1264                                                         layer->numframes = min(numparameters - 2, TEXTURE_MAXFRAMES);
1265                                                         layer->framerate = atof(parameter[1]);
1266                                                         for (i = 0;i < layer->numframes;i++)
1267                                                                 strlcpy(layer->texturename[i], parameter[i + 2], sizeof(layer->texturename));
1268                                                 }
1269                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "rgbgen"))
1270                                                 {
1271                                                         int i;
1272                                                         for (i = 0;i < numparameters - 2 && i < Q3RGBGEN_MAXPARMS;i++)
1273                                                                 layer->rgbgen.parms[i] = atof(parameter[i+2]);
1274                                                              if (!strcasecmp(parameter[1], "identity"))         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1275                                                         else if (!strcasecmp(parameter[1], "const"))            layer->rgbgen.rgbgen = Q3RGBGEN_CONST;
1276                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->rgbgen.rgbgen = Q3RGBGEN_ENTITY;
1277                                                         else if (!strcasecmp(parameter[1], "exactvertex"))      layer->rgbgen.rgbgen = Q3RGBGEN_EXACTVERTEX;
1278                                                         else if (!strcasecmp(parameter[1], "identitylighting")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITYLIGHTING;
1279                                                         else if (!strcasecmp(parameter[1], "lightingdiffuse"))  layer->rgbgen.rgbgen = Q3RGBGEN_LIGHTINGDIFFUSE;
1280                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSENTITY;
1281                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSVERTEX;
1282                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->rgbgen.rgbgen = Q3RGBGEN_VERTEX;
1283                                                         else if (!strcasecmp(parameter[1], "wave"))
1284                                                         {
1285                                                                 layer->rgbgen.rgbgen = Q3RGBGEN_WAVE;
1286                                                                 layer->rgbgen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1287                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1288                                                                         layer->rgbgen.waveparms[i] = atof(parameter[i+3]);
1289                                                         }
1290                                                         else Con_DPrintf("%s parsing warning: unknown rgbgen %s\n", search->filenames[fileindex], parameter[1]);
1291                                                 }
1292                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphagen"))
1293                                                 {
1294                                                         int i;
1295                                                         for (i = 0;i < numparameters - 2 && i < Q3ALPHAGEN_MAXPARMS;i++)
1296                                                                 layer->alphagen.parms[i] = atof(parameter[i+2]);
1297                                                              if (!strcasecmp(parameter[1], "identity"))         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1298                                                         else if (!strcasecmp(parameter[1], "const"))            layer->alphagen.alphagen = Q3ALPHAGEN_CONST;
1299                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->alphagen.alphagen = Q3ALPHAGEN_ENTITY;
1300                                                         else if (!strcasecmp(parameter[1], "lightingspecular")) layer->alphagen.alphagen = Q3ALPHAGEN_LIGHTINGSPECULAR;
1301                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSENTITY;
1302                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSVERTEX;
1303                                                         else if (!strcasecmp(parameter[1], "portal"))           layer->alphagen.alphagen = Q3ALPHAGEN_PORTAL;
1304                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->alphagen.alphagen = Q3ALPHAGEN_VERTEX;
1305                                                         else if (!strcasecmp(parameter[1], "wave"))
1306                                                         {
1307                                                                 layer->alphagen.alphagen = Q3RGBGEN_WAVE;
1308                                                                 layer->alphagen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1309                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1310                                                                         layer->alphagen.waveparms[i] = atof(parameter[i+3]);
1311                                                         }
1312                                                         else Con_DPrintf("%s parsing warning: unknown alphagen %s\n", search->filenames[fileindex], parameter[1]);
1313                                                 }
1314                                                 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "texgen") || !strcasecmp(parameter[0], "tcgen")))
1315                                                 {
1316                                                         int i;
1317                                                         // observed values: tcgen environment
1318                                                         // no other values have been observed in real shaders
1319                                                         for (i = 0;i < numparameters - 2 && i < Q3TCGEN_MAXPARMS;i++)
1320                                                                 layer->tcgen.parms[i] = atof(parameter[i+2]);
1321                                                              if (!strcasecmp(parameter[1], "base"))        layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1322                                                         else if (!strcasecmp(parameter[1], "texture"))     layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1323                                                         else if (!strcasecmp(parameter[1], "environment")) layer->tcgen.tcgen = Q3TCGEN_ENVIRONMENT;
1324                                                         else if (!strcasecmp(parameter[1], "lightmap"))    layer->tcgen.tcgen = Q3TCGEN_LIGHTMAP;
1325                                                         else if (!strcasecmp(parameter[1], "vector"))      layer->tcgen.tcgen = Q3TCGEN_VECTOR;
1326                                                         else Con_DPrintf("%s parsing warning: unknown tcgen mode %s\n", search->filenames[fileindex], parameter[1]);
1327                                                 }
1328                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "tcmod"))
1329                                                 {
1330                                                         int i, tcmodindex;
1331                                                         // observed values:
1332                                                         // tcmod rotate #
1333                                                         // tcmod scale # #
1334                                                         // tcmod scroll # #
1335                                                         // tcmod stretch sin # # # #
1336                                                         // tcmod stretch triangle # # # #
1337                                                         // tcmod transform # # # # # #
1338                                                         // tcmod turb # # # #
1339                                                         // tcmod turb sin # # # #  (this is bogus)
1340                                                         // no other values have been observed in real shaders
1341                                                         for (tcmodindex = 0;tcmodindex < Q3MAXTCMODS;tcmodindex++)
1342                                                                 if (!layer->tcmods[tcmodindex].tcmod)
1343                                                                         break;
1344                                                         if (tcmodindex < Q3MAXTCMODS)
1345                                                         {
1346                                                                 for (i = 0;i < numparameters - 2 && i < Q3TCMOD_MAXPARMS;i++)
1347                                                                         layer->tcmods[tcmodindex].parms[i] = atof(parameter[i+2]);
1348                                                                          if (!strcasecmp(parameter[1], "entitytranslate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ENTITYTRANSLATE;
1349                                                                 else if (!strcasecmp(parameter[1], "rotate"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ROTATE;
1350                                                                 else if (!strcasecmp(parameter[1], "scale"))           layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCALE;
1351                                                                 else if (!strcasecmp(parameter[1], "scroll"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCROLL;
1352                                                                 else if (!strcasecmp(parameter[1], "stretch"))
1353                                                                 {
1354                                                                         layer->tcmods[tcmodindex].tcmod = Q3TCMOD_STRETCH;
1355                                                                         layer->tcmods[tcmodindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1356                                                                         for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1357                                                                                 layer->tcmods[tcmodindex].waveparms[i] = atof(parameter[i+3]);
1358                                                                 }
1359                                                                 else if (!strcasecmp(parameter[1], "transform"))       layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TRANSFORM;
1360                                                                 else if (!strcasecmp(parameter[1], "turb"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TURBULENT;
1361                                                                 else Con_DPrintf("%s parsing warning: unknown tcmod mode %s\n", search->filenames[fileindex], parameter[1]);
1362                                                         }
1363                                                         else
1364                                                                 Con_DPrintf("%s parsing warning: too many tcmods on one layer\n", search->filenames[fileindex]);
1365                                                 }
1366                                                 // break out a level if it was a closing brace (not using the character here to not confuse vim)
1367                                                 if (!strcasecmp(com_token, "}"))
1368                                                         break;
1369                                         }
1370                                         if (layer->rgbgen.rgbgen == Q3RGBGEN_LIGHTINGDIFFUSE || layer->rgbgen.rgbgen == Q3RGBGEN_VERTEX)
1371                                                 shader->lighting = true;
1372                                         if (layer->alphagen.alphagen == Q3ALPHAGEN_VERTEX)
1373                                         {
1374                                                 if (layer == shader->layers + 0)
1375                                                 {
1376                                                         // vertex controlled transparency
1377                                                         shader->vertexalpha = true;
1378                                                 }
1379                                                 else
1380                                                 {
1381                                                         // multilayer terrain shader or similar
1382                                                         shader->textureblendalpha = true;
1383                                                 }
1384                                         }
1385                                         continue;
1386                                 }
1387                                 numparameters = 0;
1388                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1389                                 {
1390                                         if (j < TEXTURE_MAXFRAMES + 4)
1391                                         {
1392                                                 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1393                                                 numparameters = j + 1;
1394                                         }
1395                                         if (!COM_ParseToken_QuakeC(&text, true))
1396                                                 break;
1397                                 }
1398                                 for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1399                                         parameter[j][0] = 0;
1400                                 if (fileindex == 0 && !strcasecmp(com_token, "}"))
1401                                         break;
1402                                 if (developer.integer >= 100)
1403                                 {
1404                                         Con_Printf("%s: ", shader->name);
1405                                         for (j = 0;j < numparameters;j++)
1406                                                 Con_Printf(" %s", parameter[j]);
1407                                         Con_Print("\n");
1408                                 }
1409                                 if (numparameters < 1)
1410                                         continue;
1411                                 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
1412                                 {
1413                                         if (!strcasecmp(parameter[1], "alphashadow"))
1414                                                 shader->surfaceparms |= Q3SURFACEPARM_ALPHASHADOW;
1415                                         else if (!strcasecmp(parameter[1], "areaportal"))
1416                                                 shader->surfaceparms |= Q3SURFACEPARM_AREAPORTAL;
1417                                         else if (!strcasecmp(parameter[1], "botclip"))
1418                                                 shader->surfaceparms |= Q3SURFACEPARM_BOTCLIP;
1419                                         else if (!strcasecmp(parameter[1], "clusterportal"))
1420                                                 shader->surfaceparms |= Q3SURFACEPARM_CLUSTERPORTAL;
1421                                         else if (!strcasecmp(parameter[1], "detail"))
1422                                                 shader->surfaceparms |= Q3SURFACEPARM_DETAIL;
1423                                         else if (!strcasecmp(parameter[1], "donotenter"))
1424                                                 shader->surfaceparms |= Q3SURFACEPARM_DONOTENTER;
1425                                         else if (!strcasecmp(parameter[1], "dust"))
1426                                                 shader->surfaceparms |= Q3SURFACEPARM_DUST;
1427                                         else if (!strcasecmp(parameter[1], "hint"))
1428                                                 shader->surfaceparms |= Q3SURFACEPARM_HINT;
1429                                         else if (!strcasecmp(parameter[1], "fog"))
1430                                                 shader->surfaceparms |= Q3SURFACEPARM_FOG;
1431                                         else if (!strcasecmp(parameter[1], "lava"))
1432                                                 shader->surfaceparms |= Q3SURFACEPARM_LAVA;
1433                                         else if (!strcasecmp(parameter[1], "lightfilter"))
1434                                                 shader->surfaceparms |= Q3SURFACEPARM_LIGHTFILTER;
1435                                         else if (!strcasecmp(parameter[1], "lightgrid"))
1436                                                 shader->surfaceparms |= Q3SURFACEPARM_LIGHTGRID;
1437                                         else if (!strcasecmp(parameter[1], "metalsteps"))
1438                                                 shader->surfaceparms |= Q3SURFACEPARM_METALSTEPS;
1439                                         else if (!strcasecmp(parameter[1], "nodamage"))
1440                                                 shader->surfaceparms |= Q3SURFACEPARM_NODAMAGE;
1441                                         else if (!strcasecmp(parameter[1], "nodlight"))
1442                                                 shader->surfaceparms |= Q3SURFACEPARM_NODLIGHT;
1443                                         else if (!strcasecmp(parameter[1], "nodraw"))
1444                                                 shader->surfaceparms |= Q3SURFACEPARM_NODRAW;
1445                                         else if (!strcasecmp(parameter[1], "nodrop"))
1446                                                 shader->surfaceparms |= Q3SURFACEPARM_NODROP;
1447                                         else if (!strcasecmp(parameter[1], "noimpact"))
1448                                                 shader->surfaceparms |= Q3SURFACEPARM_NOIMPACT;
1449                                         else if (!strcasecmp(parameter[1], "nolightmap"))
1450                                                 shader->surfaceparms |= Q3SURFACEPARM_NOLIGHTMAP;
1451                                         else if (!strcasecmp(parameter[1], "nomarks"))
1452                                                 shader->surfaceparms |= Q3SURFACEPARM_NOMARKS;
1453                                         else if (!strcasecmp(parameter[1], "nomipmaps"))
1454                                                 shader->surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1455                                         else if (!strcasecmp(parameter[1], "nonsolid"))
1456                                                 shader->surfaceparms |= Q3SURFACEPARM_NONSOLID;
1457                                         else if (!strcasecmp(parameter[1], "origin"))
1458                                                 shader->surfaceparms |= Q3SURFACEPARM_ORIGIN;
1459                                         else if (!strcasecmp(parameter[1], "playerclip"))
1460                                                 shader->surfaceparms |= Q3SURFACEPARM_PLAYERCLIP;
1461                                         else if (!strcasecmp(parameter[1], "sky"))
1462                                                 shader->surfaceparms |= Q3SURFACEPARM_SKY;
1463                                         else if (!strcasecmp(parameter[1], "slick"))
1464                                                 shader->surfaceparms |= Q3SURFACEPARM_SLICK;
1465                                         else if (!strcasecmp(parameter[1], "slime"))
1466                                                 shader->surfaceparms |= Q3SURFACEPARM_SLIME;
1467                                         else if (!strcasecmp(parameter[1], "structural"))
1468                                                 shader->surfaceparms |= Q3SURFACEPARM_STRUCTURAL;
1469                                         else if (!strcasecmp(parameter[1], "trans"))
1470                                                 shader->surfaceparms |= Q3SURFACEPARM_TRANS;
1471                                         else if (!strcasecmp(parameter[1], "water"))
1472                                                 shader->surfaceparms |= Q3SURFACEPARM_WATER;
1473                                         else if (!strcasecmp(parameter[1], "pointlight"))
1474                                                 shader->surfaceparms |= Q3SURFACEPARM_POINTLIGHT;
1475                                         else if (!strcasecmp(parameter[1], "antiportal"))
1476                                                 shader->surfaceparms |= Q3SURFACEPARM_ANTIPORTAL;
1477                                         else
1478                                                 Con_DPrintf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[fileindex], parameter[1]);
1479                                 }
1480                                 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
1481                                 {
1482                                         // some q3 skies don't have the sky parm set
1483                                         shader->surfaceparms |= Q3SURFACEPARM_SKY;
1484                                         strlcpy(shader->skyboxname, parameter[1], sizeof(shader->skyboxname));
1485                                 }
1486                                 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
1487                                 {
1488                                         // some q3 skies don't have the sky parm set
1489                                         shader->surfaceparms |= Q3SURFACEPARM_SKY;
1490                                         if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
1491                                                 strlcpy(shader->skyboxname, parameter[1], sizeof(shader->skyboxname));
1492                                 }
1493                                 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
1494                                 {
1495                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
1496                                                 shader->textureflags |= Q3TEXTUREFLAG_TWOSIDED;
1497                                 }
1498                                 else if (!strcasecmp(parameter[0], "nomipmaps"))
1499                                         shader->surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1500                                 else if (!strcasecmp(parameter[0], "nopicmip"))
1501                                         shader->textureflags |= Q3TEXTUREFLAG_NOPICMIP;
1502                                 else if (!strcasecmp(parameter[0], "polygonoffset"))
1503                                         shader->textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
1504                                 else if (!strcasecmp(parameter[0], "dp_refract") && numparameters >= 5)
1505                                 {
1506                                         shader->textureflags |= Q3TEXTUREFLAG_REFRACTION;
1507                                         shader->refractfactor = atof(parameter[1]);
1508                                         Vector4Set(shader->refractcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), 1);
1509                                 }
1510                                 else if (!strcasecmp(parameter[0], "dp_reflect") && numparameters >= 6)
1511                                 {
1512                                         shader->textureflags |= Q3TEXTUREFLAG_REFLECTION;
1513                                         shader->reflectfactor = atof(parameter[1]);
1514                                         Vector4Set(shader->reflectcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), atof(parameter[5]));
1515                                 }
1516                                 else if (!strcasecmp(parameter[0], "dp_water") && numparameters >= 11)
1517                                 {
1518                                         shader->textureflags |= Q3TEXTUREFLAG_WATERSHADER;
1519                                         shader->reflectmin = atof(parameter[1]);
1520                                         shader->reflectmax = atof(parameter[2]);
1521                                         shader->refractfactor = atof(parameter[3]);
1522                                         shader->reflectfactor = atof(parameter[4]);
1523                                         Vector4Set(shader->refractcolor4f, atof(parameter[5]), atof(parameter[6]), atof(parameter[7]), 1);
1524                                         Vector4Set(shader->reflectcolor4f, atof(parameter[8]), atof(parameter[9]), atof(parameter[10]), 1);
1525                                 }
1526                                 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
1527                                 {
1528                                         int i, deformindex;
1529                                         for (deformindex = 0;deformindex < Q3MAXDEFORMS;deformindex++)
1530                                                 if (!shader->deforms[deformindex].deform)
1531                                                         break;
1532                                         if (deformindex < Q3MAXDEFORMS)
1533                                         {
1534                                                 for (i = 0;i < numparameters - 2 && i < Q3DEFORM_MAXPARMS;i++)
1535                                                         shader->deforms[deformindex].parms[i] = atof(parameter[i+2]);
1536                                                      if (!strcasecmp(parameter[1], "projectionshadow")) shader->deforms[deformindex].deform = Q3DEFORM_PROJECTIONSHADOW;
1537                                                 else if (!strcasecmp(parameter[1], "autosprite"      )) shader->deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE;
1538                                                 else if (!strcasecmp(parameter[1], "autosprite2"     )) shader->deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE2;
1539                                                 else if (!strcasecmp(parameter[1], "text0"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT0;
1540                                                 else if (!strcasecmp(parameter[1], "text1"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT1;
1541                                                 else if (!strcasecmp(parameter[1], "text2"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT2;
1542                                                 else if (!strcasecmp(parameter[1], "text3"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT3;
1543                                                 else if (!strcasecmp(parameter[1], "text4"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT4;
1544                                                 else if (!strcasecmp(parameter[1], "text5"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT5;
1545                                                 else if (!strcasecmp(parameter[1], "text6"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT6;
1546                                                 else if (!strcasecmp(parameter[1], "text7"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT7;
1547                                                 else if (!strcasecmp(parameter[1], "bulge"           )) shader->deforms[deformindex].deform = Q3DEFORM_BULGE;
1548                                                 else if (!strcasecmp(parameter[1], "normal"          )) shader->deforms[deformindex].deform = Q3DEFORM_NORMAL;
1549                                                 else if (!strcasecmp(parameter[1], "wave"            ))
1550                                                 {
1551                                                         shader->deforms[deformindex].deform = Q3DEFORM_WAVE;
1552                                                         shader->deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[3]);
1553                                                         for (i = 0;i < numparameters - 4 && i < Q3WAVEPARMS;i++)
1554                                                                 shader->deforms[deformindex].waveparms[i] = atof(parameter[i+4]);
1555                                                 }
1556                                                 else if (!strcasecmp(parameter[1], "move"            ))
1557                                                 {
1558                                                         shader->deforms[deformindex].deform = Q3DEFORM_MOVE;
1559                                                         shader->deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[5]);
1560                                                         for (i = 0;i < numparameters - 6 && i < Q3WAVEPARMS;i++)
1561                                                                 shader->deforms[deformindex].waveparms[i] = atof(parameter[i+6]);
1562                                                 }
1563                                         }
1564                                 }
1565                         }
1566                         // identify if this is a blended terrain shader or similar
1567                         if (shader->numlayers)
1568                         {
1569                                 shader->backgroundlayer = NULL;
1570                                 shader->primarylayer = shader->layers + 0;
1571                                 if ((shader->layers[0].blendfunc[0] == GL_ONE       && shader->layers[0].blendfunc[1] == GL_ZERO                && !shader->layers[0].alphatest)
1572                                 && ((shader->layers[1].blendfunc[0] == GL_SRC_ALPHA && shader->layers[1].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA && !shader->layers[0].alphatest)
1573                                 ||  (shader->layers[1].blendfunc[0] == GL_ONE       && shader->layers[1].blendfunc[1] == GL_ZERO                &&  shader->layers[1].alphatest)))
1574                                 {
1575                                         // terrain blending or other effects
1576                                         shader->backgroundlayer = shader->layers + 0;
1577                                         shader->primarylayer = shader->layers + 1;
1578                                 }
1579                                 // now see if the lightmap came first, and if so choose the second texture instead
1580                                 if (!strcasecmp(shader->primarylayer->texturename[0], "$lightmap"))
1581                                 {
1582                                         shader->backgroundlayer = NULL;
1583                                         shader->primarylayer = shader->layers + 1;
1584                                 }
1585                         }
1586                         // fix up multiple reflection types
1587                         if(shader->textureflags & Q3TEXTUREFLAG_WATERSHADER)
1588                                 shader->textureflags &= ~(Q3TEXTUREFLAG_REFRACTION | Q3TEXTUREFLAG_REFLECTION);
1589                 }
1590                 Mem_Free(f);
1591         }
1592 }
1593
1594 q3shaderinfo_t *Mod_LookupQ3Shader(const char *name)
1595 {
1596         int i;
1597         for (i = 0;i < q3shaders_numshaders;i++)
1598                 if (!strcasecmp(q3shaders_shaders[i].name, name))
1599                         return q3shaders_shaders + i;
1600         return NULL;
1601 }
1602
1603 extern cvar_t r_picmipworld;
1604 qboolean Mod_LoadTextureFromQ3Shader(texture_t *texture, const char *name, qboolean q1bsp, qboolean q3bsp, qboolean md3)
1605 {
1606         int j;
1607         int texflags;
1608         qboolean success = true;
1609         q3shaderinfo_t *shader;
1610         strlcpy(texture->name, name, sizeof(texture->name));
1611         shader = name[0] ? Mod_LookupQ3Shader(name) : NULL;
1612         if (shader)
1613         {
1614                 if (developer.integer >= 100)
1615                         Con_DPrintf("%s: loaded shader for %s\n", loadmodel->name, name);
1616                 texture->surfaceparms = shader->surfaceparms;
1617                 texture->textureflags = shader->textureflags;
1618                 texture->basematerialflags = 0;
1619                 if (shader->surfaceparms & Q3SURFACEPARM_SKY)
1620                 {
1621                         texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1622                         if (shader->skyboxname[0])
1623                         {
1624                                 // quake3 seems to append a _ to the skybox name, so this must do so as well
1625                                 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", shader->skyboxname);
1626                         }
1627                 }
1628                 else if ((texture->surfaceflags & Q3SURFACEFLAG_NODRAW) || shader->numlayers == 0)
1629                         texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1630                 else if (shader->surfaceparms & Q3SURFACEPARM_LAVA)
1631                         texture->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOSHADOW;
1632                 else if (shader->surfaceparms & Q3SURFACEPARM_SLIME)
1633                         texture->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_WATERALPHA | MATERIALFLAG_NOSHADOW;
1634                 else if (shader->surfaceparms & Q3SURFACEPARM_WATER)
1635                         texture->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_WATERALPHA | MATERIALFLAG_NOSHADOW;
1636                 else
1637                         texture->basematerialflags |= MATERIALFLAG_WALL;
1638                 if (shader->layers[0].alphatest)
1639                         texture->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
1640                 if (shader->textureflags & Q3TEXTUREFLAG_TWOSIDED)
1641                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
1642                 if (shader->textureflags & Q3TEXTUREFLAG_POLYGONOFFSET)
1643                         texture->basepolygonoffset -= 2;
1644                 if (shader->textureflags & Q3TEXTUREFLAG_REFRACTION)
1645                         texture->basematerialflags |= MATERIALFLAG_REFRACTION;
1646                 if (shader->textureflags & Q3TEXTUREFLAG_REFLECTION)
1647                         texture->basematerialflags |= MATERIALFLAG_REFLECTION;
1648                 if (shader->textureflags & Q3TEXTUREFLAG_WATERSHADER)
1649                         texture->basematerialflags |= MATERIALFLAG_WATERSHADER;
1650                 texture->customblendfunc[0] = GL_ONE;
1651                 texture->customblendfunc[1] = GL_ZERO;
1652                 if (shader->numlayers > 0)
1653                 {
1654                         texture->customblendfunc[0] = shader->layers[0].blendfunc[0];
1655                         texture->customblendfunc[1] = shader->layers[0].blendfunc[1];
1656 /*
1657 Q3 shader blendfuncs actually used in the game (* = supported by DP)
1658 * additive               GL_ONE GL_ONE
1659 additive weird         GL_ONE GL_SRC_ALPHA
1660 additive weird 2       GL_ONE GL_ONE_MINUS_SRC_ALPHA
1661 * alpha                  GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
1662 alpha inverse          GL_ONE_MINUS_SRC_ALPHA GL_SRC_ALPHA
1663 brighten               GL_DST_COLOR GL_ONE
1664 brighten               GL_ONE GL_SRC_COLOR
1665 brighten weird         GL_DST_COLOR GL_ONE_MINUS_DST_ALPHA
1666 brighten weird 2       GL_DST_COLOR GL_SRC_ALPHA
1667 * modulate               GL_DST_COLOR GL_ZERO
1668 * modulate               GL_ZERO GL_SRC_COLOR
1669 modulate inverse       GL_ZERO GL_ONE_MINUS_SRC_COLOR
1670 modulate inverse alpha GL_ZERO GL_SRC_ALPHA
1671 modulate weird inverse GL_ONE_MINUS_DST_COLOR GL_ZERO
1672 * modulate x2            GL_DST_COLOR GL_SRC_COLOR
1673 * no blend               GL_ONE GL_ZERO
1674 nothing                GL_ZERO GL_ONE
1675 */
1676                         // if not opaque, figure out what blendfunc to use
1677                         if (shader->layers[0].blendfunc[0] != GL_ONE || shader->layers[0].blendfunc[1] != GL_ZERO)
1678                         {
1679                                 if (shader->layers[0].blendfunc[0] == GL_ONE && shader->layers[0].blendfunc[1] == GL_ONE)
1680                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1681                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE)
1682                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1683                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
1684                                         texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1685                                 else
1686                                         texture->basematerialflags |= MATERIALFLAG_CUSTOMBLEND | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1687                         }
1688                 }
1689                 if (!shader->lighting)
1690                         texture->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
1691                 if (shader->primarylayer)
1692                 {
1693                         // copy over many shader->primarylayer parameters
1694                         texture->rgbgen = shader->primarylayer->rgbgen;
1695                         texture->alphagen = shader->primarylayer->alphagen;
1696                         texture->tcgen = shader->primarylayer->tcgen;
1697                         memcpy(texture->tcmods, shader->primarylayer->tcmods, sizeof(texture->tcmods));
1698                         // load the textures
1699                         texture->numskinframes = shader->primarylayer->numframes;
1700                         texture->skinframerate = shader->primarylayer->framerate;
1701                         for (j = 0;j < shader->primarylayer->numframes;j++)
1702                         {
1703                                 texflags = TEXF_ALPHA | TEXF_PRECACHE;
1704                                 if (!(shader->surfaceparms & Q3SURFACEPARM_NOMIPMAPS))
1705                                         texflags |= TEXF_MIPMAP;
1706                                 if (!(shader->textureflags & Q3TEXTUREFLAG_NOPICMIP) && ((!q1bsp && !q3bsp) || r_picmipworld.integer))
1707                                         texflags |= TEXF_PICMIP | TEXF_COMPRESS;
1708                                 if (shader->primarylayer->clampmap)
1709                                         texflags |= TEXF_CLAMP;
1710                                 if (!(texture->skinframes[j] = R_SkinFrame_LoadExternal(shader->primarylayer->texturename[j], texflags, false)))
1711                                 {
1712                                         Con_Printf("^1%s:^7 could not load texture ^3\"%s\"^7 (frame %i) for shader ^2\"%s\"\n", loadmodel->name, shader->primarylayer->texturename[j], j, texture->name);
1713                                         texture->skinframes[j] = R_SkinFrame_LoadMissing();
1714                                 }
1715                         }
1716                 }
1717                 if (shader->backgroundlayer)
1718                 {
1719                         texture->backgroundnumskinframes = shader->backgroundlayer->numframes;
1720                         texture->backgroundskinframerate = shader->backgroundlayer->framerate;
1721                         for (j = 0;j < shader->backgroundlayer->numframes;j++)
1722                         {
1723                                 if (!(texture->backgroundskinframes[j] = R_SkinFrame_LoadExternal(shader->backgroundlayer->texturename[j], ((shader->surfaceparms & Q3SURFACEPARM_NOMIPMAPS) ? 0 : TEXF_MIPMAP) | TEXF_ALPHA | TEXF_PRECACHE | ((!r_picmipworld.integer || (shader->textureflags & Q3TEXTUREFLAG_NOPICMIP)) ? 0 : (TEXF_PICMIP | TEXF_COMPRESS)) | (shader->backgroundlayer->clampmap ? TEXF_CLAMP : 0), false)))
1724                                 {
1725                                         Con_Printf("^1%s:^7 could not load texture ^3\"%s\"^7 (frame %i) for shader ^2\"%s\"\n", loadmodel->name, shader->backgroundlayer->texturename[j], j, texture->name);
1726                                         texture->backgroundskinframes[j] = R_SkinFrame_LoadMissing();
1727                                 }
1728                         }
1729                 }
1730                 memcpy(texture->deforms, shader->deforms, sizeof(texture->deforms));
1731                 texture->reflectmin = shader->reflectmin;
1732                 texture->reflectmax = shader->reflectmax;
1733                 texture->refractfactor = shader->refractfactor;
1734                 Vector4Copy(shader->refractcolor4f, texture->refractcolor4f);
1735                 texture->reflectfactor = shader->reflectfactor;
1736                 Vector4Copy(shader->reflectcolor4f, texture->reflectcolor4f);
1737         }
1738         else if (!strcmp(texture->name, "noshader"))
1739         {
1740                 if (developer.integer >= 100)
1741                         Con_DPrintf("%s: using default handler for %s\n", loadmodel->name, name);
1742                 texture->surfaceparms = 0;
1743         }
1744         else
1745         {
1746                 success = false;
1747                 if (developer.integer >= 100 || loadmodel->type == mod_brushq3)
1748                         Con_DPrintf("%s: No shader found for texture \"%s\"\n", loadmodel->name, texture->name);
1749                 texture->surfaceparms = 0;
1750                 if (texture->surfaceflags & Q3SURFACEFLAG_NODRAW)
1751                         texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1752                 else if (texture->surfaceflags & Q3SURFACEFLAG_SKY)
1753                         texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1754                 else
1755                         texture->basematerialflags |= MATERIALFLAG_WALL;
1756                 texture->numskinframes = 1;
1757                 if (!(texture->skinframes[0] = R_SkinFrame_LoadExternal(texture->name, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | (r_picmipworld.integer ? TEXF_PICMIP : 0) | TEXF_COMPRESS, false)))
1758                         if(developer.integer || q3bsp) // only the Q3BSP path provides no alternative (like loading image directly, or internal texture)
1759                                 Con_Printf("^1%s:^7 could not load texture for missing shader ^3\"%s\"\n", loadmodel->name, texture->name);
1760         }
1761         // init the animation variables
1762         texture->currentframe = texture;
1763         if (texture->numskinframes < 1)
1764                 texture->numskinframes = 1;
1765         if (!texture->skinframes[0])
1766                 texture->skinframes[0] = R_SkinFrame_LoadMissing();
1767         texture->currentskinframe = texture->skinframes[0];
1768         texture->backgroundcurrentskinframe = texture->backgroundskinframes[0];
1769         return success;
1770 }
1771
1772 skinfile_t *Mod_LoadSkinFiles(void)
1773 {
1774         int i, words, numtags, line, tagsetsused = false, wordsoverflow;
1775         char *text;
1776         const char *data;
1777         skinfile_t *skinfile = NULL, *first = NULL;
1778         skinfileitem_t *skinfileitem;
1779         char word[10][MAX_QPATH];
1780         overridetagnameset_t tagsets[MAX_SKINS];
1781         overridetagname_t tags[256];
1782
1783 /*
1784 sample file:
1785 U_bodyBox,models/players/Legoman/BikerA2.tga
1786 U_RArm,models/players/Legoman/BikerA1.tga
1787 U_LArm,models/players/Legoman/BikerA1.tga
1788 U_armor,common/nodraw
1789 U_sword,common/nodraw
1790 U_shield,common/nodraw
1791 U_homb,common/nodraw
1792 U_backpack,common/nodraw
1793 U_colcha,common/nodraw
1794 tag_head,
1795 tag_weapon,
1796 tag_torso,
1797 */
1798         memset(tagsets, 0, sizeof(tagsets));
1799         memset(word, 0, sizeof(word));
1800         for (i = 0;i < MAX_SKINS && (data = text = (char *)FS_LoadFile(va("%s_%i.skin", loadmodel->name, i), tempmempool, true, NULL));i++)
1801         {
1802                 numtags = 0;
1803
1804                 // If it's the first file we parse
1805                 if (skinfile == NULL)
1806                 {
1807                         skinfile = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
1808                         first = skinfile;
1809                 }
1810                 else
1811                 {
1812                         skinfile->next = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
1813                         skinfile = skinfile->next;
1814                 }
1815                 skinfile->next = NULL;
1816
1817                 for(line = 0;;line++)
1818                 {
1819                         // parse line
1820                         if (!COM_ParseToken_QuakeC(&data, true))
1821                                 break;
1822                         if (!strcmp(com_token, "\n"))
1823                                 continue;
1824                         words = 0;
1825                         wordsoverflow = false;
1826                         do
1827                         {
1828                                 if (words < 10)
1829                                         strlcpy(word[words++], com_token, sizeof (word[0]));
1830                                 else
1831                                         wordsoverflow = true;
1832                         }
1833                         while (COM_ParseToken_QuakeC(&data, true) && strcmp(com_token, "\n"));
1834                         if (wordsoverflow)
1835                         {
1836                                 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);
1837                                 continue;
1838                         }
1839                         // words is always >= 1
1840                         if (!strcmp(word[0], "replace"))
1841                         {
1842                                 if (words == 3)
1843                                 {
1844                                         Con_DPrintf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[1], word[2]);
1845                                         skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
1846                                         skinfileitem->next = skinfile->items;
1847                                         skinfile->items = skinfileitem;
1848                                         strlcpy (skinfileitem->name, word[1], sizeof (skinfileitem->name));
1849                                         strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
1850                                 }
1851                                 else
1852                                         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]);
1853                         }
1854                         else if (words == 2 && !strcmp(word[1], ","))
1855                         {
1856                                 // tag name, like "tag_weapon,"
1857                                 Con_DPrintf("Mod_LoadSkinFiles: parsed tag #%i \"%s\"\n", numtags, word[0]);
1858                                 memset(tags + numtags, 0, sizeof(tags[numtags]));
1859                                 strlcpy (tags[numtags].name, word[0], sizeof (tags[numtags].name));
1860                                 numtags++;
1861                         }
1862                         else if (words == 3 && !strcmp(word[1], ","))
1863                         {
1864                                 // mesh shader name, like "U_RArm,models/players/Legoman/BikerA1.tga"
1865                                 Con_DPrintf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[0], word[2]);
1866                                 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
1867                                 skinfileitem->next = skinfile->items;
1868                                 skinfile->items = skinfileitem;
1869                                 strlcpy (skinfileitem->name, word[0], sizeof (skinfileitem->name));
1870                                 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
1871                         }
1872                         else
1873                                 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);
1874                 }
1875                 Mem_Free(text);
1876
1877                 if (numtags)
1878                 {
1879                         overridetagnameset_t *t;
1880                         t = tagsets + i;
1881                         t->num_overridetagnames = numtags;
1882                         t->data_overridetagnames = (overridetagname_t *)Mem_Alloc(loadmodel->mempool, t->num_overridetagnames * sizeof(overridetagname_t));
1883                         memcpy(t->data_overridetagnames, tags, t->num_overridetagnames * sizeof(overridetagname_t));
1884                         tagsetsused = true;
1885                 }
1886         }
1887         if (tagsetsused)
1888         {
1889                 loadmodel->data_overridetagnamesforskin = (overridetagnameset_t *)Mem_Alloc(loadmodel->mempool, i * sizeof(overridetagnameset_t));
1890                 memcpy(loadmodel->data_overridetagnamesforskin, tagsets, i * sizeof(overridetagnameset_t));
1891         }
1892         if (i)
1893                 loadmodel->numskins = i;
1894         return first;
1895 }
1896
1897 void Mod_FreeSkinFiles(skinfile_t *skinfile)
1898 {
1899         skinfile_t *next;
1900         skinfileitem_t *skinfileitem, *nextitem;
1901         for (;skinfile;skinfile = next)
1902         {
1903                 next = skinfile->next;
1904                 for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = nextitem)
1905                 {
1906                         nextitem = skinfileitem->next;
1907                         Mem_Free(skinfileitem);
1908                 }
1909                 Mem_Free(skinfile);
1910         }
1911 }
1912
1913 int Mod_CountSkinFiles(skinfile_t *skinfile)
1914 {
1915         int i;
1916         for (i = 0;skinfile;skinfile = skinfile->next, i++);
1917         return i;
1918 }
1919
1920 void Mod_SnapVertices(int numcomponents, int numvertices, float *vertices, float snap)
1921 {
1922         int i;
1923         double isnap = 1.0 / snap;
1924         for (i = 0;i < numvertices*numcomponents;i++)
1925                 vertices[i] = floor(vertices[i]*isnap)*snap;
1926 }
1927
1928 int Mod_RemoveDegenerateTriangles(int numtriangles, const int *inelement3i, int *outelement3i, const float *vertex3f)
1929 {
1930         int i, outtriangles;
1931         float d, edgedir[3], temp[3];
1932         // a degenerate triangle is one with no width (thickness, surface area)
1933         // these are characterized by having all 3 points colinear (along a line)
1934         // or having two points identical
1935         for (i = 0, outtriangles = 0;i < numtriangles;i++, inelement3i += 3)
1936         {
1937                 // calculate first edge
1938                 VectorSubtract(vertex3f + inelement3i[1] * 3, vertex3f + inelement3i[0] * 3, edgedir);
1939                 if (VectorLength2(edgedir) < 0.0001f)
1940                         continue; // degenerate first edge (no length)
1941                 VectorNormalize(edgedir);
1942                 // check if third point is on the edge (colinear)
1943                 d = -DotProduct(vertex3f + inelement3i[2] * 3, edgedir);
1944                 VectorMA(vertex3f + inelement3i[2] * 3, d, edgedir, temp);
1945                 if (VectorLength2(temp) < 0.0001f)
1946                         continue; // third point colinear with first edge
1947                 // valid triangle (no colinear points, no duplicate points)
1948                 VectorCopy(inelement3i, outelement3i);
1949                 outelement3i += 3;
1950                 outtriangles++;
1951         }
1952         return outtriangles;
1953 }
1954
1955 void Mod_VertexRangeFromElements(int numelements, const int *elements, int *firstvertexpointer, int *lastvertexpointer)
1956 {
1957         int i, e;
1958         int firstvertex, lastvertex;
1959         if (numelements > 0 && elements)
1960         {
1961                 firstvertex = lastvertex = elements[0];
1962                 for (i = 1;i < numelements;i++)
1963                 {
1964                         e = elements[i];
1965                         firstvertex = min(firstvertex, e);
1966                         lastvertex = max(lastvertex, e);
1967                 }
1968         }
1969         else
1970                 firstvertex = lastvertex = 0;
1971         if (firstvertexpointer)
1972                 *firstvertexpointer = firstvertex;
1973         if (lastvertexpointer)
1974                 *lastvertexpointer = lastvertex;
1975 }
1976
1977 static void Mod_BuildVBOs(void)
1978 {
1979         if (!gl_support_arb_vertex_buffer_object)
1980                 return;
1981
1982         // element buffer is easy because it's just one array
1983         if (loadmodel->surfmesh.num_triangles)
1984                 loadmodel->surfmesh.ebo = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles * sizeof(int[3]), loadmodel->name);
1985
1986         // vertex buffer is several arrays and we put them in the same buffer
1987         //
1988         // is this wise?  the texcoordtexture2f array is used with dynamic
1989         // vertex/svector/tvector/normal when rendering animated models, on the
1990         // other hand animated models don't use a lot of vertices anyway...
1991         if (loadmodel->surfmesh.num_vertices)
1992         {
1993                 size_t size;
1994                 unsigned char *mem;
1995                 size = 0;
1996                 loadmodel->surfmesh.vbooffset_vertex3f           = size;if (loadmodel->surfmesh.data_vertex3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
1997                 loadmodel->surfmesh.vbooffset_svector3f          = size;if (loadmodel->surfmesh.data_svector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
1998                 loadmodel->surfmesh.vbooffset_tvector3f          = size;if (loadmodel->surfmesh.data_tvector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
1999                 loadmodel->surfmesh.vbooffset_normal3f           = size;if (loadmodel->surfmesh.data_normal3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2000                 loadmodel->surfmesh.vbooffset_texcoordtexture2f  = size;if (loadmodel->surfmesh.data_texcoordtexture2f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2001                 loadmodel->surfmesh.vbooffset_texcoordlightmap2f = size;if (loadmodel->surfmesh.data_texcoordlightmap2f) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2002                 loadmodel->surfmesh.vbooffset_lightmapcolor4f    = size;if (loadmodel->surfmesh.data_lightmapcolor4f   ) size += loadmodel->surfmesh.num_vertices * sizeof(float[4]);
2003                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
2004                 if (loadmodel->surfmesh.data_vertex3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_vertex3f          , loadmodel->surfmesh.data_vertex3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2005                 if (loadmodel->surfmesh.data_svector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_svector3f         , loadmodel->surfmesh.data_svector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2006                 if (loadmodel->surfmesh.data_tvector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_tvector3f         , loadmodel->surfmesh.data_tvector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2007                 if (loadmodel->surfmesh.data_normal3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_normal3f          , loadmodel->surfmesh.data_normal3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2008                 if (loadmodel->surfmesh.data_texcoordtexture2f ) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordtexture2f , loadmodel->surfmesh.data_texcoordtexture2f , loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2009                 if (loadmodel->surfmesh.data_texcoordlightmap2f) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordlightmap2f, loadmodel->surfmesh.data_texcoordlightmap2f, loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2010                 if (loadmodel->surfmesh.data_lightmapcolor4f   ) memcpy(mem + loadmodel->surfmesh.vbooffset_lightmapcolor4f   , loadmodel->surfmesh.data_lightmapcolor4f   , loadmodel->surfmesh.num_vertices * sizeof(float[4]));
2011                 loadmodel->surfmesh.vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, loadmodel->name);
2012                 Mem_Free(mem);
2013         }
2014 }