only print the "missing texture for missing shader" message for developer or Q3BSP...
[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_GetTerrainVertex3fTexCoord2fFromRGBA(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_GetTerrainVertexFromRGBA(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_GetTerrainVertex3fTexCoord2fFromRGBA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, pixelstepmatrix, pixeltexturestepmatrix);
1054         Mod_GetTerrainVertex3fTexCoord2fFromRGBA(imagepixels, imagewidth, imageheight, ix, iy - 1, vup, tcup, pixelstepmatrix, pixeltexturestepmatrix);
1055         Mod_GetTerrainVertex3fTexCoord2fFromRGBA(imagepixels, imagewidth, imageheight, ix, iy + 1, vdown, tcdown, pixelstepmatrix, pixeltexturestepmatrix);
1056         Mod_GetTerrainVertex3fTexCoord2fFromRGBA(imagepixels, imagewidth, imageheight, ix - 1, iy, vleft, tcleft, pixelstepmatrix, pixeltexturestepmatrix);
1057         Mod_GetTerrainVertex3fTexCoord2fFromRGBA(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_ConstructTerrainPatchFromRGBA(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_GetTerrainVertexFromRGBA(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                         VectorSet(shader->reflectcolor, 1, 1, 1);
1139                         VectorSet(shader->refractcolor, 1, 1, 1);
1140                         shader->refractmin = 0;
1141                         shader->refractmax = 1;
1142                         shader->refractfactor = 1;
1143
1144                         strlcpy(shader->name, com_token, sizeof(shader->name));
1145                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1146                         {
1147                                 Con_Printf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[fileindex], com_token);
1148                                 break;
1149                         }
1150                         while (COM_ParseToken_QuakeC(&text, false))
1151                         {
1152                                 if (!strcasecmp(com_token, "}"))
1153                                         break;
1154                                 if (!strcasecmp(com_token, "{"))
1155                                 {
1156                                         if (shader->numlayers < Q3SHADER_MAXLAYERS)
1157                                         {
1158                                                 layer = shader->layers + shader->numlayers++;
1159                                                 layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1160                                                 layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1161                                                 layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1162                                                 layer->blendfunc[0] = GL_ONE;
1163                                                 layer->blendfunc[1] = GL_ZERO;
1164                                         }
1165                                         else
1166                                                 layer = NULL;
1167                                         while (COM_ParseToken_QuakeC(&text, false))
1168                                         {
1169                                                 if (!strcasecmp(com_token, "}"))
1170                                                         break;
1171                                                 if (!strcasecmp(com_token, "\n"))
1172                                                         continue;
1173                                                 if (layer == NULL)
1174                                                         continue;
1175                                                 numparameters = 0;
1176                                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1177                                                 {
1178                                                         if (j < TEXTURE_MAXFRAMES + 4)
1179                                                         {
1180                                                                 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1181                                                                 numparameters = j + 1;
1182                                                         }
1183                                                         if (!COM_ParseToken_QuakeC(&text, true))
1184                                                                 break;
1185                                                 }
1186                                                 for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1187                                                         parameter[j][0] = 0;
1188                                                 if (developer.integer >= 100)
1189                                                 {
1190                                                         Con_Printf("%s %i: ", shader->name, shader->numlayers - 1);
1191                                                         for (j = 0;j < numparameters;j++)
1192                                                                 Con_Printf(" %s", parameter[j]);
1193                                                         Con_Print("\n");
1194                                                 }
1195                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "blendfunc"))
1196                                                 {
1197                                                         if (numparameters == 2)
1198                                                         {
1199                                                                 if (!strcasecmp(parameter[1], "add"))
1200                                                                 {
1201                                                                         layer->blendfunc[0] = GL_ONE;
1202                                                                         layer->blendfunc[1] = GL_ONE;
1203                                                                 }
1204                                                                 else if (!strcasecmp(parameter[1], "filter"))
1205                                                                 {
1206                                                                         layer->blendfunc[0] = GL_DST_COLOR;
1207                                                                         layer->blendfunc[1] = GL_ZERO;
1208                                                                 }
1209                                                                 else if (!strcasecmp(parameter[1], "blend"))
1210                                                                 {
1211                                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1212                                                                         layer->blendfunc[1] = GL_ONE_MINUS_SRC_ALPHA;
1213                                                                 }
1214                                                         }
1215                                                         else if (numparameters == 3)
1216                                                         {
1217                                                                 int k;
1218                                                                 for (k = 0;k < 2;k++)
1219                                                                 {
1220                                                                         if (!strcasecmp(parameter[k+1], "GL_ONE"))
1221                                                                                 layer->blendfunc[k] = GL_ONE;
1222                                                                         else if (!strcasecmp(parameter[k+1], "GL_ZERO"))
1223                                                                                 layer->blendfunc[k] = GL_ZERO;
1224                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_COLOR"))
1225                                                                                 layer->blendfunc[k] = GL_SRC_COLOR;
1226                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_ALPHA"))
1227                                                                                 layer->blendfunc[k] = GL_SRC_ALPHA;
1228                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_COLOR"))
1229                                                                                 layer->blendfunc[k] = GL_DST_COLOR;
1230                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_ALPHA"))
1231                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1232                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_COLOR"))
1233                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_COLOR;
1234                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_ALPHA"))
1235                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_ALPHA;
1236                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_COLOR"))
1237                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_COLOR;
1238                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_ALPHA"))
1239                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1240                                                                         else
1241                                                                                 layer->blendfunc[k] = GL_ONE; // default in case of parsing error
1242                                                                 }
1243                                                         }
1244                                                 }
1245                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
1246                                                         layer->alphatest = true;
1247                                                 if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
1248                                                 {
1249                                                         if (!strcasecmp(parameter[0], "clampmap"))
1250                                                                 layer->clampmap = true;
1251                                                         layer->numframes = 1;
1252                                                         layer->framerate = 1;
1253                                                         strlcpy(layer->texturename[0], parameter[1], sizeof(layer->texturename));
1254                                                         if (!strcasecmp(parameter[1], "$lightmap"))
1255                                                                 shader->lighting = true;
1256                                                 }
1257                                                 else if (numparameters >= 3 && (!strcasecmp(parameter[0], "animmap") || !strcasecmp(parameter[0], "animclampmap")))
1258                                                 {
1259                                                         int i;
1260                                                         layer->numframes = min(numparameters - 2, TEXTURE_MAXFRAMES);
1261                                                         layer->framerate = atof(parameter[1]);
1262                                                         for (i = 0;i < layer->numframes;i++)
1263                                                                 strlcpy(layer->texturename[i], parameter[i + 2], sizeof(layer->texturename));
1264                                                 }
1265                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "rgbgen"))
1266                                                 {
1267                                                         int i;
1268                                                         for (i = 0;i < numparameters - 2 && i < Q3RGBGEN_MAXPARMS;i++)
1269                                                                 layer->rgbgen.parms[i] = atof(parameter[i+2]);
1270                                                              if (!strcasecmp(parameter[1], "identity"))         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1271                                                         else if (!strcasecmp(parameter[1], "const"))            layer->rgbgen.rgbgen = Q3RGBGEN_CONST;
1272                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->rgbgen.rgbgen = Q3RGBGEN_ENTITY;
1273                                                         else if (!strcasecmp(parameter[1], "exactvertex"))      layer->rgbgen.rgbgen = Q3RGBGEN_EXACTVERTEX;
1274                                                         else if (!strcasecmp(parameter[1], "identitylighting")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITYLIGHTING;
1275                                                         else if (!strcasecmp(parameter[1], "lightingdiffuse"))  layer->rgbgen.rgbgen = Q3RGBGEN_LIGHTINGDIFFUSE;
1276                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSENTITY;
1277                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSVERTEX;
1278                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->rgbgen.rgbgen = Q3RGBGEN_VERTEX;
1279                                                         else if (!strcasecmp(parameter[1], "wave"))
1280                                                         {
1281                                                                 layer->rgbgen.rgbgen = Q3RGBGEN_WAVE;
1282                                                                 layer->rgbgen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1283                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1284                                                                         layer->rgbgen.waveparms[i] = atof(parameter[i+3]);
1285                                                         }
1286                                                         else Con_DPrintf("%s parsing warning: unknown rgbgen %s\n", search->filenames[fileindex], parameter[1]);
1287                                                 }
1288                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphagen"))
1289                                                 {
1290                                                         int i;
1291                                                         for (i = 0;i < numparameters - 2 && i < Q3ALPHAGEN_MAXPARMS;i++)
1292                                                                 layer->alphagen.parms[i] = atof(parameter[i+2]);
1293                                                              if (!strcasecmp(parameter[1], "identity"))         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1294                                                         else if (!strcasecmp(parameter[1], "const"))            layer->alphagen.alphagen = Q3ALPHAGEN_CONST;
1295                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->alphagen.alphagen = Q3ALPHAGEN_ENTITY;
1296                                                         else if (!strcasecmp(parameter[1], "lightingspecular")) layer->alphagen.alphagen = Q3ALPHAGEN_LIGHTINGSPECULAR;
1297                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSENTITY;
1298                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSVERTEX;
1299                                                         else if (!strcasecmp(parameter[1], "portal"))           layer->alphagen.alphagen = Q3ALPHAGEN_PORTAL;
1300                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->alphagen.alphagen = Q3ALPHAGEN_VERTEX;
1301                                                         else if (!strcasecmp(parameter[1], "wave"))
1302                                                         {
1303                                                                 layer->alphagen.alphagen = Q3RGBGEN_WAVE;
1304                                                                 layer->alphagen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1305                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1306                                                                         layer->alphagen.waveparms[i] = atof(parameter[i+3]);
1307                                                         }
1308                                                         else Con_DPrintf("%s parsing warning: unknown alphagen %s\n", search->filenames[fileindex], parameter[1]);
1309                                                 }
1310                                                 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "texgen") || !strcasecmp(parameter[0], "tcgen")))
1311                                                 {
1312                                                         int i;
1313                                                         // observed values: tcgen environment
1314                                                         // no other values have been observed in real shaders
1315                                                         for (i = 0;i < numparameters - 2 && i < Q3TCGEN_MAXPARMS;i++)
1316                                                                 layer->tcgen.parms[i] = atof(parameter[i+2]);
1317                                                              if (!strcasecmp(parameter[1], "base"))        layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1318                                                         else if (!strcasecmp(parameter[1], "texture"))     layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1319                                                         else if (!strcasecmp(parameter[1], "environment")) layer->tcgen.tcgen = Q3TCGEN_ENVIRONMENT;
1320                                                         else if (!strcasecmp(parameter[1], "lightmap"))    layer->tcgen.tcgen = Q3TCGEN_LIGHTMAP;
1321                                                         else if (!strcasecmp(parameter[1], "vector"))      layer->tcgen.tcgen = Q3TCGEN_VECTOR;
1322                                                         else Con_DPrintf("%s parsing warning: unknown tcgen mode %s\n", search->filenames[fileindex], parameter[1]);
1323                                                 }
1324                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "tcmod"))
1325                                                 {
1326                                                         int i, tcmodindex;
1327                                                         // observed values:
1328                                                         // tcmod rotate #
1329                                                         // tcmod scale # #
1330                                                         // tcmod scroll # #
1331                                                         // tcmod stretch sin # # # #
1332                                                         // tcmod stretch triangle # # # #
1333                                                         // tcmod transform # # # # # #
1334                                                         // tcmod turb # # # #
1335                                                         // tcmod turb sin # # # #  (this is bogus)
1336                                                         // no other values have been observed in real shaders
1337                                                         for (tcmodindex = 0;tcmodindex < Q3MAXTCMODS;tcmodindex++)
1338                                                                 if (!layer->tcmods[tcmodindex].tcmod)
1339                                                                         break;
1340                                                         if (tcmodindex < Q3MAXTCMODS)
1341                                                         {
1342                                                                 for (i = 0;i < numparameters - 2 && i < Q3TCMOD_MAXPARMS;i++)
1343                                                                         layer->tcmods[tcmodindex].parms[i] = atof(parameter[i+2]);
1344                                                                          if (!strcasecmp(parameter[1], "entitytranslate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ENTITYTRANSLATE;
1345                                                                 else if (!strcasecmp(parameter[1], "rotate"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ROTATE;
1346                                                                 else if (!strcasecmp(parameter[1], "scale"))           layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCALE;
1347                                                                 else if (!strcasecmp(parameter[1], "scroll"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCROLL;
1348                                                                 else if (!strcasecmp(parameter[1], "stretch"))
1349                                                                 {
1350                                                                         layer->tcmods[tcmodindex].tcmod = Q3TCMOD_STRETCH;
1351                                                                         layer->tcmods[tcmodindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1352                                                                         for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1353                                                                                 layer->tcmods[tcmodindex].waveparms[i] = atof(parameter[i+3]);
1354                                                                 }
1355                                                                 else if (!strcasecmp(parameter[1], "transform"))       layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TRANSFORM;
1356                                                                 else if (!strcasecmp(parameter[1], "turb"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TURBULENT;
1357                                                                 else Con_DPrintf("%s parsing warning: unknown tcmod mode %s\n", search->filenames[fileindex], parameter[1]);
1358                                                         }
1359                                                         else
1360                                                                 Con_DPrintf("%s parsing warning: too many tcmods on one layer\n", search->filenames[fileindex]);
1361                                                 }
1362                                                 // break out a level if it was }
1363                                                 if (!strcasecmp(com_token, "}"))
1364                                                         break;
1365                                         }
1366                                         if (layer->rgbgen.rgbgen == Q3RGBGEN_LIGHTINGDIFFUSE || layer->rgbgen.rgbgen == Q3RGBGEN_VERTEX)
1367                                                 shader->lighting = true;
1368                                         if (layer->alphagen.alphagen == Q3ALPHAGEN_VERTEX)
1369                                         {
1370                                                 if (layer == shader->layers + 0)
1371                                                 {
1372                                                         // vertex controlled transparency
1373                                                         shader->vertexalpha = true;
1374                                                 }
1375                                                 else
1376                                                 {
1377                                                         // multilayer terrain shader or similar
1378                                                         shader->textureblendalpha = true;
1379                                                 }
1380                                         }
1381                                         continue;
1382                                 }
1383                                 numparameters = 0;
1384                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1385                                 {
1386                                         if (j < TEXTURE_MAXFRAMES + 4)
1387                                         {
1388                                                 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1389                                                 numparameters = j + 1;
1390                                         }
1391                                         if (!COM_ParseToken_QuakeC(&text, true))
1392                                                 break;
1393                                 }
1394                                 for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1395                                         parameter[j][0] = 0;
1396                                 if (fileindex == 0 && !strcasecmp(com_token, "}"))
1397                                         break;
1398                                 if (developer.integer >= 100)
1399                                 {
1400                                         Con_Printf("%s: ", shader->name);
1401                                         for (j = 0;j < numparameters;j++)
1402                                                 Con_Printf(" %s", parameter[j]);
1403                                         Con_Print("\n");
1404                                 }
1405                                 if (numparameters < 1)
1406                                         continue;
1407                                 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
1408                                 {
1409                                         if (!strcasecmp(parameter[1], "alphashadow"))
1410                                                 shader->surfaceparms |= Q3SURFACEPARM_ALPHASHADOW;
1411                                         else if (!strcasecmp(parameter[1], "areaportal"))
1412                                                 shader->surfaceparms |= Q3SURFACEPARM_AREAPORTAL;
1413                                         else if (!strcasecmp(parameter[1], "botclip"))
1414                                                 shader->surfaceparms |= Q3SURFACEPARM_BOTCLIP;
1415                                         else if (!strcasecmp(parameter[1], "clusterportal"))
1416                                                 shader->surfaceparms |= Q3SURFACEPARM_CLUSTERPORTAL;
1417                                         else if (!strcasecmp(parameter[1], "detail"))
1418                                                 shader->surfaceparms |= Q3SURFACEPARM_DETAIL;
1419                                         else if (!strcasecmp(parameter[1], "donotenter"))
1420                                                 shader->surfaceparms |= Q3SURFACEPARM_DONOTENTER;
1421                                         else if (!strcasecmp(parameter[1], "dust"))
1422                                                 shader->surfaceparms |= Q3SURFACEPARM_DUST;
1423                                         else if (!strcasecmp(parameter[1], "hint"))
1424                                                 shader->surfaceparms |= Q3SURFACEPARM_HINT;
1425                                         else if (!strcasecmp(parameter[1], "fog"))
1426                                                 shader->surfaceparms |= Q3SURFACEPARM_FOG;
1427                                         else if (!strcasecmp(parameter[1], "lava"))
1428                                                 shader->surfaceparms |= Q3SURFACEPARM_LAVA;
1429                                         else if (!strcasecmp(parameter[1], "lightfilter"))
1430                                                 shader->surfaceparms |= Q3SURFACEPARM_LIGHTFILTER;
1431                                         else if (!strcasecmp(parameter[1], "lightgrid"))
1432                                                 shader->surfaceparms |= Q3SURFACEPARM_LIGHTGRID;
1433                                         else if (!strcasecmp(parameter[1], "metalsteps"))
1434                                                 shader->surfaceparms |= Q3SURFACEPARM_METALSTEPS;
1435                                         else if (!strcasecmp(parameter[1], "nodamage"))
1436                                                 shader->surfaceparms |= Q3SURFACEPARM_NODAMAGE;
1437                                         else if (!strcasecmp(parameter[1], "nodlight"))
1438                                                 shader->surfaceparms |= Q3SURFACEPARM_NODLIGHT;
1439                                         else if (!strcasecmp(parameter[1], "nodraw"))
1440                                                 shader->surfaceparms |= Q3SURFACEPARM_NODRAW;
1441                                         else if (!strcasecmp(parameter[1], "nodrop"))
1442                                                 shader->surfaceparms |= Q3SURFACEPARM_NODROP;
1443                                         else if (!strcasecmp(parameter[1], "noimpact"))
1444                                                 shader->surfaceparms |= Q3SURFACEPARM_NOIMPACT;
1445                                         else if (!strcasecmp(parameter[1], "nolightmap"))
1446                                                 shader->surfaceparms |= Q3SURFACEPARM_NOLIGHTMAP;
1447                                         else if (!strcasecmp(parameter[1], "nomarks"))
1448                                                 shader->surfaceparms |= Q3SURFACEPARM_NOMARKS;
1449                                         else if (!strcasecmp(parameter[1], "nomipmaps"))
1450                                                 shader->surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1451                                         else if (!strcasecmp(parameter[1], "nonsolid"))
1452                                                 shader->surfaceparms |= Q3SURFACEPARM_NONSOLID;
1453                                         else if (!strcasecmp(parameter[1], "origin"))
1454                                                 shader->surfaceparms |= Q3SURFACEPARM_ORIGIN;
1455                                         else if (!strcasecmp(parameter[1], "playerclip"))
1456                                                 shader->surfaceparms |= Q3SURFACEPARM_PLAYERCLIP;
1457                                         else if (!strcasecmp(parameter[1], "sky"))
1458                                                 shader->surfaceparms |= Q3SURFACEPARM_SKY;
1459                                         else if (!strcasecmp(parameter[1], "slick"))
1460                                                 shader->surfaceparms |= Q3SURFACEPARM_SLICK;
1461                                         else if (!strcasecmp(parameter[1], "slime"))
1462                                                 shader->surfaceparms |= Q3SURFACEPARM_SLIME;
1463                                         else if (!strcasecmp(parameter[1], "structural"))
1464                                                 shader->surfaceparms |= Q3SURFACEPARM_STRUCTURAL;
1465                                         else if (!strcasecmp(parameter[1], "trans"))
1466                                                 shader->surfaceparms |= Q3SURFACEPARM_TRANS;
1467                                         else if (!strcasecmp(parameter[1], "water"))
1468                                                 shader->surfaceparms |= Q3SURFACEPARM_WATER;
1469                                         else if (!strcasecmp(parameter[1], "pointlight"))
1470                                                 shader->surfaceparms |= Q3SURFACEPARM_POINTLIGHT;
1471                                         else if (!strcasecmp(parameter[1], "antiportal"))
1472                                                 shader->surfaceparms |= Q3SURFACEPARM_ANTIPORTAL;
1473                                         else
1474                                                 Con_DPrintf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[fileindex], parameter[1]);
1475                                 }
1476                                 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
1477                                 {
1478                                         // some q3 skies don't have the sky parm set
1479                                         shader->surfaceparms |= Q3SURFACEPARM_SKY;
1480                                         strlcpy(shader->skyboxname, parameter[1], sizeof(shader->skyboxname));
1481                                 }
1482                                 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
1483                                 {
1484                                         // some q3 skies don't have the sky parm set
1485                                         shader->surfaceparms |= Q3SURFACEPARM_SKY;
1486                                         if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
1487                                                 strlcpy(shader->skyboxname, parameter[1], sizeof(shader->skyboxname));
1488                                 }
1489                                 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
1490                                 {
1491                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
1492                                                 shader->textureflags |= Q3TEXTUREFLAG_TWOSIDED;
1493                                 }
1494                                 else if (!strcasecmp(parameter[0], "nomipmaps"))
1495                                         shader->surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1496                                 else if (!strcasecmp(parameter[0], "nopicmip"))
1497                                         shader->textureflags |= Q3TEXTUREFLAG_NOPICMIP;
1498                                 else if (!strcasecmp(parameter[0], "polygonoffset"))
1499                                         shader->textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
1500                                 else if (!strcasecmp(parameter[0], "dp_reflect"))
1501                                 {
1502                                         shader->textureflags |= Q3TEXTUREFLAG_REFLECTION;
1503                                         if(numparameters >= 2)
1504                                                 VectorSet(shader->reflectcolor, atof(parameter[1]), atof(parameter[1]), atof(parameter[1])); // grey
1505                                         if(numparameters >= 4)
1506                                                 VectorSet(shader->reflectcolor, atof(parameter[1]), atof(parameter[2]), atof(parameter[3]));
1507                                 }
1508                                 else if (!strcasecmp(parameter[0], "dp_refract"))
1509                                 {
1510                                         shader->textureflags |= Q3TEXTUREFLAG_WATERSHADER;
1511                                         if(numparameters >= 2)
1512                                                 shader->refractmin = atof(parameter[1]);
1513                                         if(numparameters >= 3)
1514                                                 shader->refractmax = atof(parameter[2]);
1515                                         if(numparameters >= 4)
1516                                                 shader->refractfactor = atof(parameter[3]);
1517                                         if(numparameters >= 5)
1518                                                 VectorSet(shader->refractcolor, atof(parameter[4]), atof(parameter[4]), atof(parameter[4])); // grey
1519                                         if(numparameters >= 7)
1520                                                 VectorSet(shader->refractcolor, atof(parameter[4]), atof(parameter[5]), atof(parameter[6]));
1521                                 }
1522                                 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
1523                                 {
1524                                         int i, deformindex;
1525                                         for (deformindex = 0;deformindex < Q3MAXDEFORMS;deformindex++)
1526                                                 if (!shader->deforms[deformindex].deform)
1527                                                         break;
1528                                         if (deformindex < Q3MAXDEFORMS)
1529                                         {
1530                                                 for (i = 0;i < numparameters - 2 && i < Q3DEFORM_MAXPARMS;i++)
1531                                                         shader->deforms[deformindex].parms[i] = atof(parameter[i+2]);
1532                                                      if (!strcasecmp(parameter[1], "projectionshadow")) shader->deforms[deformindex].deform = Q3DEFORM_PROJECTIONSHADOW;
1533                                                 else if (!strcasecmp(parameter[1], "autosprite"      )) shader->deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE;
1534                                                 else if (!strcasecmp(parameter[1], "autosprite2"     )) shader->deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE2;
1535                                                 else if (!strcasecmp(parameter[1], "text0"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT0;
1536                                                 else if (!strcasecmp(parameter[1], "text1"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT1;
1537                                                 else if (!strcasecmp(parameter[1], "text2"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT2;
1538                                                 else if (!strcasecmp(parameter[1], "text3"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT3;
1539                                                 else if (!strcasecmp(parameter[1], "text4"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT4;
1540                                                 else if (!strcasecmp(parameter[1], "text5"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT5;
1541                                                 else if (!strcasecmp(parameter[1], "text6"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT6;
1542                                                 else if (!strcasecmp(parameter[1], "text7"           )) shader->deforms[deformindex].deform = Q3DEFORM_TEXT7;
1543                                                 else if (!strcasecmp(parameter[1], "bulge"           )) shader->deforms[deformindex].deform = Q3DEFORM_BULGE;
1544                                                 else if (!strcasecmp(parameter[1], "normal"          )) shader->deforms[deformindex].deform = Q3DEFORM_NORMAL;
1545                                                 else if (!strcasecmp(parameter[1], "wave"            ))
1546                                                 {
1547                                                         shader->deforms[deformindex].deform = Q3DEFORM_WAVE;
1548                                                         shader->deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[3]);
1549                                                         for (i = 0;i < numparameters - 4 && i < Q3WAVEPARMS;i++)
1550                                                                 shader->deforms[deformindex].waveparms[i] = atof(parameter[i+4]);
1551                                                 }
1552                                                 else if (!strcasecmp(parameter[1], "move"            ))
1553                                                 {
1554                                                         shader->deforms[deformindex].deform = Q3DEFORM_MOVE;
1555                                                         shader->deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[5]);
1556                                                         for (i = 0;i < numparameters - 6 && i < Q3WAVEPARMS;i++)
1557                                                                 shader->deforms[deformindex].waveparms[i] = atof(parameter[i+6]);
1558                                                 }
1559                                         }
1560                                 }
1561                         }
1562                         // identify if this is a blended terrain shader or similar
1563                         if (shader->numlayers)
1564                         {
1565                                 shader->backgroundlayer = NULL;
1566                                 shader->primarylayer = shader->layers + 0;
1567                                 if ((shader->layers[0].blendfunc[0] == GL_ONE       && shader->layers[0].blendfunc[1] == GL_ZERO                && !shader->layers[0].alphatest)
1568                                 && ((shader->layers[1].blendfunc[0] == GL_SRC_ALPHA && shader->layers[1].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA && !shader->layers[0].alphatest)
1569                                 ||  (shader->layers[1].blendfunc[0] == GL_ONE       && shader->layers[1].blendfunc[1] == GL_ZERO                &&  shader->layers[1].alphatest)))
1570                                 {
1571                                         // terrain blending or other effects
1572                                         shader->backgroundlayer = shader->layers + 0;
1573                                         shader->primarylayer = shader->layers + 1;
1574                                 }
1575                                 // now see if the lightmap came first, and if so choose the second texture instead
1576                                 if (!strcasecmp(shader->primarylayer->texturename[0], "$lightmap"))
1577                                 {
1578                                         shader->backgroundlayer = NULL;
1579                                         shader->primarylayer = shader->layers + 1;
1580                                 }
1581                         }
1582                         // fix up multiple reflection types
1583                         if(shader->textureflags & Q3TEXTUREFLAG_WATERSHADER)
1584                                 shader->textureflags &= ~Q3TEXTUREFLAG_REFLECTION;
1585                 }
1586                 Mem_Free(f);
1587         }
1588 }
1589
1590 q3shaderinfo_t *Mod_LookupQ3Shader(const char *name)
1591 {
1592         int i;
1593         for (i = 0;i < Q3SHADER_MAXSHADERS;i++)
1594                 if (!strcasecmp(q3shaders_shaders[i].name, name))
1595                         return q3shaders_shaders + i;
1596         return NULL;
1597 }
1598
1599 extern cvar_t r_picmipworld;
1600 qboolean Mod_LoadTextureFromQ3Shader(texture_t *texture, const char *name, qboolean q1bsp, qboolean q3bsp, qboolean md3)
1601 {
1602         int j;
1603         int texflags;
1604         qboolean success = true;
1605         q3shaderinfo_t *shader;
1606         strlcpy(texture->name, name, sizeof(texture->name));
1607         shader = name[0] ? Mod_LookupQ3Shader(name) : NULL;
1608         if (shader)
1609         {
1610                 if (developer.integer >= 100)
1611                         Con_DPrintf("%s: loaded shader for %s\n", loadmodel->name, name);
1612                 texture->surfaceparms = shader->surfaceparms;
1613                 texture->textureflags = shader->textureflags;
1614                 texture->basematerialflags = 0;
1615                 if (shader->surfaceparms & Q3SURFACEPARM_SKY)
1616                 {
1617                         texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1618                         if (shader->skyboxname[0])
1619                         {
1620                                 // quake3 seems to append a _ to the skybox name, so this must do so as well
1621                                 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", shader->skyboxname);
1622                         }
1623                 }
1624                 else if ((texture->surfaceflags & Q3SURFACEFLAG_NODRAW) || shader->numlayers == 0)
1625                         texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1626                 else if (shader->surfaceparms & Q3SURFACEPARM_LAVA)
1627                         texture->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_NOSHADOW;
1628                 else if (shader->surfaceparms & Q3SURFACEPARM_SLIME)
1629                         texture->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_WATERALPHA | MATERIALFLAG_NOSHADOW;
1630                 else if (shader->surfaceparms & Q3SURFACEPARM_WATER)
1631                         texture->basematerialflags |= MATERIALFLAG_WATER | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_WATERALPHA | MATERIALFLAG_NOSHADOW;
1632                 else
1633                         texture->basematerialflags |= MATERIALFLAG_WALL;
1634                 if (shader->layers[0].alphatest)
1635                         texture->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
1636                 if (shader->textureflags & Q3TEXTUREFLAG_TWOSIDED)
1637                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
1638                 if (shader->textureflags & Q3TEXTUREFLAG_POLYGONOFFSET)
1639                         texture->basepolygonoffset -= 2;
1640                 if (shader->textureflags & Q3TEXTUREFLAG_REFLECTION)
1641                         texture->basematerialflags |= MATERIALFLAG_REFLECTION;
1642                 if (shader->textureflags & Q3TEXTUREFLAG_WATERSHADER)
1643                         texture->basematerialflags |= MATERIALFLAG_WATERSHADER;
1644                 texture->customblendfunc[0] = GL_ONE;
1645                 texture->customblendfunc[1] = GL_ZERO;
1646                 if (shader->numlayers > 0)
1647                 {
1648                         texture->customblendfunc[0] = shader->layers[0].blendfunc[0];
1649                         texture->customblendfunc[1] = shader->layers[0].blendfunc[1];
1650 /*
1651 Q3 shader blendfuncs actually used in the game (* = supported by DP)
1652 * additive               GL_ONE GL_ONE
1653 additive weird         GL_ONE GL_SRC_ALPHA
1654 additive weird 2       GL_ONE GL_ONE_MINUS_SRC_ALPHA
1655 * alpha                  GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
1656 alpha inverse          GL_ONE_MINUS_SRC_ALPHA GL_SRC_ALPHA
1657 brighten               GL_DST_COLOR GL_ONE
1658 brighten               GL_ONE GL_SRC_COLOR
1659 brighten weird         GL_DST_COLOR GL_ONE_MINUS_DST_ALPHA
1660 brighten weird 2       GL_DST_COLOR GL_SRC_ALPHA
1661 * modulate               GL_DST_COLOR GL_ZERO
1662 * modulate               GL_ZERO GL_SRC_COLOR
1663 modulate inverse       GL_ZERO GL_ONE_MINUS_SRC_COLOR
1664 modulate inverse alpha GL_ZERO GL_SRC_ALPHA
1665 modulate weird inverse GL_ONE_MINUS_DST_COLOR GL_ZERO
1666 * modulate x2            GL_DST_COLOR GL_SRC_COLOR
1667 * no blend               GL_ONE GL_ZERO
1668 nothing                GL_ZERO GL_ONE
1669 */
1670                         // if not opaque, figure out what blendfunc to use
1671                         if (shader->layers[0].blendfunc[0] != GL_ONE || shader->layers[0].blendfunc[1] != GL_ZERO)
1672                         {
1673                                 if (shader->layers[0].blendfunc[0] == GL_ONE && shader->layers[0].blendfunc[1] == GL_ONE)
1674                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1675                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE)
1676                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1677                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
1678                                         texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1679                                 else
1680                                         texture->basematerialflags |= MATERIALFLAG_CUSTOMBLEND | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1681                         }
1682                 }
1683                 if (!shader->lighting)
1684                         texture->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
1685                 if (shader->primarylayer)
1686                 {
1687                         // copy over many shader->primarylayer parameters
1688                         texture->rgbgen = shader->primarylayer->rgbgen;
1689                         texture->alphagen = shader->primarylayer->alphagen;
1690                         texture->tcgen = shader->primarylayer->tcgen;
1691                         memcpy(texture->tcmods, shader->primarylayer->tcmods, sizeof(texture->tcmods));
1692                         // load the textures
1693                         texture->numskinframes = shader->primarylayer->numframes;
1694                         texture->skinframerate = shader->primarylayer->framerate;
1695                         for (j = 0;j < shader->primarylayer->numframes;j++)
1696                         {
1697                                 texflags = TEXF_ALPHA | TEXF_PRECACHE;
1698                                 if (!(shader->surfaceparms & Q3SURFACEPARM_NOMIPMAPS))
1699                                         texflags |= TEXF_MIPMAP;
1700                                 if (!(shader->textureflags & Q3TEXTUREFLAG_NOPICMIP) && ((!q1bsp && !q3bsp) || r_picmipworld.integer))
1701                                         texflags |= TEXF_PICMIP | TEXF_COMPRESS;
1702                                 if (shader->primarylayer->clampmap)
1703                                         texflags |= TEXF_CLAMP;
1704                                 if (!(texture->skinframes[j] = R_SkinFrame_LoadExternal(shader->primarylayer->texturename[j], texflags, false)))
1705                                 {
1706                                         Con_Printf("^4%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);
1707                                         texture->skinframes[j] = R_SkinFrame_LoadMissing();
1708                                 }
1709                         }
1710                 }
1711                 if (shader->backgroundlayer)
1712                 {
1713                         texture->backgroundnumskinframes = shader->backgroundlayer->numframes;
1714                         texture->backgroundskinframerate = shader->backgroundlayer->framerate;
1715                         for (j = 0;j < shader->backgroundlayer->numframes;j++)
1716                         {
1717                                 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)))
1718                                 {
1719                                         Con_Printf("^4%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);
1720                                         texture->backgroundskinframes[j] = R_SkinFrame_LoadMissing();
1721                                 }
1722                         }
1723                 }
1724                 memcpy(texture->deforms, shader->deforms, sizeof(texture->deforms));
1725                 texture->refractmin = shader->refractmin;
1726                 texture->refractmax = shader->refractmax;
1727                 texture->refractfactor = shader->refractfactor;
1728                 VectorCopy(shader->reflectcolor, texture->reflectcolor);
1729                 VectorCopy(shader->refractcolor, texture->refractcolor);
1730         }
1731         else if (!strcmp(texture->name, "noshader"))
1732         {
1733                 if (developer.integer >= 100)
1734                         Con_DPrintf("%s: using default handler for %s\n", loadmodel->name, name);
1735                 texture->surfaceparms = 0;
1736         }
1737         else
1738         {
1739                 success = false;
1740                 if (developer.integer >= 100 || loadmodel->type == mod_brushq3)
1741                         Con_DPrintf("%s: No shader found for texture \"%s\"\n", loadmodel->name, texture->name);
1742                 texture->surfaceparms = 0;
1743                 if (texture->surfaceflags & Q3SURFACEFLAG_NODRAW)
1744                         texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1745                 else if (texture->surfaceflags & Q3SURFACEFLAG_SKY)
1746                         texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1747                 else
1748                         texture->basematerialflags |= MATERIALFLAG_WALL;
1749                 texture->numskinframes = 1;
1750                 if (!(texture->skinframes[0] = R_SkinFrame_LoadExternal(texture->name, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | (r_picmipworld.integer ? TEXF_PICMIP : 0) | TEXF_COMPRESS, false)))
1751                         if(developer.integer || loadmodel->type == mod_brushq3)
1752                                 Con_Printf("^4%s:^7 could not load texture for missing shader ^3\"%s\"\n", loadmodel->name, texture->name);
1753         }
1754         // init the animation variables
1755         texture->currentframe = texture;
1756         if (texture->numskinframes < 1)
1757                 texture->numskinframes = 1;
1758         if (!texture->skinframes[0])
1759                 texture->skinframes[0] = R_SkinFrame_LoadMissing();
1760         texture->currentskinframe = texture->skinframes[0];
1761         texture->backgroundcurrentskinframe = texture->backgroundskinframes[0];
1762         return success;
1763 }
1764
1765 skinfile_t *Mod_LoadSkinFiles(void)
1766 {
1767         int i, words, numtags, line, tagsetsused = false, wordsoverflow;
1768         char *text;
1769         const char *data;
1770         skinfile_t *skinfile = NULL, *first = NULL;
1771         skinfileitem_t *skinfileitem;
1772         char word[10][MAX_QPATH];
1773         overridetagnameset_t tagsets[MAX_SKINS];
1774         overridetagname_t tags[256];
1775
1776 /*
1777 sample file:
1778 U_bodyBox,models/players/Legoman/BikerA2.tga
1779 U_RArm,models/players/Legoman/BikerA1.tga
1780 U_LArm,models/players/Legoman/BikerA1.tga
1781 U_armor,common/nodraw
1782 U_sword,common/nodraw
1783 U_shield,common/nodraw
1784 U_homb,common/nodraw
1785 U_backpack,common/nodraw
1786 U_colcha,common/nodraw
1787 tag_head,
1788 tag_weapon,
1789 tag_torso,
1790 */
1791         memset(tagsets, 0, sizeof(tagsets));
1792         memset(word, 0, sizeof(word));
1793         for (i = 0;i < MAX_SKINS && (data = text = (char *)FS_LoadFile(va("%s_%i.skin", loadmodel->name, i), tempmempool, true, NULL));i++)
1794         {
1795                 numtags = 0;
1796
1797                 // If it's the first file we parse
1798                 if (skinfile == NULL)
1799                 {
1800                         skinfile = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
1801                         first = skinfile;
1802                 }
1803                 else
1804                 {
1805                         skinfile->next = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
1806                         skinfile = skinfile->next;
1807                 }
1808                 skinfile->next = NULL;
1809
1810                 for(line = 0;;line++)
1811                 {
1812                         // parse line
1813                         if (!COM_ParseToken_QuakeC(&data, true))
1814                                 break;
1815                         if (!strcmp(com_token, "\n"))
1816                                 continue;
1817                         words = 0;
1818                         wordsoverflow = false;
1819                         do
1820                         {
1821                                 if (words < 10)
1822                                         strlcpy(word[words++], com_token, sizeof (word[0]));
1823                                 else
1824                                         wordsoverflow = true;
1825                         }
1826                         while (COM_ParseToken_QuakeC(&data, true) && strcmp(com_token, "\n"));
1827                         if (wordsoverflow)
1828                         {
1829                                 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);
1830                                 continue;
1831                         }
1832                         // words is always >= 1
1833                         if (!strcmp(word[0], "replace"))
1834                         {
1835                                 if (words == 3)
1836                                 {
1837                                         Con_DPrintf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[1], word[2]);
1838                                         skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
1839                                         skinfileitem->next = skinfile->items;
1840                                         skinfile->items = skinfileitem;
1841                                         strlcpy (skinfileitem->name, word[1], sizeof (skinfileitem->name));
1842                                         strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
1843                                 }
1844                                 else
1845                                         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]);
1846                         }
1847                         else if (words == 2 && !strcmp(word[1], ","))
1848                         {
1849                                 // tag name, like "tag_weapon,"
1850                                 Con_DPrintf("Mod_LoadSkinFiles: parsed tag #%i \"%s\"\n", numtags, word[0]);
1851                                 memset(tags + numtags, 0, sizeof(tags[numtags]));
1852                                 strlcpy (tags[numtags].name, word[0], sizeof (tags[numtags].name));
1853                                 numtags++;
1854                         }
1855                         else if (words == 3 && !strcmp(word[1], ","))
1856                         {
1857                                 // mesh shader name, like "U_RArm,models/players/Legoman/BikerA1.tga"
1858                                 Con_DPrintf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[0], word[2]);
1859                                 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
1860                                 skinfileitem->next = skinfile->items;
1861                                 skinfile->items = skinfileitem;
1862                                 strlcpy (skinfileitem->name, word[0], sizeof (skinfileitem->name));
1863                                 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
1864                         }
1865                         else
1866                                 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);
1867                 }
1868                 Mem_Free(text);
1869
1870                 if (numtags)
1871                 {
1872                         overridetagnameset_t *t;
1873                         t = tagsets + i;
1874                         t->num_overridetagnames = numtags;
1875                         t->data_overridetagnames = (overridetagname_t *)Mem_Alloc(loadmodel->mempool, t->num_overridetagnames * sizeof(overridetagname_t));
1876                         memcpy(t->data_overridetagnames, tags, t->num_overridetagnames * sizeof(overridetagname_t));
1877                         tagsetsused = true;
1878                 }
1879         }
1880         if (tagsetsused)
1881         {
1882                 loadmodel->data_overridetagnamesforskin = (overridetagnameset_t *)Mem_Alloc(loadmodel->mempool, i * sizeof(overridetagnameset_t));
1883                 memcpy(loadmodel->data_overridetagnamesforskin, tagsets, i * sizeof(overridetagnameset_t));
1884         }
1885         if (i)
1886                 loadmodel->numskins = i;
1887         return first;
1888 }
1889
1890 void Mod_FreeSkinFiles(skinfile_t *skinfile)
1891 {
1892         skinfile_t *next;
1893         skinfileitem_t *skinfileitem, *nextitem;
1894         for (;skinfile;skinfile = next)
1895         {
1896                 next = skinfile->next;
1897                 for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = nextitem)
1898                 {
1899                         nextitem = skinfileitem->next;
1900                         Mem_Free(skinfileitem);
1901                 }
1902                 Mem_Free(skinfile);
1903         }
1904 }
1905
1906 int Mod_CountSkinFiles(skinfile_t *skinfile)
1907 {
1908         int i;
1909         for (i = 0;skinfile;skinfile = skinfile->next, i++);
1910         return i;
1911 }
1912
1913 void Mod_SnapVertices(int numcomponents, int numvertices, float *vertices, float snap)
1914 {
1915         int i;
1916         double isnap = 1.0 / snap;
1917         for (i = 0;i < numvertices*numcomponents;i++)
1918                 vertices[i] = floor(vertices[i]*isnap)*snap;
1919 }
1920
1921 int Mod_RemoveDegenerateTriangles(int numtriangles, const int *inelement3i, int *outelement3i, const float *vertex3f)
1922 {
1923         int i, outtriangles;
1924         float d, edgedir[3], temp[3];
1925         // a degenerate triangle is one with no width (thickness, surface area)
1926         // these are characterized by having all 3 points colinear (along a line)
1927         // or having two points identical
1928         for (i = 0, outtriangles = 0;i < numtriangles;i++, inelement3i += 3)
1929         {
1930                 // calculate first edge
1931                 VectorSubtract(vertex3f + inelement3i[1] * 3, vertex3f + inelement3i[0] * 3, edgedir);
1932                 if (VectorLength2(edgedir) < 0.0001f)
1933                         continue; // degenerate first edge (no length)
1934                 VectorNormalize(edgedir);
1935                 // check if third point is on the edge (colinear)
1936                 d = -DotProduct(vertex3f + inelement3i[2] * 3, edgedir);
1937                 VectorMA(vertex3f + inelement3i[2] * 3, d, edgedir, temp);
1938                 if (VectorLength2(temp) < 0.0001f)
1939                         continue; // third point colinear with first edge
1940                 // valid triangle (no colinear points, no duplicate points)
1941                 VectorCopy(inelement3i, outelement3i);
1942                 outelement3i += 3;
1943                 outtriangles++;
1944         }
1945         return outtriangles;
1946 }
1947
1948 void Mod_VertexRangeFromElements(int numelements, const int *elements, int *firstvertexpointer, int *lastvertexpointer)
1949 {
1950         int i, e;
1951         int firstvertex, lastvertex;
1952         if (numelements > 0 && elements)
1953         {
1954                 firstvertex = lastvertex = elements[0];
1955                 for (i = 1;i < numelements;i++)
1956                 {
1957                         e = elements[i];
1958                         firstvertex = min(firstvertex, e);
1959                         lastvertex = max(lastvertex, e);
1960                 }
1961         }
1962         else
1963                 firstvertex = lastvertex = 0;
1964         if (firstvertexpointer)
1965                 *firstvertexpointer = firstvertex;
1966         if (lastvertexpointer)
1967                 *lastvertexpointer = lastvertex;
1968 }
1969
1970 static void Mod_BuildVBOs(void)
1971 {
1972         if (!gl_support_arb_vertex_buffer_object)
1973                 return;
1974
1975         // element buffer is easy because it's just one array
1976         if (loadmodel->surfmesh.num_triangles)
1977                 loadmodel->surfmesh.ebo = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles * sizeof(int[3]), loadmodel->name);
1978
1979         // vertex buffer is several arrays and we put them in the same buffer
1980         //
1981         // is this wise?  the texcoordtexture2f array is used with dynamic
1982         // vertex/svector/tvector/normal when rendering animated models, on the
1983         // other hand animated models don't use a lot of vertices anyway...
1984         if (loadmodel->surfmesh.num_vertices)
1985         {
1986                 size_t size;
1987                 unsigned char *mem;
1988                 size = 0;
1989                 loadmodel->surfmesh.vbooffset_vertex3f           = size;if (loadmodel->surfmesh.data_vertex3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
1990                 loadmodel->surfmesh.vbooffset_svector3f          = size;if (loadmodel->surfmesh.data_svector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
1991                 loadmodel->surfmesh.vbooffset_tvector3f          = size;if (loadmodel->surfmesh.data_tvector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
1992                 loadmodel->surfmesh.vbooffset_normal3f           = size;if (loadmodel->surfmesh.data_normal3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
1993                 loadmodel->surfmesh.vbooffset_texcoordtexture2f  = size;if (loadmodel->surfmesh.data_texcoordtexture2f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
1994                 loadmodel->surfmesh.vbooffset_texcoordlightmap2f = size;if (loadmodel->surfmesh.data_texcoordlightmap2f) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
1995                 loadmodel->surfmesh.vbooffset_lightmapcolor4f    = size;if (loadmodel->surfmesh.data_lightmapcolor4f   ) size += loadmodel->surfmesh.num_vertices * sizeof(float[4]);
1996                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
1997                 if (loadmodel->surfmesh.data_vertex3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_vertex3f          , loadmodel->surfmesh.data_vertex3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
1998                 if (loadmodel->surfmesh.data_svector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_svector3f         , loadmodel->surfmesh.data_svector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
1999                 if (loadmodel->surfmesh.data_tvector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_tvector3f         , loadmodel->surfmesh.data_tvector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2000                 if (loadmodel->surfmesh.data_normal3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_normal3f          , loadmodel->surfmesh.data_normal3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2001                 if (loadmodel->surfmesh.data_texcoordtexture2f ) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordtexture2f , loadmodel->surfmesh.data_texcoordtexture2f , loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2002                 if (loadmodel->surfmesh.data_texcoordlightmap2f) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordlightmap2f, loadmodel->surfmesh.data_texcoordlightmap2f, loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2003                 if (loadmodel->surfmesh.data_lightmapcolor4f   ) memcpy(mem + loadmodel->surfmesh.vbooffset_lightmapcolor4f   , loadmodel->surfmesh.data_lightmapcolor4f   , loadmodel->surfmesh.num_vertices * sizeof(float[4]));
2004                 loadmodel->surfmesh.vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, loadmodel->name);
2005                 Mem_Free(mem);
2006         }
2007 }