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