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