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