redesigned skeletal model animation bone pose format - instead of
[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;
659         edgehashentry_t *edgehashentries, *hash;
660         if (!numtriangles)
661                 return;
662         edgehash = Mem_Alloc(tempmempool, TRIANGLEEDGEHASH * 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         Mem_Free(edgehash);
715 }
716 #else
717 // very slow but simple way
718 static int Mod_FindTriangleWithEdge(const int *elements, int numtriangles, int start, int end, int ignore)
719 {
720         int i, match, count;
721         count = 0;
722         match = -1;
723         for (i = 0;i < numtriangles;i++, elements += 3)
724         {
725                      if ((elements[0] == start && elements[1] == end)
726                       || (elements[1] == start && elements[2] == end)
727                       || (elements[2] == start && elements[0] == end))
728                 {
729                         if (i != ignore)
730                                 match = i;
731                         count++;
732                 }
733                 else if ((elements[1] == start && elements[0] == end)
734                       || (elements[2] == start && elements[1] == end)
735                       || (elements[0] == start && elements[2] == end))
736                         count++;
737         }
738         // detect edges shared by three triangles and make them seams
739         if (count > 2)
740                 match = -1;
741         return match;
742 }
743
744 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
745 {
746         int i, *n;
747         const int *e;
748         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
749         {
750                 n[0] = Mod_FindTriangleWithEdge(elements, numtriangles, e[1], e[0], i);
751                 n[1] = Mod_FindTriangleWithEdge(elements, numtriangles, e[2], e[1], i);
752                 n[2] = Mod_FindTriangleWithEdge(elements, numtriangles, e[0], e[2], i);
753         }
754 }
755 #endif
756
757 void Mod_ValidateElements(int *elements, int numtriangles, int firstvertex, int numverts, const char *filename, int fileline)
758 {
759         int i, warned = false, endvertex = firstvertex + numverts;
760         for (i = 0;i < numtriangles * 3;i++)
761         {
762                 if (elements[i] < firstvertex || elements[i] >= endvertex)
763                 {
764                         if (!warned)
765                         {
766                                 warned = true;
767                                 Con_Printf("Mod_ValidateElements: out of bounds elements detected at %s:%d\n", filename, fileline);
768                         }
769                         elements[i] = firstvertex;
770                 }
771         }
772 }
773
774 // warning: this is an expensive function!
775 void Mod_BuildNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const int *elements, float *normal3f, qboolean areaweighting)
776 {
777         int i, j;
778         const int *element;
779         float *vectorNormal;
780         float areaNormal[3];
781         // clear the vectors
782         memset(normal3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
783         // process each vertex of each triangle and accumulate the results
784         // use area-averaging, to make triangles with a big area have a bigger
785         // weighting on the vertex normal than triangles with a small area
786         // to do so, just add the 'normals' together (the bigger the area
787         // the greater the length of the normal is
788         element = elements;
789         for (i = 0; i < numtriangles; i++, element += 3)
790         {
791                 TriangleNormal(
792                         vertex3f + element[0] * 3,
793                         vertex3f + element[1] * 3,
794                         vertex3f + element[2] * 3,
795                         areaNormal
796                         );
797
798                 if (!areaweighting)
799                         VectorNormalize(areaNormal);
800
801                 for (j = 0;j < 3;j++)
802                 {
803                         vectorNormal = normal3f + element[j] * 3;
804                         vectorNormal[0] += areaNormal[0];
805                         vectorNormal[1] += areaNormal[1];
806                         vectorNormal[2] += areaNormal[2];
807                 }
808         }
809         // and just normalize the accumulated vertex normal in the end
810         vectorNormal = normal3f + 3 * firstvertex;
811         for (i = 0; i < numvertices; i++, vectorNormal += 3)
812                 VectorNormalize(vectorNormal);
813 }
814
815 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)
816 {
817         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
818         // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
819         // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
820
821         // 6 multiply, 9 subtract
822         VectorSubtract(v1, v0, v10);
823         VectorSubtract(v2, v0, v20);
824         normal3f[0] = v20[1] * v10[2] - v20[2] * v10[1];
825         normal3f[1] = v20[2] * v10[0] - v20[0] * v10[2];
826         normal3f[2] = v20[0] * v10[1] - v20[1] * v10[0];
827         // 12 multiply, 10 subtract
828         tc10[1] = tc1[1] - tc0[1];
829         tc20[1] = tc2[1] - tc0[1];
830         svector3f[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
831         svector3f[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
832         svector3f[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
833         tc10[0] = tc1[0] - tc0[0];
834         tc20[0] = tc2[0] - tc0[0];
835         tvector3f[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
836         tvector3f[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
837         tvector3f[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
838         // 12 multiply, 4 add, 6 subtract
839         f = DotProduct(svector3f, normal3f);
840         svector3f[0] -= f * normal3f[0];
841         svector3f[1] -= f * normal3f[1];
842         svector3f[2] -= f * normal3f[2];
843         f = DotProduct(tvector3f, normal3f);
844         tvector3f[0] -= f * normal3f[0];
845         tvector3f[1] -= f * normal3f[1];
846         tvector3f[2] -= f * normal3f[2];
847         // if texture is mapped the wrong way (counterclockwise), the tangents
848         // have to be flipped, this is detected by calculating a normal from the
849         // two tangents, and seeing if it is opposite the surface normal
850         // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
851         CrossProduct(tvector3f, svector3f, tangentcross);
852         if (DotProduct(tangentcross, normal3f) < 0)
853         {
854                 VectorNegate(svector3f, svector3f);
855                 VectorNegate(tvector3f, tvector3f);
856         }
857 }
858
859 // warning: this is a very expensive function!
860 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)
861 {
862         int i, tnum;
863         float sdir[3], tdir[3], normal[3], *sv, *tv;
864         const float *v0, *v1, *v2, *tc0, *tc1, *tc2, *n;
865         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
866         const int *e;
867         // clear the vectors
868         memset(svector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
869         memset(tvector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
870         // process each vertex of each triangle and accumulate the results
871         for (tnum = 0, e = elements;tnum < numtriangles;tnum++, e += 3)
872         {
873                 v0 = vertex3f + e[0] * 3;
874                 v1 = vertex3f + e[1] * 3;
875                 v2 = vertex3f + e[2] * 3;
876                 tc0 = texcoord2f + e[0] * 2;
877                 tc1 = texcoord2f + e[1] * 2;
878                 tc2 = texcoord2f + e[2] * 2;
879
880                 // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
881                 // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
882
883                 // calculate the edge directions and surface normal
884                 // 6 multiply, 9 subtract
885                 VectorSubtract(v1, v0, v10);
886                 VectorSubtract(v2, v0, v20);
887                 normal[0] = v20[1] * v10[2] - v20[2] * v10[1];
888                 normal[1] = v20[2] * v10[0] - v20[0] * v10[2];
889                 normal[2] = v20[0] * v10[1] - v20[1] * v10[0];
890
891                 // calculate the tangents
892                 // 12 multiply, 10 subtract
893                 tc10[1] = tc1[1] - tc0[1];
894                 tc20[1] = tc2[1] - tc0[1];
895                 sdir[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
896                 sdir[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
897                 sdir[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
898                 tc10[0] = tc1[0] - tc0[0];
899                 tc20[0] = tc2[0] - tc0[0];
900                 tdir[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
901                 tdir[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
902                 tdir[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
903
904                 // if texture is mapped the wrong way (counterclockwise), the tangents
905                 // have to be flipped, this is detected by calculating a normal from the
906                 // two tangents, and seeing if it is opposite the surface normal
907                 // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
908                 CrossProduct(tdir, sdir, tangentcross);
909                 if (DotProduct(tangentcross, normal) < 0)
910                 {
911                         VectorNegate(sdir, sdir);
912                         VectorNegate(tdir, tdir);
913                 }
914
915                 if (!areaweighting)
916                 {
917                         VectorNormalize(sdir);
918                         VectorNormalize(tdir);
919                 }
920                 for (i = 0;i < 3;i++)
921                 {
922                         VectorAdd(svector3f + e[i]*3, sdir, svector3f + e[i]*3);
923                         VectorAdd(tvector3f + e[i]*3, tdir, tvector3f + e[i]*3);
924                 }
925         }
926         // make the tangents completely perpendicular to the surface normal, and
927         // then normalize them
928         // 16 assignments, 2 divide, 2 sqrt, 2 negates, 14 adds, 24 multiplies
929         for (i = 0, sv = svector3f + 3 * firstvertex, tv = tvector3f + 3 * firstvertex, n = normal3f + 3 * firstvertex;i < numvertices;i++, sv += 3, tv += 3, n += 3)
930         {
931                 f = -DotProduct(sv, n);
932                 VectorMA(sv, f, n, sv);
933                 VectorNormalize(sv);
934                 f = -DotProduct(tv, n);
935                 VectorMA(tv, f, n, tv);
936                 VectorNormalize(tv);
937         }
938 }
939
940 void Mod_AllocSurfMesh(mempool_t *mempool, int numvertices, int numtriangles, qboolean lightmapoffsets, qboolean vertexcolors, qboolean neighbors)
941 {
942         unsigned char *data;
943         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));
944         loadmodel->surfmesh.num_vertices = numvertices;
945         loadmodel->surfmesh.num_triangles = numtriangles;
946         if (loadmodel->surfmesh.num_vertices)
947         {
948                 loadmodel->surfmesh.data_vertex3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
949                 loadmodel->surfmesh.data_svector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
950                 loadmodel->surfmesh.data_tvector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
951                 loadmodel->surfmesh.data_normal3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
952                 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
953                 loadmodel->surfmesh.data_texcoordlightmap2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
954                 if (vertexcolors)
955                         loadmodel->surfmesh.data_lightmapcolor4f = (float *)data, data += sizeof(float[4]) * loadmodel->surfmesh.num_vertices;
956                 if (lightmapoffsets)
957                         loadmodel->surfmesh.data_lightmapoffsets = (int *)data, data += sizeof(int) * loadmodel->surfmesh.num_vertices;
958         }
959         if (loadmodel->surfmesh.num_triangles)
960         {
961                 loadmodel->surfmesh.data_element3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
962                 if (neighbors)
963                         loadmodel->surfmesh.data_neighbor3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
964                 if (loadmodel->surfmesh.num_vertices <= 65536)
965                         loadmodel->surfmesh.data_element3s = (unsigned short *)data, data += sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles;
966         }
967 }
968
969 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)
970 {
971         shadowmesh_t *newmesh;
972         unsigned char *data;
973         int size;
974         size = sizeof(shadowmesh_t);
975         size += maxverts * sizeof(float[3]);
976         if (light)
977                 size += maxverts * sizeof(float[11]);
978         size += maxtriangles * sizeof(int[3]);
979         if (maxverts <= 65536)
980                 size += maxtriangles * sizeof(unsigned short[3]);
981         if (neighbors)
982                 size += maxtriangles * sizeof(int[3]);
983         if (expandable)
984                 size += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *) + maxverts * sizeof(shadowmeshvertexhash_t);
985         data = (unsigned char *)Mem_Alloc(mempool, size);
986         newmesh = (shadowmesh_t *)data;data += sizeof(*newmesh);
987         newmesh->map_diffuse = map_diffuse;
988         newmesh->map_specular = map_specular;
989         newmesh->map_normal = map_normal;
990         newmesh->maxverts = maxverts;
991         newmesh->maxtriangles = maxtriangles;
992         newmesh->numverts = 0;
993         newmesh->numtriangles = 0;
994         memset(newmesh->sideoffsets, 0, sizeof(newmesh->sideoffsets));
995         memset(newmesh->sidetotals, 0, sizeof(newmesh->sidetotals));
996
997         newmesh->vertex3f = (float *)data;data += maxverts * sizeof(float[3]);
998         if (light)
999         {
1000                 newmesh->svector3f = (float *)data;data += maxverts * sizeof(float[3]);
1001                 newmesh->tvector3f = (float *)data;data += maxverts * sizeof(float[3]);
1002                 newmesh->normal3f = (float *)data;data += maxverts * sizeof(float[3]);
1003                 newmesh->texcoord2f = (float *)data;data += maxverts * sizeof(float[2]);
1004         }
1005         newmesh->element3i = (int *)data;data += maxtriangles * sizeof(int[3]);
1006         if (neighbors)
1007         {
1008                 newmesh->neighbor3i = (int *)data;data += maxtriangles * sizeof(int[3]);
1009         }
1010         if (expandable)
1011         {
1012                 newmesh->vertexhashtable = (shadowmeshvertexhash_t **)data;data += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *);
1013                 newmesh->vertexhashentries = (shadowmeshvertexhash_t *)data;data += maxverts * sizeof(shadowmeshvertexhash_t);
1014         }
1015         if (maxverts <= 65536)
1016                 newmesh->element3s = (unsigned short *)data;data += maxtriangles * sizeof(unsigned short[3]);
1017         return newmesh;
1018 }
1019
1020 shadowmesh_t *Mod_ShadowMesh_ReAlloc(mempool_t *mempool, shadowmesh_t *oldmesh, int light, int neighbors)
1021 {
1022         shadowmesh_t *newmesh;
1023         newmesh = Mod_ShadowMesh_Alloc(mempool, oldmesh->numverts, oldmesh->numtriangles, oldmesh->map_diffuse, oldmesh->map_specular, oldmesh->map_normal, light, neighbors, false);
1024         newmesh->numverts = oldmesh->numverts;
1025         newmesh->numtriangles = oldmesh->numtriangles;
1026         memcpy(newmesh->sideoffsets, oldmesh->sideoffsets, sizeof(oldmesh->sideoffsets));
1027         memcpy(newmesh->sidetotals, oldmesh->sidetotals, sizeof(oldmesh->sidetotals));
1028
1029         memcpy(newmesh->vertex3f, oldmesh->vertex3f, oldmesh->numverts * sizeof(float[3]));
1030         if (newmesh->svector3f && oldmesh->svector3f)
1031         {
1032                 memcpy(newmesh->svector3f, oldmesh->svector3f, oldmesh->numverts * sizeof(float[3]));
1033                 memcpy(newmesh->tvector3f, oldmesh->tvector3f, oldmesh->numverts * sizeof(float[3]));
1034                 memcpy(newmesh->normal3f, oldmesh->normal3f, oldmesh->numverts * sizeof(float[3]));
1035                 memcpy(newmesh->texcoord2f, oldmesh->texcoord2f, oldmesh->numverts * sizeof(float[2]));
1036         }
1037         memcpy(newmesh->element3i, oldmesh->element3i, oldmesh->numtriangles * sizeof(int[3]));
1038         if (newmesh->neighbor3i && oldmesh->neighbor3i)
1039                 memcpy(newmesh->neighbor3i, oldmesh->neighbor3i, oldmesh->numtriangles * sizeof(int[3]));
1040         return newmesh;
1041 }
1042
1043 int Mod_ShadowMesh_AddVertex(shadowmesh_t *mesh, float *vertex14f)
1044 {
1045         int hashindex, vnum;
1046         shadowmeshvertexhash_t *hash;
1047         // this uses prime numbers intentionally
1048         hashindex = (unsigned int) (vertex14f[0] * 2003 + vertex14f[1] * 4001 + vertex14f[2] * 7919) % SHADOWMESHVERTEXHASH;
1049         for (hash = mesh->vertexhashtable[hashindex];hash;hash = hash->next)
1050         {
1051                 vnum = (hash - mesh->vertexhashentries);
1052                 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]))
1053                  && (mesh->svector3f == NULL || (mesh->svector3f[vnum * 3 + 0] == vertex14f[3] && mesh->svector3f[vnum * 3 + 1] == vertex14f[4] && mesh->svector3f[vnum * 3 + 2] == vertex14f[5]))
1054                  && (mesh->tvector3f == NULL || (mesh->tvector3f[vnum * 3 + 0] == vertex14f[6] && mesh->tvector3f[vnum * 3 + 1] == vertex14f[7] && mesh->tvector3f[vnum * 3 + 2] == vertex14f[8]))
1055                  && (mesh->normal3f == NULL || (mesh->normal3f[vnum * 3 + 0] == vertex14f[9] && mesh->normal3f[vnum * 3 + 1] == vertex14f[10] && mesh->normal3f[vnum * 3 + 2] == vertex14f[11]))
1056                  && (mesh->texcoord2f == NULL || (mesh->texcoord2f[vnum * 2 + 0] == vertex14f[12] && mesh->texcoord2f[vnum * 2 + 1] == vertex14f[13])))
1057                         return hash - mesh->vertexhashentries;
1058         }
1059         vnum = mesh->numverts++;
1060         hash = mesh->vertexhashentries + vnum;
1061         hash->next = mesh->vertexhashtable[hashindex];
1062         mesh->vertexhashtable[hashindex] = hash;
1063         if (mesh->vertex3f) {mesh->vertex3f[vnum * 3 + 0] = vertex14f[0];mesh->vertex3f[vnum * 3 + 1] = vertex14f[1];mesh->vertex3f[vnum * 3 + 2] = vertex14f[2];}
1064         if (mesh->svector3f) {mesh->svector3f[vnum * 3 + 0] = vertex14f[3];mesh->svector3f[vnum * 3 + 1] = vertex14f[4];mesh->svector3f[vnum * 3 + 2] = vertex14f[5];}
1065         if (mesh->tvector3f) {mesh->tvector3f[vnum * 3 + 0] = vertex14f[6];mesh->tvector3f[vnum * 3 + 1] = vertex14f[7];mesh->tvector3f[vnum * 3 + 2] = vertex14f[8];}
1066         if (mesh->normal3f) {mesh->normal3f[vnum * 3 + 0] = vertex14f[9];mesh->normal3f[vnum * 3 + 1] = vertex14f[10];mesh->normal3f[vnum * 3 + 2] = vertex14f[11];}
1067         if (mesh->texcoord2f) {mesh->texcoord2f[vnum * 2 + 0] = vertex14f[12];mesh->texcoord2f[vnum * 2 + 1] = vertex14f[13];}
1068         return vnum;
1069 }
1070
1071 void Mod_ShadowMesh_AddTriangle(mempool_t *mempool, shadowmesh_t *mesh, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, float *vertex14f)
1072 {
1073         if (mesh->numtriangles == 0)
1074         {
1075                 // set the properties on this empty mesh to be more favorable...
1076                 // (note: this case only occurs for the first triangle added to a new mesh chain)
1077                 mesh->map_diffuse = map_diffuse;
1078                 mesh->map_specular = map_specular;
1079                 mesh->map_normal = map_normal;
1080         }
1081         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)
1082         {
1083                 if (mesh->next == NULL)
1084                         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);
1085                 mesh = mesh->next;
1086         }
1087         mesh->element3i[mesh->numtriangles * 3 + 0] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 0);
1088         mesh->element3i[mesh->numtriangles * 3 + 1] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 1);
1089         mesh->element3i[mesh->numtriangles * 3 + 2] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 2);
1090         mesh->numtriangles++;
1091 }
1092
1093 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)
1094 {
1095         int i, j, e;
1096         float vbuf[3*14], *v;
1097         memset(vbuf, 0, sizeof(vbuf));
1098         for (i = 0;i < numtris;i++)
1099         {
1100                 for (j = 0, v = vbuf;j < 3;j++, v += 14)
1101                 {
1102                         e = *element3i++;
1103                         if (vertex3f)
1104                         {
1105                                 v[0] = vertex3f[e * 3 + 0];
1106                                 v[1] = vertex3f[e * 3 + 1];
1107                                 v[2] = vertex3f[e * 3 + 2];
1108                         }
1109                         if (svector3f)
1110                         {
1111                                 v[3] = svector3f[e * 3 + 0];
1112                                 v[4] = svector3f[e * 3 + 1];
1113                                 v[5] = svector3f[e * 3 + 2];
1114                         }
1115                         if (tvector3f)
1116                         {
1117                                 v[6] = tvector3f[e * 3 + 0];
1118                                 v[7] = tvector3f[e * 3 + 1];
1119                                 v[8] = tvector3f[e * 3 + 2];
1120                         }
1121                         if (normal3f)
1122                         {
1123                                 v[9] = normal3f[e * 3 + 0];
1124                                 v[10] = normal3f[e * 3 + 1];
1125                                 v[11] = normal3f[e * 3 + 2];
1126                         }
1127                         if (texcoord2f)
1128                         {
1129                                 v[12] = texcoord2f[e * 2 + 0];
1130                                 v[13] = texcoord2f[e * 2 + 1];
1131                         }
1132                 }
1133                 Mod_ShadowMesh_AddTriangle(mempool, mesh, map_diffuse, map_specular, map_normal, vbuf);
1134         }
1135
1136         // the triangle calculation can take a while, so let's do a keepalive here
1137         CL_KeepaliveMessage(false);
1138 }
1139
1140 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)
1141 {
1142         // the preparation before shadow mesh initialization can take a while, so let's do a keepalive here
1143         CL_KeepaliveMessage(false);
1144
1145         return Mod_ShadowMesh_Alloc(mempool, maxverts, maxtriangles, map_diffuse, map_specular, map_normal, light, neighbors, expandable);
1146 }
1147
1148 static void Mod_ShadowMesh_CreateVBOs(shadowmesh_t *mesh)
1149 {
1150         if (!vid.support.arb_vertex_buffer_object)
1151                 return;
1152
1153         // element buffer is easy because it's just one array
1154         if (mesh->numtriangles)
1155         {
1156                 if (mesh->element3s)
1157                         mesh->ebo3s = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, mesh->element3s, mesh->numtriangles * sizeof(unsigned short[3]), "shadowmesh");
1158                 else
1159                         mesh->ebo3i = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, mesh->element3i, mesh->numtriangles * sizeof(unsigned int[3]), "shadowmesh");
1160         }
1161
1162         // vertex buffer is several arrays and we put them in the same buffer
1163         //
1164         // is this wise?  the texcoordtexture2f array is used with dynamic
1165         // vertex/svector/tvector/normal when rendering animated models, on the
1166         // other hand animated models don't use a lot of vertices anyway...
1167         if (mesh->numverts)
1168         {
1169                 size_t size;
1170                 unsigned char *mem;
1171                 size = 0;
1172                 mesh->vbooffset_vertex3f           = size;if (mesh->vertex3f          ) size += mesh->numverts * sizeof(float[3]);
1173                 mesh->vbooffset_svector3f          = size;if (mesh->svector3f         ) size += mesh->numverts * sizeof(float[3]);
1174                 mesh->vbooffset_tvector3f          = size;if (mesh->tvector3f         ) size += mesh->numverts * sizeof(float[3]);
1175                 mesh->vbooffset_normal3f           = size;if (mesh->normal3f          ) size += mesh->numverts * sizeof(float[3]);
1176                 mesh->vbooffset_texcoord2f         = size;if (mesh->texcoord2f        ) size += mesh->numverts * sizeof(float[2]);
1177                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
1178                 if (mesh->vertex3f          ) memcpy(mem + mesh->vbooffset_vertex3f          , mesh->vertex3f          , mesh->numverts * sizeof(float[3]));
1179                 if (mesh->svector3f         ) memcpy(mem + mesh->vbooffset_svector3f         , mesh->svector3f         , mesh->numverts * sizeof(float[3]));
1180                 if (mesh->tvector3f         ) memcpy(mem + mesh->vbooffset_tvector3f         , mesh->tvector3f         , mesh->numverts * sizeof(float[3]));
1181                 if (mesh->normal3f          ) memcpy(mem + mesh->vbooffset_normal3f          , mesh->normal3f          , mesh->numverts * sizeof(float[3]));
1182                 if (mesh->texcoord2f        ) memcpy(mem + mesh->vbooffset_texcoord2f        , mesh->texcoord2f        , mesh->numverts * sizeof(float[2]));
1183                 mesh->vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, "shadowmesh");
1184                 Mem_Free(mem);
1185         }
1186 }
1187
1188 shadowmesh_t *Mod_ShadowMesh_Finish(mempool_t *mempool, shadowmesh_t *firstmesh, qboolean light, qboolean neighbors, qboolean createvbo)
1189 {
1190         shadowmesh_t *mesh, *newmesh, *nextmesh;
1191         // reallocate meshs to conserve space
1192         for (mesh = firstmesh, firstmesh = NULL;mesh;mesh = nextmesh)
1193         {
1194                 nextmesh = mesh->next;
1195                 if (mesh->numverts >= 3 && mesh->numtriangles >= 1)
1196                 {
1197                         newmesh = Mod_ShadowMesh_ReAlloc(mempool, mesh, light, neighbors);
1198                         newmesh->next = firstmesh;
1199                         firstmesh = newmesh;
1200                         if (newmesh->element3s)
1201                         {
1202                                 int i;
1203                                 for (i = 0;i < newmesh->numtriangles*3;i++)
1204                                         newmesh->element3s[i] = newmesh->element3i[i];
1205                         }
1206                         if (createvbo)
1207                                 Mod_ShadowMesh_CreateVBOs(newmesh);
1208                 }
1209                 Mem_Free(mesh);
1210         }
1211
1212         // this can take a while, so let's do a keepalive here
1213         CL_KeepaliveMessage(false);
1214
1215         return firstmesh;
1216 }
1217
1218 void Mod_ShadowMesh_CalcBBox(shadowmesh_t *firstmesh, vec3_t mins, vec3_t maxs, vec3_t center, float *radius)
1219 {
1220         int i;
1221         shadowmesh_t *mesh;
1222         vec3_t nmins, nmaxs, ncenter, temp;
1223         float nradius2, dist2, *v;
1224         VectorClear(nmins);
1225         VectorClear(nmaxs);
1226         // calculate bbox
1227         for (mesh = firstmesh;mesh;mesh = mesh->next)
1228         {
1229                 if (mesh == firstmesh)
1230                 {
1231                         VectorCopy(mesh->vertex3f, nmins);
1232                         VectorCopy(mesh->vertex3f, nmaxs);
1233                 }
1234                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1235                 {
1236                         if (nmins[0] > v[0]) nmins[0] = v[0];if (nmaxs[0] < v[0]) nmaxs[0] = v[0];
1237                         if (nmins[1] > v[1]) nmins[1] = v[1];if (nmaxs[1] < v[1]) nmaxs[1] = v[1];
1238                         if (nmins[2] > v[2]) nmins[2] = v[2];if (nmaxs[2] < v[2]) nmaxs[2] = v[2];
1239                 }
1240         }
1241         // calculate center and radius
1242         ncenter[0] = (nmins[0] + nmaxs[0]) * 0.5f;
1243         ncenter[1] = (nmins[1] + nmaxs[1]) * 0.5f;
1244         ncenter[2] = (nmins[2] + nmaxs[2]) * 0.5f;
1245         nradius2 = 0;
1246         for (mesh = firstmesh;mesh;mesh = mesh->next)
1247         {
1248                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1249                 {
1250                         VectorSubtract(v, ncenter, temp);
1251                         dist2 = DotProduct(temp, temp);
1252                         if (nradius2 < dist2)
1253                                 nradius2 = dist2;
1254                 }
1255         }
1256         // return data
1257         if (mins)
1258                 VectorCopy(nmins, mins);
1259         if (maxs)
1260                 VectorCopy(nmaxs, maxs);
1261         if (center)
1262                 VectorCopy(ncenter, center);
1263         if (radius)
1264                 *radius = sqrt(nradius2);
1265 }
1266
1267 void Mod_ShadowMesh_Free(shadowmesh_t *mesh)
1268 {
1269         shadowmesh_t *nextmesh;
1270         for (;mesh;mesh = nextmesh)
1271         {
1272                 if (mesh->ebo3i)
1273                         R_Mesh_DestroyBufferObject(mesh->ebo3i);
1274                 if (mesh->ebo3s)
1275                         R_Mesh_DestroyBufferObject(mesh->ebo3s);
1276                 if (mesh->vbo)
1277                         R_Mesh_DestroyBufferObject(mesh->vbo);
1278                 nextmesh = mesh->next;
1279                 Mem_Free(mesh);
1280         }
1281 }
1282
1283 void Mod_CreateCollisionMesh(dp_model_t *mod)
1284 {
1285         int k;
1286         int numcollisionmeshtriangles;
1287         const msurface_t *surface;
1288         mempool_t *mempool = mod->mempool;
1289         if (!mempool && mod->brush.parentmodel)
1290                 mempool = mod->brush.parentmodel->mempool;
1291         // make a single combined collision mesh for physics engine use
1292         // TODO rewrite this to use the collision brushes as source, to fix issues with e.g. common/caulk which creates no drawsurface
1293         numcollisionmeshtriangles = 0;
1294         for (k = 0;k < mod->nummodelsurfaces;k++)
1295         {
1296                 surface = mod->data_surfaces + mod->firstmodelsurface + k;
1297                 if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1298                         continue;
1299                 numcollisionmeshtriangles += surface->num_triangles;
1300         }
1301         mod->brush.collisionmesh = Mod_ShadowMesh_Begin(mempool, numcollisionmeshtriangles * 3, numcollisionmeshtriangles, NULL, NULL, NULL, false, false, true);
1302         for (k = 0;k < mod->nummodelsurfaces;k++)
1303         {
1304                 surface = mod->data_surfaces + mod->firstmodelsurface + k;
1305                 if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1306                         continue;
1307                 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));
1308         }
1309         mod->brush.collisionmesh = Mod_ShadowMesh_Finish(mempool, mod->brush.collisionmesh, false, true, false);
1310 }
1311
1312 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)
1313 {
1314         float v[3], tc[3];
1315         v[0] = ix;
1316         v[1] = iy;
1317         if (ix >= 0 && iy >= 0 && ix < imagewidth && iy < imageheight)
1318                 v[2] = (imagepixels[((iy*imagewidth)+ix)*4+0] + imagepixels[((iy*imagewidth)+ix)*4+1] + imagepixels[((iy*imagewidth)+ix)*4+2]) * (1.0f / 765.0f);
1319         else
1320                 v[2] = 0;
1321         Matrix4x4_Transform(pixelstepmatrix, v, vertex3f);
1322         Matrix4x4_Transform(pixeltexturestepmatrix, v, tc);
1323         texcoord2f[0] = tc[0];
1324         texcoord2f[1] = tc[1];
1325 }
1326
1327 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)
1328 {
1329         float vup[3], vdown[3], vleft[3], vright[3];
1330         float tcup[3], tcdown[3], tcleft[3], tcright[3];
1331         float sv[3], tv[3], nl[3];
1332         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, pixelstepmatrix, pixeltexturestepmatrix);
1333         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy - 1, vup, tcup, pixelstepmatrix, pixeltexturestepmatrix);
1334         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy + 1, vdown, tcdown, pixelstepmatrix, pixeltexturestepmatrix);
1335         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix - 1, iy, vleft, tcleft, pixelstepmatrix, pixeltexturestepmatrix);
1336         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix + 1, iy, vright, tcright, pixelstepmatrix, pixeltexturestepmatrix);
1337         Mod_BuildBumpVectors(vertex3f, vup, vright, texcoord2f, tcup, tcright, svector3f, tvector3f, normal3f);
1338         Mod_BuildBumpVectors(vertex3f, vright, vdown, texcoord2f, tcright, tcdown, sv, tv, nl);
1339         VectorAdd(svector3f, sv, svector3f);
1340         VectorAdd(tvector3f, tv, tvector3f);
1341         VectorAdd(normal3f, nl, normal3f);
1342         Mod_BuildBumpVectors(vertex3f, vdown, vleft, texcoord2f, tcdown, tcleft, sv, tv, nl);
1343         VectorAdd(svector3f, sv, svector3f);
1344         VectorAdd(tvector3f, tv, tvector3f);
1345         VectorAdd(normal3f, nl, normal3f);
1346         Mod_BuildBumpVectors(vertex3f, vleft, vup, texcoord2f, tcleft, tcup, sv, tv, nl);
1347         VectorAdd(svector3f, sv, svector3f);
1348         VectorAdd(tvector3f, tv, tvector3f);
1349         VectorAdd(normal3f, nl, normal3f);
1350 }
1351
1352 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)
1353 {
1354         int x, y, ix, iy, *e;
1355         e = element3i;
1356         for (y = 0;y < height;y++)
1357         {
1358                 for (x = 0;x < width;x++)
1359                 {
1360                         e[0] = (y + 1) * (width + 1) + (x + 0);
1361                         e[1] = (y + 0) * (width + 1) + (x + 0);
1362                         e[2] = (y + 1) * (width + 1) + (x + 1);
1363                         e[3] = (y + 0) * (width + 1) + (x + 0);
1364                         e[4] = (y + 0) * (width + 1) + (x + 1);
1365                         e[5] = (y + 1) * (width + 1) + (x + 1);
1366                         e += 6;
1367                 }
1368         }
1369         Mod_BuildTriangleNeighbors(neighbor3i, element3i, width*height*2);
1370         for (y = 0, iy = y1;y < height + 1;y++, iy++)
1371                 for (x = 0, ix = x1;x < width + 1;x++, ix++, vertex3f += 3, texcoord2f += 2, svector3f += 3, tvector3f += 3, normal3f += 3)
1372                         Mod_GetTerrainVertexFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, svector3f, tvector3f, normal3f, pixelstepmatrix, pixeltexturestepmatrix);
1373 }
1374
1375 #if 0
1376 void Mod_Terrain_SurfaceRecurseChunk(dp_model_t *model, int stepsize, int x, int y)
1377 {
1378         float mins[3];
1379         float maxs[3];
1380         float chunkwidth = min(stepsize, model->terrain.width - 1 - x);
1381         float chunkheight = min(stepsize, model->terrain.height - 1 - y);
1382         float viewvector[3];
1383         unsigned int firstvertex;
1384         unsigned int *e;
1385         float *v;
1386         if (chunkwidth < 2 || chunkheight < 2)
1387                 return;
1388         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]);
1389         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]);
1390         viewvector[0] = bound(mins[0], localvieworigin, maxs[0]) - model->terrain.vieworigin[0];
1391         viewvector[1] = bound(mins[1], localvieworigin, maxs[1]) - model->terrain.vieworigin[1];
1392         viewvector[2] = bound(mins[2], localvieworigin, maxs[2]) - model->terrain.vieworigin[2];
1393         if (stepsize > 1 && VectorLength(viewvector) < stepsize*model->terrain.scale[0]*r_terrain_lodscale.value)
1394         {
1395                 // too close for this stepsize, emit as 4 chunks instead
1396                 stepsize /= 2;
1397                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y);
1398                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y);
1399                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y+stepsize);
1400                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y+stepsize);
1401                 return;
1402         }
1403         // emit the geometry at stepsize into our vertex buffer / index buffer
1404         // we add two columns and two rows for skirt
1405         outwidth = chunkwidth+2;
1406         outheight = chunkheight+2;
1407         outwidth2 = outwidth-1;
1408         outheight2 = outheight-1;
1409         outwidth3 = outwidth+1;
1410         outheight3 = outheight+1;
1411         firstvertex = numvertices;
1412         e = model->terrain.element3i + numtriangles;
1413         numtriangles += chunkwidth*chunkheight*2+chunkwidth*2*2+chunkheight*2*2;
1414         v = model->terrain.vertex3f + numvertices;
1415         numvertices += (chunkwidth+1)*(chunkheight+1)+(chunkwidth+1)*2+(chunkheight+1)*2;
1416         // emit the triangles (note: the skirt is treated as two extra rows and two extra columns)
1417         for (ty = 0;ty < outheight;ty++)
1418         {
1419                 for (tx = 0;tx < outwidth;tx++)
1420                 {
1421                         *e++ = firstvertex + (ty  )*outwidth3+(tx  );
1422                         *e++ = firstvertex + (ty  )*outwidth3+(tx+1);
1423                         *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1424                         *e++ = firstvertex + (ty  )*outwidth3+(tx  );
1425                         *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1426                         *e++ = firstvertex + (ty+1)*outwidth3+(tx  );
1427                 }
1428         }
1429         // TODO: emit surface vertices (x+tx*stepsize, y+ty*stepsize)
1430         for (ty = 0;ty <= outheight;ty++)
1431         {
1432                 skirtrow = ty == 0 || ty == outheight;
1433                 ry = y+bound(1, ty, outheight)*stepsize;
1434                 for (tx = 0;tx <= outwidth;tx++)
1435                 {
1436                         skirt = skirtrow || tx == 0 || tx == outwidth;
1437                         rx = x+bound(1, tx, outwidth)*stepsize;
1438                         v[0] = rx*scale[0];
1439                         v[1] = ry*scale[1];
1440                         v[2] = heightmap[ry*terrainwidth+rx]*scale[2];
1441                         v += 3;
1442                 }
1443         }
1444         // TODO: emit skirt vertices
1445 }
1446
1447 void Mod_Terrain_UpdateSurfacesForViewOrigin(dp_model_t *model)
1448 {
1449         for (y = 0;y < model->terrain.size[1];y += model->terrain.
1450         Mod_Terrain_SurfaceRecurseChunk(model, model->terrain.maxstepsize, x, y);
1451         Mod_Terrain_BuildChunk(model, 
1452 }
1453 #endif
1454
1455 q3wavefunc_t Mod_LoadQ3Shaders_EnumerateWaveFunc(const char *s)
1456 {
1457         if (!strcasecmp(s, "sin"))             return Q3WAVEFUNC_SIN;
1458         if (!strcasecmp(s, "square"))          return Q3WAVEFUNC_SQUARE;
1459         if (!strcasecmp(s, "triangle"))        return Q3WAVEFUNC_TRIANGLE;
1460         if (!strcasecmp(s, "sawtooth"))        return Q3WAVEFUNC_SAWTOOTH;
1461         if (!strcasecmp(s, "inversesawtooth")) return Q3WAVEFUNC_INVERSESAWTOOTH;
1462         if (!strcasecmp(s, "noise"))           return Q3WAVEFUNC_NOISE;
1463         Con_DPrintf("Mod_LoadQ3Shaders: unknown wavefunc %s\n", s);
1464         return Q3WAVEFUNC_NONE;
1465 }
1466
1467 void Mod_FreeQ3Shaders(void)
1468 {
1469         Mem_FreePool(&q3shaders_mem);
1470 }
1471
1472 static void Q3Shader_AddToHash (q3shaderinfo_t* shader)
1473 {
1474         unsigned short hash = CRC_Block_CaseInsensitive ((const unsigned char *)shader->name, strlen (shader->name));
1475         q3shader_hash_entry_t* entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
1476         q3shader_hash_entry_t* lastEntry = NULL;
1477         while (entry != NULL)
1478         {
1479                 if (strcasecmp (entry->shader.name, shader->name) == 0)
1480                 {
1481                         unsigned char *start, *end, *start2;
1482                         start = (unsigned char *) (&shader->Q3SHADERINFO_COMPARE_START);
1483                         end = ((unsigned char *) (&shader->Q3SHADERINFO_COMPARE_END)) + sizeof(shader->Q3SHADERINFO_COMPARE_END);
1484                         start2 = (unsigned char *) (&entry->shader.Q3SHADERINFO_COMPARE_START);
1485                         if(memcmp(start, start2, end - start))
1486                                 Con_DPrintf("Shader '%s' already defined, ignoring mismatching redeclaration\n", shader->name);
1487                         else
1488                                 Con_DPrintf("Shader '%s' already defined\n", shader->name);
1489                         return;
1490                 }
1491                 lastEntry = entry;
1492                 entry = entry->chain;
1493         }
1494         if (entry == NULL)
1495         {
1496                 if (lastEntry->shader.name[0] != 0)
1497                 {
1498                         /* Add to chain */
1499                         q3shader_hash_entry_t* newEntry = (q3shader_hash_entry_t*)
1500                           Mem_ExpandableArray_AllocRecord (&q3shader_data->hash_entries);
1501
1502                         while (lastEntry->chain != NULL) lastEntry = lastEntry->chain;
1503                         lastEntry->chain = newEntry;
1504                         newEntry->chain = NULL;
1505                         lastEntry = newEntry;
1506                 }
1507                 /* else: head of chain, in hash entry array */
1508                 entry = lastEntry;
1509         }
1510         memcpy (&entry->shader, shader, sizeof (q3shaderinfo_t));
1511 }
1512
1513 extern cvar_t r_picmipworld;
1514 void Mod_LoadQ3Shaders(void)
1515 {
1516         int j;
1517         int fileindex;
1518         fssearch_t *search;
1519         char *f;
1520         const char *text;
1521         q3shaderinfo_t shader;
1522         q3shaderinfo_layer_t *layer;
1523         int numparameters;
1524         char parameter[TEXTURE_MAXFRAMES + 4][Q3PATHLENGTH];
1525
1526         Mod_FreeQ3Shaders();
1527
1528         q3shaders_mem = Mem_AllocPool("q3shaders", 0, NULL);
1529         q3shader_data = (q3shader_data_t*)Mem_Alloc (q3shaders_mem,
1530                 sizeof (q3shader_data_t));
1531         Mem_ExpandableArray_NewArray (&q3shader_data->hash_entries,
1532                 q3shaders_mem, sizeof (q3shader_hash_entry_t), 256);
1533         Mem_ExpandableArray_NewArray (&q3shader_data->char_ptrs,
1534                 q3shaders_mem, sizeof (char**), 256);
1535
1536         search = FS_Search("scripts/*.shader", true, false);
1537         if (!search)
1538                 return;
1539         for (fileindex = 0;fileindex < search->numfilenames;fileindex++)
1540         {
1541                 text = f = (char *)FS_LoadFile(search->filenames[fileindex], tempmempool, false, NULL);
1542                 if (!f)
1543                         continue;
1544                 while (COM_ParseToken_QuakeC(&text, false))
1545                 {
1546                         memset (&shader, 0, sizeof(shader));
1547                         shader.reflectmin = 0;
1548                         shader.reflectmax = 1;
1549                         shader.refractfactor = 1;
1550                         Vector4Set(shader.refractcolor4f, 1, 1, 1, 1);
1551                         shader.reflectfactor = 1;
1552                         Vector4Set(shader.reflectcolor4f, 1, 1, 1, 1);
1553                         shader.r_water_wateralpha = 1;
1554                         shader.specularscalemod = 1;
1555                         shader.specularpowermod = 1;
1556
1557                         strlcpy(shader.name, com_token, sizeof(shader.name));
1558                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1559                         {
1560                                 Con_DPrintf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[fileindex], com_token);
1561                                 break;
1562                         }
1563                         while (COM_ParseToken_QuakeC(&text, false))
1564                         {
1565                                 if (!strcasecmp(com_token, "}"))
1566                                         break;
1567                                 if (!strcasecmp(com_token, "{"))
1568                                 {
1569                                         static q3shaderinfo_layer_t dummy;
1570                                         if (shader.numlayers < Q3SHADER_MAXLAYERS)
1571                                         {
1572                                                 layer = shader.layers + shader.numlayers++;
1573                                         }
1574                                         else
1575                                         {
1576                                                 // parse and process it anyway, just don't store it (so a map $lightmap or such stuff still is found)
1577                                                 memset(&dummy, 0, sizeof(dummy));
1578                                                 layer = &dummy;
1579                                         }
1580                                         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1581                                         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1582                                         layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1583                                         layer->blendfunc[0] = GL_ONE;
1584                                         layer->blendfunc[1] = GL_ZERO;
1585                                         while (COM_ParseToken_QuakeC(&text, false))
1586                                         {
1587                                                 if (!strcasecmp(com_token, "}"))
1588                                                         break;
1589                                                 if (!strcasecmp(com_token, "\n"))
1590                                                         continue;
1591                                                 numparameters = 0;
1592                                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1593                                                 {
1594                                                         if (j < TEXTURE_MAXFRAMES + 4)
1595                                                         {
1596                                                                 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1597                                                                 numparameters = j + 1;
1598                                                         }
1599                                                         if (!COM_ParseToken_QuakeC(&text, true))
1600                                                                 break;
1601                                                 }
1602                                                 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1603                                                 //      parameter[j][0] = 0;
1604                                                 if (developer_insane.integer)
1605                                                 {
1606                                                         Con_DPrintf("%s %i: ", shader.name, shader.numlayers - 1);
1607                                                         for (j = 0;j < numparameters;j++)
1608                                                                 Con_DPrintf(" %s", parameter[j]);
1609                                                         Con_DPrint("\n");
1610                                                 }
1611                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "blendfunc"))
1612                                                 {
1613                                                         if (numparameters == 2)
1614                                                         {
1615                                                                 if (!strcasecmp(parameter[1], "add"))
1616                                                                 {
1617                                                                         layer->blendfunc[0] = GL_ONE;
1618                                                                         layer->blendfunc[1] = GL_ONE;
1619                                                                 }
1620                                                                 else if (!strcasecmp(parameter[1], "filter"))
1621                                                                 {
1622                                                                         layer->blendfunc[0] = GL_DST_COLOR;
1623                                                                         layer->blendfunc[1] = GL_ZERO;
1624                                                                 }
1625                                                                 else if (!strcasecmp(parameter[1], "blend"))
1626                                                                 {
1627                                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1628                                                                         layer->blendfunc[1] = GL_ONE_MINUS_SRC_ALPHA;
1629                                                                 }
1630                                                         }
1631                                                         else if (numparameters == 3)
1632                                                         {
1633                                                                 int k;
1634                                                                 for (k = 0;k < 2;k++)
1635                                                                 {
1636                                                                         if (!strcasecmp(parameter[k+1], "GL_ONE"))
1637                                                                                 layer->blendfunc[k] = GL_ONE;
1638                                                                         else if (!strcasecmp(parameter[k+1], "GL_ZERO"))
1639                                                                                 layer->blendfunc[k] = GL_ZERO;
1640                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_COLOR"))
1641                                                                                 layer->blendfunc[k] = GL_SRC_COLOR;
1642                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_ALPHA"))
1643                                                                                 layer->blendfunc[k] = GL_SRC_ALPHA;
1644                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_COLOR"))
1645                                                                                 layer->blendfunc[k] = GL_DST_COLOR;
1646                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_ALPHA"))
1647                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1648                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_COLOR"))
1649                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_COLOR;
1650                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_ALPHA"))
1651                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_ALPHA;
1652                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_COLOR"))
1653                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_COLOR;
1654                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_ALPHA"))
1655                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1656                                                                         else
1657                                                                                 layer->blendfunc[k] = GL_ONE; // default in case of parsing error
1658                                                                 }
1659                                                         }
1660                                                 }
1661                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
1662                                                         layer->alphatest = true;
1663                                                 if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
1664                                                 {
1665                                                         if (!strcasecmp(parameter[0], "clampmap"))
1666                                                                 layer->clampmap = true;
1667                                                         layer->numframes = 1;
1668                                                         layer->framerate = 1;
1669                                                         layer->texturename = (char**)Mem_ExpandableArray_AllocRecord (
1670                                                                 &q3shader_data->char_ptrs);
1671                                                         layer->texturename[0] = Mem_strdup (q3shaders_mem, parameter[1]);
1672                                                         if (!strcasecmp(parameter[1], "$lightmap"))
1673                                                                 shader.lighting = true;
1674                                                 }
1675                                                 else if (numparameters >= 3 && (!strcasecmp(parameter[0], "animmap") || !strcasecmp(parameter[0], "animclampmap")))
1676                                                 {
1677                                                         int i;
1678                                                         layer->numframes = min(numparameters - 2, TEXTURE_MAXFRAMES);
1679                                                         layer->framerate = atof(parameter[1]);
1680                                                         layer->texturename = (char **) Mem_Alloc (q3shaders_mem, sizeof (char*) * layer->numframes);
1681                                                         for (i = 0;i < layer->numframes;i++)
1682                                                                 layer->texturename[i] = Mem_strdup (q3shaders_mem, parameter[i + 2]);
1683                                                 }
1684                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "rgbgen"))
1685                                                 {
1686                                                         int i;
1687                                                         for (i = 0;i < numparameters - 2 && i < Q3RGBGEN_MAXPARMS;i++)
1688                                                                 layer->rgbgen.parms[i] = atof(parameter[i+2]);
1689                                                              if (!strcasecmp(parameter[1], "identity"))         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1690                                                         else if (!strcasecmp(parameter[1], "const"))            layer->rgbgen.rgbgen = Q3RGBGEN_CONST;
1691                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->rgbgen.rgbgen = Q3RGBGEN_ENTITY;
1692                                                         else if (!strcasecmp(parameter[1], "exactvertex"))      layer->rgbgen.rgbgen = Q3RGBGEN_EXACTVERTEX;
1693                                                         else if (!strcasecmp(parameter[1], "identitylighting")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITYLIGHTING;
1694                                                         else if (!strcasecmp(parameter[1], "lightingdiffuse"))  layer->rgbgen.rgbgen = Q3RGBGEN_LIGHTINGDIFFUSE;
1695                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSENTITY;
1696                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSVERTEX;
1697                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->rgbgen.rgbgen = Q3RGBGEN_VERTEX;
1698                                                         else if (!strcasecmp(parameter[1], "wave"))
1699                                                         {
1700                                                                 layer->rgbgen.rgbgen = Q3RGBGEN_WAVE;
1701                                                                 layer->rgbgen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1702                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1703                                                                         layer->rgbgen.waveparms[i] = atof(parameter[i+3]);
1704                                                         }
1705                                                         else Con_DPrintf("%s parsing warning: unknown rgbgen %s\n", search->filenames[fileindex], parameter[1]);
1706                                                 }
1707                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphagen"))
1708                                                 {
1709                                                         int i;
1710                                                         for (i = 0;i < numparameters - 2 && i < Q3ALPHAGEN_MAXPARMS;i++)
1711                                                                 layer->alphagen.parms[i] = atof(parameter[i+2]);
1712                                                              if (!strcasecmp(parameter[1], "identity"))         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1713                                                         else if (!strcasecmp(parameter[1], "const"))            layer->alphagen.alphagen = Q3ALPHAGEN_CONST;
1714                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->alphagen.alphagen = Q3ALPHAGEN_ENTITY;
1715                                                         else if (!strcasecmp(parameter[1], "lightingspecular")) layer->alphagen.alphagen = Q3ALPHAGEN_LIGHTINGSPECULAR;
1716                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSENTITY;
1717                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSVERTEX;
1718                                                         else if (!strcasecmp(parameter[1], "portal"))           layer->alphagen.alphagen = Q3ALPHAGEN_PORTAL;
1719                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->alphagen.alphagen = Q3ALPHAGEN_VERTEX;
1720                                                         else if (!strcasecmp(parameter[1], "wave"))
1721                                                         {
1722                                                                 layer->alphagen.alphagen = Q3ALPHAGEN_WAVE;
1723                                                                 layer->alphagen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1724                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1725                                                                         layer->alphagen.waveparms[i] = atof(parameter[i+3]);
1726                                                         }
1727                                                         else Con_DPrintf("%s parsing warning: unknown alphagen %s\n", search->filenames[fileindex], parameter[1]);
1728                                                 }
1729                                                 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "texgen") || !strcasecmp(parameter[0], "tcgen")))
1730                                                 {
1731                                                         int i;
1732                                                         // observed values: tcgen environment
1733                                                         // no other values have been observed in real shaders
1734                                                         for (i = 0;i < numparameters - 2 && i < Q3TCGEN_MAXPARMS;i++)
1735                                                                 layer->tcgen.parms[i] = atof(parameter[i+2]);
1736                                                              if (!strcasecmp(parameter[1], "base"))        layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1737                                                         else if (!strcasecmp(parameter[1], "texture"))     layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1738                                                         else if (!strcasecmp(parameter[1], "environment")) layer->tcgen.tcgen = Q3TCGEN_ENVIRONMENT;
1739                                                         else if (!strcasecmp(parameter[1], "lightmap"))    layer->tcgen.tcgen = Q3TCGEN_LIGHTMAP;
1740                                                         else if (!strcasecmp(parameter[1], "vector"))      layer->tcgen.tcgen = Q3TCGEN_VECTOR;
1741                                                         else Con_DPrintf("%s parsing warning: unknown tcgen mode %s\n", search->filenames[fileindex], parameter[1]);
1742                                                 }
1743                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "tcmod"))
1744                                                 {
1745                                                         int i, tcmodindex;
1746                                                         // observed values:
1747                                                         // tcmod rotate #
1748                                                         // tcmod scale # #
1749                                                         // tcmod scroll # #
1750                                                         // tcmod stretch sin # # # #
1751                                                         // tcmod stretch triangle # # # #
1752                                                         // tcmod transform # # # # # #
1753                                                         // tcmod turb # # # #
1754                                                         // tcmod turb sin # # # #  (this is bogus)
1755                                                         // no other values have been observed in real shaders
1756                                                         for (tcmodindex = 0;tcmodindex < Q3MAXTCMODS;tcmodindex++)
1757                                                                 if (!layer->tcmods[tcmodindex].tcmod)
1758                                                                         break;
1759                                                         if (tcmodindex < Q3MAXTCMODS)
1760                                                         {
1761                                                                 for (i = 0;i < numparameters - 2 && i < Q3TCMOD_MAXPARMS;i++)
1762                                                                         layer->tcmods[tcmodindex].parms[i] = atof(parameter[i+2]);
1763                                                                          if (!strcasecmp(parameter[1], "entitytranslate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ENTITYTRANSLATE;
1764                                                                 else if (!strcasecmp(parameter[1], "rotate"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ROTATE;
1765                                                                 else if (!strcasecmp(parameter[1], "scale"))           layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCALE;
1766                                                                 else if (!strcasecmp(parameter[1], "scroll"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCROLL;
1767                                                                 else if (!strcasecmp(parameter[1], "page"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_PAGE;
1768                                                                 else if (!strcasecmp(parameter[1], "stretch"))
1769                                                                 {
1770                                                                         layer->tcmods[tcmodindex].tcmod = Q3TCMOD_STRETCH;
1771                                                                         layer->tcmods[tcmodindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1772                                                                         for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1773                                                                                 layer->tcmods[tcmodindex].waveparms[i] = atof(parameter[i+3]);
1774                                                                 }
1775                                                                 else if (!strcasecmp(parameter[1], "transform"))       layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TRANSFORM;
1776                                                                 else if (!strcasecmp(parameter[1], "turb"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TURBULENT;
1777                                                                 else Con_DPrintf("%s parsing warning: unknown tcmod mode %s\n", search->filenames[fileindex], parameter[1]);
1778                                                         }
1779                                                         else
1780                                                                 Con_DPrintf("%s parsing warning: too many tcmods on one layer\n", search->filenames[fileindex]);
1781                                                 }
1782                                                 // break out a level if it was a closing brace (not using the character here to not confuse vim)
1783                                                 if (!strcasecmp(com_token, "}"))
1784                                                         break;
1785                                         }
1786                                         if (layer->rgbgen.rgbgen == Q3RGBGEN_LIGHTINGDIFFUSE || layer->rgbgen.rgbgen == Q3RGBGEN_VERTEX)
1787                                                 shader.lighting = true;
1788                                         if (layer->alphagen.alphagen == Q3ALPHAGEN_VERTEX)
1789                                         {
1790                                                 if (layer == shader.layers + 0)
1791                                                 {
1792                                                         // vertex controlled transparency
1793                                                         shader.vertexalpha = true;
1794                                                 }
1795                                                 else
1796                                                 {
1797                                                         // multilayer terrain shader or similar
1798                                                         shader.textureblendalpha = true;
1799                                                 }
1800                                         }
1801                                         layer->texflags = TEXF_ALPHA;
1802                                         if (!(shader.surfaceparms & Q3SURFACEPARM_NOMIPMAPS))
1803                                                 layer->texflags |= TEXF_MIPMAP;
1804                                         if (!(shader.textureflags & Q3TEXTUREFLAG_NOPICMIP))
1805                                                 layer->texflags |= TEXF_PICMIP | TEXF_COMPRESS;
1806                                         if (layer->clampmap)
1807                                                 layer->texflags |= TEXF_CLAMP;
1808                                         continue;
1809                                 }
1810                                 numparameters = 0;
1811                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1812                                 {
1813                                         if (j < TEXTURE_MAXFRAMES + 4)
1814                                         {
1815                                                 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1816                                                 numparameters = j + 1;
1817                                         }
1818                                         if (!COM_ParseToken_QuakeC(&text, true))
1819                                                 break;
1820                                 }
1821                                 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1822                                 //      parameter[j][0] = 0;
1823                                 if (fileindex == 0 && !strcasecmp(com_token, "}"))
1824                                         break;
1825                                 if (developer_insane.integer)
1826                                 {
1827                                         Con_DPrintf("%s: ", shader.name);
1828                                         for (j = 0;j < numparameters;j++)
1829                                                 Con_DPrintf(" %s", parameter[j]);
1830                                         Con_DPrint("\n");
1831                                 }
1832                                 if (numparameters < 1)
1833                                         continue;
1834                                 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
1835                                 {
1836                                         if (!strcasecmp(parameter[1], "alphashadow"))
1837                                                 shader.surfaceparms |= Q3SURFACEPARM_ALPHASHADOW;
1838                                         else if (!strcasecmp(parameter[1], "areaportal"))
1839                                                 shader.surfaceparms |= Q3SURFACEPARM_AREAPORTAL;
1840                                         else if (!strcasecmp(parameter[1], "botclip"))
1841                                                 shader.surfaceparms |= Q3SURFACEPARM_BOTCLIP;
1842                                         else if (!strcasecmp(parameter[1], "clusterportal"))
1843                                                 shader.surfaceparms |= Q3SURFACEPARM_CLUSTERPORTAL;
1844                                         else if (!strcasecmp(parameter[1], "detail"))
1845                                                 shader.surfaceparms |= Q3SURFACEPARM_DETAIL;
1846                                         else if (!strcasecmp(parameter[1], "donotenter"))
1847                                                 shader.surfaceparms |= Q3SURFACEPARM_DONOTENTER;
1848                                         else if (!strcasecmp(parameter[1], "dust"))
1849                                                 shader.surfaceparms |= Q3SURFACEPARM_DUST;
1850                                         else if (!strcasecmp(parameter[1], "hint"))
1851                                                 shader.surfaceparms |= Q3SURFACEPARM_HINT;
1852                                         else if (!strcasecmp(parameter[1], "fog"))
1853                                                 shader.surfaceparms |= Q3SURFACEPARM_FOG;
1854                                         else if (!strcasecmp(parameter[1], "lava"))
1855                                                 shader.surfaceparms |= Q3SURFACEPARM_LAVA;
1856                                         else if (!strcasecmp(parameter[1], "lightfilter"))
1857                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTFILTER;
1858                                         else if (!strcasecmp(parameter[1], "lightgrid"))
1859                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTGRID;
1860                                         else if (!strcasecmp(parameter[1], "metalsteps"))
1861                                                 shader.surfaceparms |= Q3SURFACEPARM_METALSTEPS;
1862                                         else if (!strcasecmp(parameter[1], "nodamage"))
1863                                                 shader.surfaceparms |= Q3SURFACEPARM_NODAMAGE;
1864                                         else if (!strcasecmp(parameter[1], "nodlight"))
1865                                                 shader.surfaceparms |= Q3SURFACEPARM_NODLIGHT;
1866                                         else if (!strcasecmp(parameter[1], "nodraw"))
1867                                                 shader.surfaceparms |= Q3SURFACEPARM_NODRAW;
1868                                         else if (!strcasecmp(parameter[1], "nodrop"))
1869                                                 shader.surfaceparms |= Q3SURFACEPARM_NODROP;
1870                                         else if (!strcasecmp(parameter[1], "noimpact"))
1871                                                 shader.surfaceparms |= Q3SURFACEPARM_NOIMPACT;
1872                                         else if (!strcasecmp(parameter[1], "nolightmap"))
1873                                                 shader.surfaceparms |= Q3SURFACEPARM_NOLIGHTMAP;
1874                                         else if (!strcasecmp(parameter[1], "nomarks"))
1875                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMARKS;
1876                                         else if (!strcasecmp(parameter[1], "nomipmaps"))
1877                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1878                                         else if (!strcasecmp(parameter[1], "nonsolid"))
1879                                                 shader.surfaceparms |= Q3SURFACEPARM_NONSOLID;
1880                                         else if (!strcasecmp(parameter[1], "origin"))
1881                                                 shader.surfaceparms |= Q3SURFACEPARM_ORIGIN;
1882                                         else if (!strcasecmp(parameter[1], "playerclip"))
1883                                                 shader.surfaceparms |= Q3SURFACEPARM_PLAYERCLIP;
1884                                         else if (!strcasecmp(parameter[1], "sky"))
1885                                                 shader.surfaceparms |= Q3SURFACEPARM_SKY;
1886                                         else if (!strcasecmp(parameter[1], "slick"))
1887                                                 shader.surfaceparms |= Q3SURFACEPARM_SLICK;
1888                                         else if (!strcasecmp(parameter[1], "slime"))
1889                                                 shader.surfaceparms |= Q3SURFACEPARM_SLIME;
1890                                         else if (!strcasecmp(parameter[1], "structural"))
1891                                                 shader.surfaceparms |= Q3SURFACEPARM_STRUCTURAL;
1892                                         else if (!strcasecmp(parameter[1], "trans"))
1893                                                 shader.surfaceparms |= Q3SURFACEPARM_TRANS;
1894                                         else if (!strcasecmp(parameter[1], "water"))
1895                                                 shader.surfaceparms |= Q3SURFACEPARM_WATER;
1896                                         else if (!strcasecmp(parameter[1], "pointlight"))
1897                                                 shader.surfaceparms |= Q3SURFACEPARM_POINTLIGHT;
1898                                         else if (!strcasecmp(parameter[1], "antiportal"))
1899                                                 shader.surfaceparms |= Q3SURFACEPARM_ANTIPORTAL;
1900                                         else
1901                                                 Con_DPrintf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[fileindex], parameter[1]);
1902                                 }
1903                                 else if (!strcasecmp(parameter[0], "dpshadow"))
1904                                         shader.dpshadow = true;
1905                                 else if (!strcasecmp(parameter[0], "dpnoshadow"))
1906                                         shader.dpnoshadow = true;
1907                                 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
1908                                 {
1909                                         // some q3 skies don't have the sky parm set
1910                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
1911                                         strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
1912                                 }
1913                                 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
1914                                 {
1915                                         // some q3 skies don't have the sky parm set
1916                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
1917                                         if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
1918                                                 strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
1919                                 }
1920                                 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
1921                                 {
1922                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
1923                                                 shader.textureflags |= Q3TEXTUREFLAG_TWOSIDED;
1924                                 }
1925                                 else if (!strcasecmp(parameter[0], "nomipmaps"))
1926                                         shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1927                                 else if (!strcasecmp(parameter[0], "nopicmip"))
1928                                         shader.textureflags |= Q3TEXTUREFLAG_NOPICMIP;
1929                                 else if (!strcasecmp(parameter[0], "polygonoffset"))
1930                                         shader.textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
1931                                 else if (!strcasecmp(parameter[0], "dp_refract") && numparameters >= 5)
1932                                 {
1933                                         shader.textureflags |= Q3TEXTUREFLAG_REFRACTION;
1934                                         shader.refractfactor = atof(parameter[1]);
1935                                         Vector4Set(shader.refractcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), 1);
1936                                 }
1937                                 else if (!strcasecmp(parameter[0], "dp_reflect") && numparameters >= 6)
1938                                 {
1939                                         shader.textureflags |= Q3TEXTUREFLAG_REFLECTION;
1940                                         shader.reflectfactor = atof(parameter[1]);
1941                                         Vector4Set(shader.reflectcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), atof(parameter[5]));
1942                                 }
1943                                 else if (!strcasecmp(parameter[0], "dp_water") && numparameters >= 12)
1944                                 {
1945                                         shader.textureflags |= Q3TEXTUREFLAG_WATERSHADER;
1946                                         shader.reflectmin = atof(parameter[1]);
1947                                         shader.reflectmax = atof(parameter[2]);
1948                                         shader.refractfactor = atof(parameter[3]);
1949                                         shader.reflectfactor = atof(parameter[4]);
1950                                         Vector4Set(shader.refractcolor4f, atof(parameter[5]), atof(parameter[6]), atof(parameter[7]), 1);
1951                                         Vector4Set(shader.reflectcolor4f, atof(parameter[8]), atof(parameter[9]), atof(parameter[10]), 1);
1952                                         shader.r_water_wateralpha = atof(parameter[11]);
1953                                 }
1954                                 else if (!strcasecmp(parameter[0], "dp_glossintensitymod") && numparameters >= 2)
1955                                 {
1956                                         shader.specularscalemod = atof(parameter[1]);
1957                                 }
1958                                 else if (!strcasecmp(parameter[0], "dp_glossexponentmod") && numparameters >= 2)
1959                                 {
1960                                         shader.specularpowermod = atof(parameter[1]);
1961                                 }
1962                                 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
1963                                 {
1964                                         int i, deformindex;
1965                                         for (deformindex = 0;deformindex < Q3MAXDEFORMS;deformindex++)
1966                                                 if (!shader.deforms[deformindex].deform)
1967                                                         break;
1968                                         if (deformindex < Q3MAXDEFORMS)
1969                                         {
1970                                                 for (i = 0;i < numparameters - 2 && i < Q3DEFORM_MAXPARMS;i++)
1971                                                         shader.deforms[deformindex].parms[i] = atof(parameter[i+2]);
1972                                                      if (!strcasecmp(parameter[1], "projectionshadow")) shader.deforms[deformindex].deform = Q3DEFORM_PROJECTIONSHADOW;
1973                                                 else if (!strcasecmp(parameter[1], "autosprite"      )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE;
1974                                                 else if (!strcasecmp(parameter[1], "autosprite2"     )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE2;
1975                                                 else if (!strcasecmp(parameter[1], "text0"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT0;
1976                                                 else if (!strcasecmp(parameter[1], "text1"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT1;
1977                                                 else if (!strcasecmp(parameter[1], "text2"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT2;
1978                                                 else if (!strcasecmp(parameter[1], "text3"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT3;
1979                                                 else if (!strcasecmp(parameter[1], "text4"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT4;
1980                                                 else if (!strcasecmp(parameter[1], "text5"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT5;
1981                                                 else if (!strcasecmp(parameter[1], "text6"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT6;
1982                                                 else if (!strcasecmp(parameter[1], "text7"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT7;
1983                                                 else if (!strcasecmp(parameter[1], "bulge"           )) shader.deforms[deformindex].deform = Q3DEFORM_BULGE;
1984                                                 else if (!strcasecmp(parameter[1], "normal"          )) shader.deforms[deformindex].deform = Q3DEFORM_NORMAL;
1985                                                 else if (!strcasecmp(parameter[1], "wave"            ))
1986                                                 {
1987                                                         shader.deforms[deformindex].deform = Q3DEFORM_WAVE;
1988                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[3]);
1989                                                         for (i = 0;i < numparameters - 4 && i < Q3WAVEPARMS;i++)
1990                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+4]);
1991                                                 }
1992                                                 else if (!strcasecmp(parameter[1], "move"            ))
1993                                                 {
1994                                                         shader.deforms[deformindex].deform = Q3DEFORM_MOVE;
1995                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[5]);
1996                                                         for (i = 0;i < numparameters - 6 && i < Q3WAVEPARMS;i++)
1997                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+6]);
1998                                                 }
1999                                         }
2000                                 }
2001                         }
2002                         // pick the primary layer to render with
2003                         if (shader.numlayers)
2004                         {
2005                                 shader.backgroundlayer = -1;
2006                                 shader.primarylayer = 0;
2007                                 // if lightmap comes first this is definitely an ordinary texture
2008                                 // if the first two layers have the correct blendfuncs and use vertex alpha, it is a blended terrain shader
2009                                 if ((shader.layers[shader.primarylayer].texturename != NULL)
2010                                   && !strcasecmp(shader.layers[shader.primarylayer].texturename[0], "$lightmap"))
2011                                 {
2012                                         shader.backgroundlayer = -1;
2013                                         shader.primarylayer = 1;
2014                                 }
2015                                 else if (shader.numlayers >= 2
2016                                 &&   shader.layers[1].alphagen.alphagen == Q3ALPHAGEN_VERTEX
2017                                 &&  (shader.layers[0].blendfunc[0] == GL_ONE       && shader.layers[0].blendfunc[1] == GL_ZERO                && !shader.layers[0].alphatest)
2018                                 && ((shader.layers[1].blendfunc[0] == GL_SRC_ALPHA && shader.layers[1].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2019                                 ||  (shader.layers[1].blendfunc[0] == GL_ONE       && shader.layers[1].blendfunc[1] == GL_ZERO                &&  shader.layers[1].alphatest)))
2020                                 {
2021                                         // terrain blending or other effects
2022                                         shader.backgroundlayer = 0;
2023                                         shader.primarylayer = 1;
2024                                 }
2025                         }
2026                         // fix up multiple reflection types
2027                         if(shader.textureflags & Q3TEXTUREFLAG_WATERSHADER)
2028                                 shader.textureflags &= ~(Q3TEXTUREFLAG_REFRACTION | Q3TEXTUREFLAG_REFLECTION);
2029
2030                         Q3Shader_AddToHash (&shader);
2031                 }
2032                 Mem_Free(f);
2033         }
2034         FS_FreeSearch(search);
2035 }
2036
2037 q3shaderinfo_t *Mod_LookupQ3Shader(const char *name)
2038 {
2039         unsigned short hash;
2040         q3shader_hash_entry_t* entry;
2041         if (!q3shaders_mem)
2042                 Mod_LoadQ3Shaders();
2043         hash = CRC_Block_CaseInsensitive ((const unsigned char *)name, strlen (name));
2044         entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
2045         while (entry != NULL)
2046         {
2047                 if (strcasecmp (entry->shader.name, name) == 0)
2048                         return &entry->shader;
2049                 entry = entry->chain;
2050         }
2051         return NULL;
2052 }
2053
2054 qboolean Mod_LoadTextureFromQ3Shader(texture_t *texture, const char *name, qboolean warnmissing, qboolean fallback, int defaulttexflags)
2055 {
2056         int j;
2057         int texflagsmask;
2058         qboolean success = true;
2059         q3shaderinfo_t *shader;
2060         if (!name)
2061                 name = "";
2062         strlcpy(texture->name, name, sizeof(texture->name));
2063         shader = name[0] ? Mod_LookupQ3Shader(name) : NULL;
2064
2065         texflagsmask = ~0;
2066         if(!(defaulttexflags & TEXF_PICMIP))
2067                 texflagsmask &= ~TEXF_PICMIP;
2068         if(!(defaulttexflags & TEXF_COMPRESS))
2069                 texflagsmask &= ~TEXF_COMPRESS;
2070         texture->specularscalemod = 1; // unless later loaded from the shader
2071         texture->specularpowermod = 1; // unless later loaded from the shader
2072         // WHEN ADDING DEFAULTS HERE, REMEMBER TO SYNC TO SHADER LOADING ABOVE
2073         // HERE, AND Q1BSP LOADING
2074         // JUST GREP FOR "specularscalemod = 1".
2075
2076         if (shader)
2077         {
2078                 if (developer_loading.integer)
2079                         Con_Printf("%s: loaded shader for %s\n", loadmodel->name, name);
2080                 texture->surfaceparms = shader->surfaceparms;
2081
2082                 // allow disabling of picmip or compression by defaulttexflags
2083                 texture->textureflags = shader->textureflags & texflagsmask;
2084
2085                 if (shader->surfaceparms & Q3SURFACEPARM_SKY)
2086                 {
2087                         texture->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2088                         if (shader->skyboxname[0])
2089                         {
2090                                 // quake3 seems to append a _ to the skybox name, so this must do so as well
2091                                 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", shader->skyboxname);
2092                         }
2093                 }
2094                 else if ((texture->surfaceflags & Q3SURFACEFLAG_NODRAW) || shader->numlayers == 0)
2095                         texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2096                 else
2097                         texture->basematerialflags = MATERIALFLAG_WALL;
2098
2099                 if (shader->layers[0].alphatest)
2100                         texture->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
2101                 if (shader->textureflags & Q3TEXTUREFLAG_TWOSIDED)
2102                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
2103                 if (shader->textureflags & Q3TEXTUREFLAG_POLYGONOFFSET)
2104                         texture->biaspolygonoffset -= 2;
2105                 if (shader->textureflags & Q3TEXTUREFLAG_REFRACTION)
2106                         texture->basematerialflags |= MATERIALFLAG_REFRACTION;
2107                 if (shader->textureflags & Q3TEXTUREFLAG_REFLECTION)
2108                         texture->basematerialflags |= MATERIALFLAG_REFLECTION;
2109                 if (shader->textureflags & Q3TEXTUREFLAG_WATERSHADER)
2110                         texture->basematerialflags |= MATERIALFLAG_WATERSHADER;
2111                 texture->customblendfunc[0] = GL_ONE;
2112                 texture->customblendfunc[1] = GL_ZERO;
2113                 if (shader->numlayers > 0)
2114                 {
2115                         texture->customblendfunc[0] = shader->layers[0].blendfunc[0];
2116                         texture->customblendfunc[1] = shader->layers[0].blendfunc[1];
2117 /*
2118 Q3 shader blendfuncs actually used in the game (* = supported by DP)
2119 * additive               GL_ONE GL_ONE
2120 additive weird         GL_ONE GL_SRC_ALPHA
2121 additive weird 2       GL_ONE GL_ONE_MINUS_SRC_ALPHA
2122 * alpha                  GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
2123 alpha inverse          GL_ONE_MINUS_SRC_ALPHA GL_SRC_ALPHA
2124 brighten               GL_DST_COLOR GL_ONE
2125 brighten               GL_ONE GL_SRC_COLOR
2126 brighten weird         GL_DST_COLOR GL_ONE_MINUS_DST_ALPHA
2127 brighten weird 2       GL_DST_COLOR GL_SRC_ALPHA
2128 * modulate               GL_DST_COLOR GL_ZERO
2129 * modulate               GL_ZERO GL_SRC_COLOR
2130 modulate inverse       GL_ZERO GL_ONE_MINUS_SRC_COLOR
2131 modulate inverse alpha GL_ZERO GL_SRC_ALPHA
2132 modulate weird inverse GL_ONE_MINUS_DST_COLOR GL_ZERO
2133 * modulate x2            GL_DST_COLOR GL_SRC_COLOR
2134 * no blend               GL_ONE GL_ZERO
2135 nothing                GL_ZERO GL_ONE
2136 */
2137                         // if not opaque, figure out what blendfunc to use
2138                         if (shader->layers[0].blendfunc[0] != GL_ONE || shader->layers[0].blendfunc[1] != GL_ZERO)
2139                         {
2140                                 if (shader->layers[0].blendfunc[0] == GL_ONE && shader->layers[0].blendfunc[1] == GL_ONE)
2141                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2142                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE)
2143                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2144                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2145                                         texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2146                                 else
2147                                         texture->basematerialflags |= MATERIALFLAG_CUSTOMBLEND | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2148                         }
2149                 }
2150                 if (!shader->lighting)
2151                         texture->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
2152                 if (shader->primarylayer >= 0)
2153                 {
2154                         q3shaderinfo_layer_t* primarylayer = shader->layers + shader->primarylayer;
2155                         // copy over many primarylayer parameters
2156                         texture->rgbgen = primarylayer->rgbgen;
2157                         texture->alphagen = primarylayer->alphagen;
2158                         texture->tcgen = primarylayer->tcgen;
2159                         memcpy(texture->tcmods, primarylayer->tcmods, sizeof(texture->tcmods));
2160                         // load the textures
2161                         texture->numskinframes = primarylayer->numframes;
2162                         texture->skinframerate = primarylayer->framerate;
2163                         for (j = 0;j < primarylayer->numframes;j++)
2164                         {
2165                                 if(cls.state == ca_dedicated)
2166                                 {
2167                                         texture->skinframes[j] = NULL;
2168                                 }
2169                                 else if (!(texture->skinframes[j] = R_SkinFrame_LoadExternal(primarylayer->texturename[j], primarylayer->texflags & texflagsmask, false)))
2170                                 {
2171                                         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);
2172                                         texture->skinframes[j] = R_SkinFrame_LoadMissing();
2173                                 }
2174                         }
2175                 }
2176                 if (shader->backgroundlayer >= 0)
2177                 {
2178                         q3shaderinfo_layer_t* backgroundlayer = shader->layers + shader->backgroundlayer;
2179                         // copy over one secondarylayer parameter
2180                         memcpy(texture->backgroundtcmods, backgroundlayer->tcmods, sizeof(texture->backgroundtcmods));
2181                         // load the textures
2182                         texture->backgroundnumskinframes = backgroundlayer->numframes;
2183                         texture->backgroundskinframerate = backgroundlayer->framerate;
2184                         for (j = 0;j < backgroundlayer->numframes;j++)
2185                         {
2186                                 if(cls.state == ca_dedicated)
2187                                 {
2188                                         texture->skinframes[j] = NULL;
2189                                 }
2190                                 else if (!(texture->backgroundskinframes[j] = R_SkinFrame_LoadExternal(backgroundlayer->texturename[j], backgroundlayer->texflags & texflagsmask, false)))
2191                                 {
2192                                         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);
2193                                         texture->backgroundskinframes[j] = R_SkinFrame_LoadMissing();
2194                                 }
2195                         }
2196                 }
2197                 if (shader->dpshadow)
2198                         texture->basematerialflags &= ~MATERIALFLAG_NOSHADOW;
2199                 if (shader->dpnoshadow)
2200                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW;
2201                 memcpy(texture->deforms, shader->deforms, sizeof(texture->deforms));
2202                 texture->reflectmin = shader->reflectmin;
2203                 texture->reflectmax = shader->reflectmax;
2204                 texture->refractfactor = shader->refractfactor;
2205                 Vector4Copy(shader->refractcolor4f, texture->refractcolor4f);
2206                 texture->reflectfactor = shader->reflectfactor;
2207                 Vector4Copy(shader->reflectcolor4f, texture->reflectcolor4f);
2208                 texture->r_water_wateralpha = shader->r_water_wateralpha;
2209                 texture->specularscalemod = shader->specularscalemod;
2210                 texture->specularpowermod = shader->specularpowermod;
2211         }
2212         else if (!strcmp(texture->name, "noshader") || !texture->name[0])
2213         {
2214                 if (developer_extra.integer)
2215                         Con_DPrintf("^1%s:^7 using fallback noshader material for ^3\"%s\"\n", loadmodel->name, name);
2216                 texture->surfaceparms = 0;
2217         }
2218         else if (!strcmp(texture->name, "common/nodraw") || !strcmp(texture->name, "textures/common/nodraw"))
2219         {
2220                 if (developer_extra.integer)
2221                         Con_DPrintf("^1%s:^7 using fallback nodraw material for ^3\"%s\"\n", loadmodel->name, name);
2222                 texture->surfaceparms = 0;
2223                 texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2224         }
2225         else
2226         {
2227                 if (developer_extra.integer)
2228                         Con_DPrintf("^1%s:^7 No shader found for texture ^3\"%s\"\n", loadmodel->name, texture->name);
2229                 texture->surfaceparms = 0;
2230                 if (texture->surfaceflags & Q3SURFACEFLAG_NODRAW)
2231                         texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2232                 else if (texture->surfaceflags & Q3SURFACEFLAG_SKY)
2233                         texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2234                 else
2235                         texture->basematerialflags |= MATERIALFLAG_WALL;
2236                 texture->numskinframes = 1;
2237                 if(cls.state == ca_dedicated)
2238                 {
2239                         texture->skinframes[0] = NULL;
2240                 }
2241                 else
2242                 {
2243                         if (fallback)
2244                         {
2245                                 if ((texture->skinframes[0] = R_SkinFrame_LoadExternal(texture->name, defaulttexflags, false)))
2246                                 {
2247                                         if(texture->skinframes[0]->hasalpha)
2248                                                 texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2249                                 }
2250                                 else
2251                                         success = false;
2252                         }
2253                         else
2254                                 success = false;
2255                         if (!success && warnmissing)
2256                                 Con_Printf("^1%s:^7 could not load texture ^3\"%s\"\n", loadmodel->name, texture->name);
2257                 }
2258         }
2259         // init the animation variables
2260         texture->currentframe = texture;
2261         if (texture->numskinframes < 1)
2262                 texture->numskinframes = 1;
2263         if (!texture->skinframes[0])
2264                 texture->skinframes[0] = R_SkinFrame_LoadMissing();
2265         texture->currentskinframe = texture->skinframes[0];
2266         texture->backgroundcurrentskinframe = texture->backgroundskinframes[0];
2267         return success;
2268 }
2269
2270 skinfile_t *Mod_LoadSkinFiles(void)
2271 {
2272         int i, words, line, wordsoverflow;
2273         char *text;
2274         const char *data;
2275         skinfile_t *skinfile = NULL, *first = NULL;
2276         skinfileitem_t *skinfileitem;
2277         char word[10][MAX_QPATH];
2278
2279 /*
2280 sample file:
2281 U_bodyBox,models/players/Legoman/BikerA2.tga
2282 U_RArm,models/players/Legoman/BikerA1.tga
2283 U_LArm,models/players/Legoman/BikerA1.tga
2284 U_armor,common/nodraw
2285 U_sword,common/nodraw
2286 U_shield,common/nodraw
2287 U_homb,common/nodraw
2288 U_backpack,common/nodraw
2289 U_colcha,common/nodraw
2290 tag_head,
2291 tag_weapon,
2292 tag_torso,
2293 */
2294         memset(word, 0, sizeof(word));
2295         for (i = 0;i < 256 && (data = text = (char *)FS_LoadFile(va("%s_%i.skin", loadmodel->name, i), tempmempool, true, NULL));i++)
2296         {
2297                 // If it's the first file we parse
2298                 if (skinfile == NULL)
2299                 {
2300                         skinfile = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2301                         first = skinfile;
2302                 }
2303                 else
2304                 {
2305                         skinfile->next = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2306                         skinfile = skinfile->next;
2307                 }
2308                 skinfile->next = NULL;
2309
2310                 for(line = 0;;line++)
2311                 {
2312                         // parse line
2313                         if (!COM_ParseToken_QuakeC(&data, true))
2314                                 break;
2315                         if (!strcmp(com_token, "\n"))
2316                                 continue;
2317                         words = 0;
2318                         wordsoverflow = false;
2319                         do
2320                         {
2321                                 if (words < 10)
2322                                         strlcpy(word[words++], com_token, sizeof (word[0]));
2323                                 else
2324                                         wordsoverflow = true;
2325                         }
2326                         while (COM_ParseToken_QuakeC(&data, true) && strcmp(com_token, "\n"));
2327                         if (wordsoverflow)
2328                         {
2329                                 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);
2330                                 continue;
2331                         }
2332                         // words is always >= 1
2333                         if (!strcmp(word[0], "replace"))
2334                         {
2335                                 if (words == 3)
2336                                 {
2337                                         if (developer_loading.integer)
2338                                                 Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[1], word[2]);
2339                                         skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2340                                         skinfileitem->next = skinfile->items;
2341                                         skinfile->items = skinfileitem;
2342                                         strlcpy (skinfileitem->name, word[1], sizeof (skinfileitem->name));
2343                                         strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2344                                 }
2345                                 else
2346                                         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]);
2347                         }
2348                         else if (words >= 2 && !strncmp(word[0], "tag_", 4))
2349                         {
2350                                 // tag name, like "tag_weapon,"
2351                                 // not used for anything (not even in Quake3)
2352                         }
2353                         else if (words >= 2 && !strcmp(word[1], ","))
2354                         {
2355                                 // mesh shader name, like "U_RArm,models/players/Legoman/BikerA1.tga"
2356                                 if (developer_loading.integer)
2357                                         Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[0], word[2]);
2358                                 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2359                                 skinfileitem->next = skinfile->items;
2360                                 skinfile->items = skinfileitem;
2361                                 strlcpy (skinfileitem->name, word[0], sizeof (skinfileitem->name));
2362                                 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2363                         }
2364                         else
2365                                 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);
2366                 }
2367                 Mem_Free(text);
2368         }
2369         if (i)
2370                 loadmodel->numskins = i;
2371         return first;
2372 }
2373
2374 void Mod_FreeSkinFiles(skinfile_t *skinfile)
2375 {
2376         skinfile_t *next;
2377         skinfileitem_t *skinfileitem, *nextitem;
2378         for (;skinfile;skinfile = next)
2379         {
2380                 next = skinfile->next;
2381                 for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = nextitem)
2382                 {
2383                         nextitem = skinfileitem->next;
2384                         Mem_Free(skinfileitem);
2385                 }
2386                 Mem_Free(skinfile);
2387         }
2388 }
2389
2390 int Mod_CountSkinFiles(skinfile_t *skinfile)
2391 {
2392         int i;
2393         for (i = 0;skinfile;skinfile = skinfile->next, i++);
2394         return i;
2395 }
2396
2397 void Mod_SnapVertices(int numcomponents, int numvertices, float *vertices, float snap)
2398 {
2399         int i;
2400         double isnap = 1.0 / snap;
2401         for (i = 0;i < numvertices*numcomponents;i++)
2402                 vertices[i] = floor(vertices[i]*isnap)*snap;
2403 }
2404
2405 int Mod_RemoveDegenerateTriangles(int numtriangles, const int *inelement3i, int *outelement3i, const float *vertex3f)
2406 {
2407         int i, outtriangles;
2408         float edgedir1[3], edgedir2[3], temp[3];
2409         // a degenerate triangle is one with no width (thickness, surface area)
2410         // these are characterized by having all 3 points colinear (along a line)
2411         // or having two points identical
2412         // the simplest check is to calculate the triangle's area
2413         for (i = 0, outtriangles = 0;i < numtriangles;i++, inelement3i += 3)
2414         {
2415                 // calculate first edge
2416                 VectorSubtract(vertex3f + inelement3i[1] * 3, vertex3f + inelement3i[0] * 3, edgedir1);
2417                 VectorSubtract(vertex3f + inelement3i[2] * 3, vertex3f + inelement3i[0] * 3, edgedir2);
2418                 CrossProduct(edgedir1, edgedir2, temp);
2419                 if (VectorLength2(temp) < 0.001f)
2420                         continue; // degenerate triangle (no area)
2421                 // valid triangle (has area)
2422                 VectorCopy(inelement3i, outelement3i);
2423                 outelement3i += 3;
2424                 outtriangles++;
2425         }
2426         return outtriangles;
2427 }
2428
2429 void Mod_VertexRangeFromElements(int numelements, const int *elements, int *firstvertexpointer, int *lastvertexpointer)
2430 {
2431         int i, e;
2432         int firstvertex, lastvertex;
2433         if (numelements > 0 && elements)
2434         {
2435                 firstvertex = lastvertex = elements[0];
2436                 for (i = 1;i < numelements;i++)
2437                 {
2438                         e = elements[i];
2439                         firstvertex = min(firstvertex, e);
2440                         lastvertex = max(lastvertex, e);
2441                 }
2442         }
2443         else
2444                 firstvertex = lastvertex = 0;
2445         if (firstvertexpointer)
2446                 *firstvertexpointer = firstvertex;
2447         if (lastvertexpointer)
2448                 *lastvertexpointer = lastvertex;
2449 }
2450
2451 void Mod_MakeSortedSurfaces(dp_model_t *mod)
2452 {
2453         // make an optimal set of texture-sorted batches to draw...
2454         int j, t;
2455         int *firstsurfacefortexture;
2456         int *numsurfacesfortexture;
2457         if (!mod->sortedmodelsurfaces)
2458                 mod->sortedmodelsurfaces = (int *) Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
2459         firstsurfacefortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*firstsurfacefortexture));
2460         numsurfacesfortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*numsurfacesfortexture));
2461         memset(numsurfacesfortexture, 0, mod->num_textures * sizeof(*numsurfacesfortexture));
2462         for (j = 0;j < mod->nummodelsurfaces;j++)
2463         {
2464                 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2465                 int t = (int)(surface->texture - mod->data_textures);
2466                 numsurfacesfortexture[t]++;
2467         }
2468         j = 0;
2469         for (t = 0;t < mod->num_textures;t++)
2470         {
2471                 firstsurfacefortexture[t] = j;
2472                 j += numsurfacesfortexture[t];
2473         }
2474         for (j = 0;j < mod->nummodelsurfaces;j++)
2475         {
2476                 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2477                 int t = (int)(surface->texture - mod->data_textures);
2478                 mod->sortedmodelsurfaces[firstsurfacefortexture[t]++] = j + mod->firstmodelsurface;
2479         }
2480         Mem_Free(firstsurfacefortexture);
2481         Mem_Free(numsurfacesfortexture);
2482 }
2483
2484 static void Mod_BuildVBOs(void)
2485 {
2486         if (gl_paranoid.integer && loadmodel->surfmesh.data_element3s && loadmodel->surfmesh.data_element3i)
2487         {
2488                 int i;
2489                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2490                 {
2491                         if (loadmodel->surfmesh.data_element3s[i] != loadmodel->surfmesh.data_element3i[i])
2492                         {
2493                                 Con_Printf("Mod_BuildVBOs: element %u is incorrect (%u should be %u)\n", i, loadmodel->surfmesh.data_element3s[i], loadmodel->surfmesh.data_element3i[i]);
2494                                 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2495                         }
2496                 }
2497         }
2498
2499         if (!vid.support.arb_vertex_buffer_object)
2500                 return;
2501
2502         // element buffer is easy because it's just one array
2503         if (loadmodel->surfmesh.num_triangles)
2504         {
2505                 if (loadmodel->surfmesh.data_element3s)
2506                         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);
2507                 else
2508                         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);
2509         }
2510
2511         // vertex buffer is several arrays and we put them in the same buffer
2512         //
2513         // is this wise?  the texcoordtexture2f array is used with dynamic
2514         // vertex/svector/tvector/normal when rendering animated models, on the
2515         // other hand animated models don't use a lot of vertices anyway...
2516         if (loadmodel->surfmesh.num_vertices)
2517         {
2518                 size_t size;
2519                 unsigned char *mem;
2520                 size = 0;
2521                 loadmodel->surfmesh.vbooffset_vertex3f           = size;if (loadmodel->surfmesh.data_vertex3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2522                 loadmodel->surfmesh.vbooffset_svector3f          = size;if (loadmodel->surfmesh.data_svector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2523                 loadmodel->surfmesh.vbooffset_tvector3f          = size;if (loadmodel->surfmesh.data_tvector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2524                 loadmodel->surfmesh.vbooffset_normal3f           = size;if (loadmodel->surfmesh.data_normal3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2525                 loadmodel->surfmesh.vbooffset_texcoordtexture2f  = size;if (loadmodel->surfmesh.data_texcoordtexture2f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2526                 loadmodel->surfmesh.vbooffset_texcoordlightmap2f = size;if (loadmodel->surfmesh.data_texcoordlightmap2f) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2527                 loadmodel->surfmesh.vbooffset_lightmapcolor4f    = size;if (loadmodel->surfmesh.data_lightmapcolor4f   ) size += loadmodel->surfmesh.num_vertices * sizeof(float[4]);
2528                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
2529                 if (loadmodel->surfmesh.data_vertex3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_vertex3f          , loadmodel->surfmesh.data_vertex3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2530                 if (loadmodel->surfmesh.data_svector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_svector3f         , loadmodel->surfmesh.data_svector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2531                 if (loadmodel->surfmesh.data_tvector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_tvector3f         , loadmodel->surfmesh.data_tvector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2532                 if (loadmodel->surfmesh.data_normal3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_normal3f          , loadmodel->surfmesh.data_normal3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2533                 if (loadmodel->surfmesh.data_texcoordtexture2f ) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordtexture2f , loadmodel->surfmesh.data_texcoordtexture2f , loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2534                 if (loadmodel->surfmesh.data_texcoordlightmap2f) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordlightmap2f, loadmodel->surfmesh.data_texcoordlightmap2f, loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2535                 if (loadmodel->surfmesh.data_lightmapcolor4f   ) memcpy(mem + loadmodel->surfmesh.vbooffset_lightmapcolor4f   , loadmodel->surfmesh.data_lightmapcolor4f   , loadmodel->surfmesh.num_vertices * sizeof(float[4]));
2536                 loadmodel->surfmesh.vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, loadmodel->name);
2537                 Mem_Free(mem);
2538         }
2539 }
2540
2541 static void Mod_Decompile_OBJ(dp_model_t *model, const char *filename, const char *mtlfilename, const char *originalfilename)
2542 {
2543         int vertexindex, surfaceindex, triangleindex, textureindex, countvertices = 0, countsurfaces = 0, countfaces = 0, counttextures = 0;
2544         int a, b, c;
2545         const char *texname;
2546         const int *e;
2547         const float *v, *vn, *vt;
2548         size_t l;
2549         size_t outbufferpos = 0;
2550         size_t outbuffermax = 0x100000;
2551         char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
2552         const msurface_t *surface;
2553         const int maxtextures = 256;
2554         char *texturenames = (char *) Z_Malloc(maxtextures * MAX_QPATH);
2555
2556         // construct the mtllib file
2557         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "# mtllib for %s exported by darkplaces engine\n", originalfilename);
2558         if (l > 0)
2559                 outbufferpos += l;
2560         for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2561         {
2562                 countsurfaces++;
2563                 countvertices += surface->num_vertices;
2564                 countfaces += surface->num_triangles;
2565                 texname = (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default";
2566                 for (textureindex = 0;textureindex < counttextures;textureindex++)
2567                         if (!strcmp(texturenames + textureindex * MAX_QPATH, texname))
2568                                 break;
2569                 if (textureindex < counttextures)
2570                         continue; // already wrote this material entry
2571                 if (textureindex >= maxtextures)
2572                         continue; // just a precaution
2573                 textureindex = counttextures++;
2574                 strlcpy(texturenames + textureindex * MAX_QPATH, texname, MAX_QPATH);
2575                 if (outbufferpos >= outbuffermax >> 1)
2576                 {
2577                         outbuffermax *= 2;
2578                         oldbuffer = outbuffer;
2579                         outbuffer = (char *) Z_Malloc(outbuffermax);
2580                         memcpy(outbuffer, oldbuffer, outbufferpos);
2581                         Z_Free(oldbuffer);
2582                 }
2583                 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");
2584                 if (l > 0)
2585                         outbufferpos += l;
2586         }
2587
2588         // write the mtllib file
2589         FS_WriteFile(mtlfilename, outbuffer, outbufferpos);
2590         outbufferpos = 0;
2591
2592         // construct the obj file
2593         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);
2594         if (l > 0)
2595                 outbufferpos += l;
2596         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)
2597         {
2598                 if (outbufferpos >= outbuffermax >> 1)
2599                 {
2600                         outbuffermax *= 2;
2601                         oldbuffer = outbuffer;
2602                         outbuffer = (char *) Z_Malloc(outbuffermax);
2603                         memcpy(outbuffer, oldbuffer, outbufferpos);
2604                         Z_Free(oldbuffer);
2605                 }
2606                 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]);
2607                 if (l > 0)
2608                         outbufferpos += l;
2609         }
2610         for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2611         {
2612                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "usemtl %s\n", (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default");
2613                 if (l > 0)
2614                         outbufferpos += l;
2615                 for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
2616                 {
2617                         if (outbufferpos >= outbuffermax >> 1)
2618                         {
2619                                 outbuffermax *= 2;
2620                                 oldbuffer = outbuffer;
2621                                 outbuffer = (char *) Z_Malloc(outbuffermax);
2622                                 memcpy(outbuffer, oldbuffer, outbufferpos);
2623                                 Z_Free(oldbuffer);
2624                         }
2625                         a = e[0]+1;
2626                         b = e[2]+1;
2627                         c = e[1]+1;
2628                         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);
2629                         if (l > 0)
2630                                 outbufferpos += l;
2631                 }
2632         }
2633
2634         // write the obj file
2635         FS_WriteFile(filename, outbuffer, outbufferpos);
2636
2637         // clean up
2638         Z_Free(outbuffer);
2639         Z_Free(texturenames);
2640
2641         // print some stats
2642         Con_Printf("Wrote %s (%i bytes, %i vertices, %i faces, %i surfaces with %i distinct textures)\n", filename, (int)outbufferpos, countvertices, countfaces, countsurfaces, counttextures);
2643 }
2644
2645 static void Mod_Decompile_SMD(dp_model_t *model, const char *filename, int firstpose, int numposes, qboolean writetriangles)
2646 {
2647         int countnodes = 0, counttriangles = 0, countframes = 0;
2648         int surfaceindex;
2649         int triangleindex;
2650         int transformindex;
2651         int poseindex;
2652         int cornerindex;
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         for (transformindex = 0;transformindex < model->num_bones;transformindex++)
2664         {
2665                 if (outbufferpos >= outbuffermax >> 1)
2666                 {
2667                         outbuffermax *= 2;
2668                         oldbuffer = outbuffer;
2669                         outbuffer = (char *) Z_Malloc(outbuffermax);
2670                         memcpy(outbuffer, oldbuffer, outbufferpos);
2671                         Z_Free(oldbuffer);
2672                 }
2673                 countnodes++;
2674                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i \"%s\" %3i\n", transformindex, model->data_bones[transformindex].name, model->data_bones[transformindex].parent);
2675                 if (l > 0)
2676                         outbufferpos += l;
2677         }
2678         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\nskeleton\n");
2679         if (l > 0)
2680                 outbufferpos += l;
2681         for (poseindex = 0;poseindex < numposes;poseindex++)
2682         {
2683                 countframes++;
2684                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "time %i\n", poseindex);
2685                 if (l > 0)
2686                         outbufferpos += l;
2687                 for (transformindex = 0;transformindex < model->num_bones;transformindex++, pose += 12)
2688                 {
2689                         float a, b, c;
2690                         float angles[3];
2691                         float mtest[4][3];
2692                         matrix4x4_t posematrix;
2693                         if (outbufferpos >= outbuffermax >> 1)
2694                         {
2695                                 outbuffermax *= 2;
2696                                 oldbuffer = outbuffer;
2697                                 outbuffer = (char *) Z_Malloc(outbuffermax);
2698                                 memcpy(outbuffer, oldbuffer, outbufferpos);
2699                                 Z_Free(oldbuffer);
2700                         }
2701
2702                         // strangely the smd angles are for a transposed matrix, so we
2703                         // have to generate a transposed matrix, then convert that...
2704                         Matrix4x4_FromBonePose6s(&posematrix, model->num_posescale, model->data_poses6s + 6*(model->num_bones * poseindex + transformindex));
2705                         Matrix4x4_ToArray12FloatGL(&posematrix, mtest[0]);
2706                         AnglesFromVectors(angles, mtest[0], mtest[2], false);
2707                         if (angles[0] >= 180) angles[0] -= 360;
2708                         if (angles[1] >= 180) angles[1] -= 360;
2709                         if (angles[2] >= 180) angles[2] -= 360;
2710
2711                         a = DEG2RAD(angles[ROLL]);
2712                         b = DEG2RAD(angles[PITCH]);
2713                         c = DEG2RAD(angles[YAW]);
2714
2715 #if 0
2716 {
2717                         float cy, sy, cp, sp, cr, sr;
2718                         float test[4][3];
2719                         // smd matrix construction, for comparing
2720                         sy = sin(c);
2721                         cy = cos(c);
2722                         sp = sin(b);
2723                         cp = cos(b);
2724                         sr = sin(a);
2725                         cr = cos(a);
2726
2727                         test[0][0] = cp*cy;
2728                         test[0][1] = cp*sy;
2729                         test[0][2] = -sp;
2730                         test[1][0] = sr*sp*cy+cr*-sy;
2731                         test[1][1] = sr*sp*sy+cr*cy;
2732                         test[1][2] = sr*cp;
2733                         test[2][0] = (cr*sp*cy+-sr*-sy);
2734                         test[2][1] = (cr*sp*sy+-sr*cy);
2735                         test[2][2] = cr*cp;
2736                         test[3][0] = pose[9];
2737                         test[3][1] = pose[10];
2738                         test[3][2] = pose[11];
2739 }