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