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