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