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