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