]> git.xonotic.org Git - xonotic/darkplaces.git/blob - model_shared.c
mod_generatelightmaps is much closer to usable now
[xonotic/darkplaces.git] / model_shared.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // models.c -- model loading and caching
21
22 // models are the only shared resource between a client and server running
23 // on the same machine.
24
25 #include "quakedef.h"
26 #include "image.h"
27 #include "r_shadow.h"
28 #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", "16", "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
35 dp_model_t *loadmodel;
36
37 static mempool_t *mod_mempool;
38 static memexpandablearray_t models;
39
40 static mempool_t* q3shaders_mem;
41 typedef struct q3shader_hash_entry_s
42 {
43   q3shaderinfo_t shader;
44   struct q3shader_hash_entry_s* chain;
45 } q3shader_hash_entry_t;
46 #define Q3SHADER_HASH_SIZE  1021
47 typedef struct q3shader_data_s
48 {
49   memexpandablearray_t hash_entries;
50   q3shader_hash_entry_t hash[Q3SHADER_HASH_SIZE];
51   memexpandablearray_t char_ptrs;
52 } q3shader_data_t;
53 static q3shader_data_t* q3shader_data;
54
55 static void mod_start(void)
56 {
57         int i, count;
58         int nummodels = Mem_ExpandableArray_IndexRange(&models);
59         dp_model_t *mod;
60
61         SCR_PushLoadingScreen(false, "Loading models", 1.0);
62         count = 0;
63         for (i = 0;i < nummodels;i++)
64                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
65                         if (mod->used)
66                                 ++count;
67         for (i = 0;i < nummodels;i++)
68                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
69                         if (mod->used)
70                         {
71                                 SCR_PushLoadingScreen(true, mod->name, 1.0 / count);
72                                 Mod_LoadModel(mod, true, false);
73                                 SCR_PopLoadingScreen(false);
74                         }
75         SCR_PopLoadingScreen(false);
76 }
77
78 static void mod_shutdown(void)
79 {
80         int i;
81         int nummodels = Mem_ExpandableArray_IndexRange(&models);
82         dp_model_t *mod;
83
84         for (i = 0;i < nummodels;i++)
85                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && (mod->loaded || mod->mempool))
86                         Mod_UnloadModel(mod);
87
88         Mod_FreeQ3Shaders();
89 }
90
91 static void mod_newmap(void)
92 {
93         msurface_t *surface;
94         int i, j, k, surfacenum, ssize, tsize;
95         int nummodels = Mem_ExpandableArray_IndexRange(&models);
96         dp_model_t *mod;
97
98         for (i = 0;i < nummodels;i++)
99         {
100                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool)
101                 {
102                         for (j = 0;j < mod->num_textures && mod->data_textures;j++)
103                         {
104                                 for (k = 0;k < mod->data_textures[j].numskinframes;k++)
105                                         R_SkinFrame_MarkUsed(mod->data_textures[j].skinframes[k]);
106                                 for (k = 0;k < mod->data_textures[j].backgroundnumskinframes;k++)
107                                         R_SkinFrame_MarkUsed(mod->data_textures[j].backgroundskinframes[k]);
108                         }
109                         if (mod->brush.solidskyskinframe)
110                                 R_SkinFrame_MarkUsed(mod->brush.solidskyskinframe);
111                         if (mod->brush.alphaskyskinframe)
112                                 R_SkinFrame_MarkUsed(mod->brush.alphaskyskinframe);
113                 }
114         }
115
116         if (!cl_stainmaps_clearonload.integer)
117                 return;
118
119         for (i = 0;i < nummodels;i++)
120         {
121                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool && mod->data_surfaces)
122                 {
123                         for (surfacenum = 0, surface = mod->data_surfaces;surfacenum < mod->num_surfaces;surfacenum++, surface++)
124                         {
125                                 if (surface->lightmapinfo && surface->lightmapinfo->stainsamples)
126                                 {
127                                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
128                                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
129                                         memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
130                                         mod->brushq1.lightmapupdateflags[surfacenum] = true;
131                                 }
132                         }
133                 }
134         }
135 }
136
137 /*
138 ===============
139 Mod_Init
140 ===============
141 */
142 static void Mod_Print(void);
143 static void Mod_Precache (void);
144 static void Mod_Decompile_f(void);
145 static void Mod_BuildVBOs(void);
146 static void Mod_GenerateLightmaps_f(void);
147 void Mod_Init (void)
148 {
149         mod_mempool = Mem_AllocPool("modelinfo", 0, NULL);
150         Mem_ExpandableArray_NewArray(&models, mod_mempool, sizeof(dp_model_t), 16);
151
152         Mod_BrushInit();
153         Mod_AliasInit();
154         Mod_SpriteInit();
155
156         Cvar_RegisterVariable(&r_mipskins);
157         Cvar_RegisterVariable(&mod_generatelightmaps_unitspersample);
158         Cvar_RegisterVariable(&mod_generatelightmaps_borderpixels);
159         Cvar_RegisterVariable(&mod_generatelightmaps_texturesize);
160         Cmd_AddCommand ("modellist", Mod_Print, "prints a list of loaded models");
161         Cmd_AddCommand ("modelprecache", Mod_Precache, "load a model");
162         Cmd_AddCommand ("modeldecompile", Mod_Decompile_f, "exports a model in several formats for editing purposes");
163         Cmd_AddCommand ("mod_generatelightmaps", Mod_GenerateLightmaps_f, "rebuilds lighting on current worldmodel");
164 }
165
166 void Mod_RenderInit(void)
167 {
168         R_RegisterModule("Models", mod_start, mod_shutdown, mod_newmap);
169 }
170
171 void Mod_UnloadModel (dp_model_t *mod)
172 {
173         char name[MAX_QPATH];
174         qboolean used;
175         dp_model_t *parentmodel;
176
177         if (developer_loading.integer)
178                 Con_Printf("unloading model %s\n", mod->name);
179
180         strlcpy(name, mod->name, sizeof(name));
181         parentmodel = mod->brush.parentmodel;
182         used = mod->used;
183         if (mod->surfmesh.ebo3i)
184                 R_Mesh_DestroyBufferObject(mod->surfmesh.ebo3i);
185         if (mod->surfmesh.ebo3s)
186                 R_Mesh_DestroyBufferObject(mod->surfmesh.ebo3s);
187         if (mod->surfmesh.vbo)
188                 R_Mesh_DestroyBufferObject(mod->surfmesh.vbo);
189         // free textures/memory attached to the model
190         R_FreeTexturePool(&mod->texturepool);
191         Mem_FreePool(&mod->mempool);
192         // clear the struct to make it available
193         memset(mod, 0, sizeof(dp_model_t));
194         // restore the fields we want to preserve
195         strlcpy(mod->name, name, sizeof(mod->name));
196         mod->brush.parentmodel = parentmodel;
197         mod->used = used;
198         mod->loaded = false;
199 }
200
201 void R_Model_Null_Draw(entity_render_t *ent)
202 {
203         return;
204 }
205
206
207 typedef void (*mod_framegroupify_parsegroups_t) (unsigned int i, int start, int len, float fps, qboolean loop, void *pass);
208
209 int Mod_FrameGroupify_ParseGroups(const char *buf, mod_framegroupify_parsegroups_t cb, void *pass)
210 {
211         const char *bufptr;
212         int start, len;
213         float fps;
214         unsigned int i;
215         qboolean loop;
216
217         bufptr = buf;
218         i = 0;
219         for(;;)
220         {
221                 // an anim scene!
222                 if (!COM_ParseToken_Simple(&bufptr, true, false))
223                         break;
224                 if (!strcmp(com_token, "\n"))
225                         continue; // empty line
226                 start = atoi(com_token);
227                 if (!COM_ParseToken_Simple(&bufptr, true, false))
228                         break;
229                 if (!strcmp(com_token, "\n"))
230                 {
231                         Con_Printf("framegroups file: missing number of frames\n");
232                         continue;
233                 }
234                 len = atoi(com_token);
235                 if (!COM_ParseToken_Simple(&bufptr, true, false))
236                         break;
237                 // we default to looping as it's usually wanted, so to NOT loop you append a 0
238                 if (strcmp(com_token, "\n"))
239                 {
240                         fps = atof(com_token);
241                         if (!COM_ParseToken_Simple(&bufptr, true, false))
242                                 break;
243                         if (strcmp(com_token, "\n"))
244                                 loop = atoi(com_token) != 0;
245                         else
246                                 loop = true;
247                 }
248                 else
249                 {
250                         fps = 20;
251                         loop = true;
252                 }
253
254                 if(cb)
255                         cb(i, start, len, fps, loop, pass);
256                 ++i;
257         }
258
259         return i;
260 }
261
262 void Mod_FrameGroupify_ParseGroups_Count (unsigned int i, int start, int len, float fps, qboolean loop, void *pass)
263 {
264         unsigned int *cnt = (unsigned int *) pass;
265         ++*cnt;
266 }
267
268 void Mod_FrameGroupify_ParseGroups_Store (unsigned int i, int start, int len, float fps, qboolean loop, void *pass)
269 {
270         dp_model_t *mod = (dp_model_t *) pass;
271         animscene_t *anim = &mod->animscenes[i];
272         dpsnprintf(anim->name, sizeof(anim[i].name), "groupified_%d", i);
273         anim->firstframe = bound(0, start, mod->num_poses - 1);
274         anim->framecount = bound(1, len, mod->num_poses - anim->firstframe);
275         anim->framerate = max(1, fps);
276         anim->loop = !!loop;
277         //Con_Printf("frame group %d is %d %d %f %d\n", i, start, len, fps, loop);
278 }
279
280 void Mod_FrameGroupify(dp_model_t *mod, const char *buf)
281 {
282         unsigned int cnt;
283
284         // 0. count
285         cnt = Mod_FrameGroupify_ParseGroups(buf, NULL, NULL);
286         if(!cnt)
287         {
288                 Con_Printf("no scene found in framegroups file, aborting\n");
289                 return;
290         }
291         mod->numframes = cnt;
292
293         // 1. reallocate
294         // (we do not free the previous animscenes, but model unloading will free the pool owning them, so it's okay)
295         mod->animscenes = (animscene_t *) Mem_Alloc(mod->mempool, sizeof(animscene_t) * mod->numframes);
296
297         // 2. parse
298         Mod_FrameGroupify_ParseGroups(buf, Mod_FrameGroupify_ParseGroups_Store, mod);
299 }
300
301 /*
302 ==================
303 Mod_LoadModel
304
305 Loads a model
306 ==================
307 */
308 dp_model_t *Mod_LoadModel(dp_model_t *mod, qboolean crash, qboolean checkdisk)
309 {
310         int num;
311         unsigned int crc;
312         void *buf;
313         fs_offset_t filesize;
314
315         mod->used = true;
316
317         if (mod->name[0] == '*') // submodel
318                 return mod;
319         
320         if (!strcmp(mod->name, "null"))
321         {
322                 if(mod->loaded)
323                         return mod;
324
325                 if (mod->loaded || mod->mempool)
326                         Mod_UnloadModel(mod);
327
328                 if (developer_loading.integer)
329                         Con_Printf("loading model %s\n", mod->name);
330
331                 mod->used = true;
332                 mod->crc = (unsigned int)-1;
333                 mod->loaded = false;
334
335                 VectorClear(mod->normalmins);
336                 VectorClear(mod->normalmaxs);
337                 VectorClear(mod->yawmins);
338                 VectorClear(mod->yawmaxs);
339                 VectorClear(mod->rotatedmins);
340                 VectorClear(mod->rotatedmaxs);
341
342                 mod->modeldatatypestring = "null";
343                 mod->type = mod_null;
344                 mod->Draw = R_Model_Null_Draw;
345                 mod->numframes = 2;
346                 mod->numskins = 1;
347
348                 // no fatal errors occurred, so this model is ready to use.
349                 mod->loaded = true;
350
351                 return mod;
352         }
353
354         crc = 0;
355         buf = NULL;
356
357         // even if the model is loaded it still may need reloading...
358
359         // if it is not loaded or checkdisk is true we need to calculate the crc
360         if (!mod->loaded || checkdisk)
361         {
362                 if (checkdisk && mod->loaded)
363                         Con_DPrintf("checking model %s\n", mod->name);
364                 buf = FS_LoadFile (mod->name, tempmempool, false, &filesize);
365                 if (buf)
366                 {
367                         crc = CRC_Block((unsigned char *)buf, filesize);
368                         // we need to reload the model if the crc does not match
369                         if (mod->crc != crc)
370                                 mod->loaded = false;
371                 }
372         }
373
374         // if the model is already loaded and checks passed, just return
375         if (mod->loaded)
376         {
377                 if (buf)
378                         Mem_Free(buf);
379                 return mod;
380         }
381
382         if (developer_loading.integer)
383                 Con_Printf("loading model %s\n", mod->name);
384         
385         SCR_PushLoadingScreen(true, mod->name, 1);
386
387         // LordHavoc: unload the existing model in this slot (if there is one)
388         if (mod->loaded || mod->mempool)
389                 Mod_UnloadModel(mod);
390
391         // load the model
392         mod->used = true;
393         mod->crc = crc;
394         // errors can prevent the corresponding mod->loaded = true;
395         mod->loaded = false;
396
397         // default model radius and bounding box (mainly for missing models)
398         mod->radius = 16;
399         VectorSet(mod->normalmins, -mod->radius, -mod->radius, -mod->radius);
400         VectorSet(mod->normalmaxs, mod->radius, mod->radius, mod->radius);
401         VectorSet(mod->yawmins, -mod->radius, -mod->radius, -mod->radius);
402         VectorSet(mod->yawmaxs, mod->radius, mod->radius, mod->radius);
403         VectorSet(mod->rotatedmins, -mod->radius, -mod->radius, -mod->radius);
404         VectorSet(mod->rotatedmaxs, mod->radius, mod->radius, mod->radius);
405
406         if (!q3shaders_mem)
407         {
408                 // load q3 shaders for the first time, or after a level change
409                 Mod_LoadQ3Shaders();
410         }
411
412         if (buf)
413         {
414                 char *bufend = (char *)buf + filesize;
415
416                 // all models use memory, so allocate a memory pool
417                 mod->mempool = Mem_AllocPool(mod->name, 0, NULL);
418
419                 num = LittleLong(*((int *)buf));
420                 // call the apropriate loader
421                 loadmodel = mod;
422                      if (!strcasecmp(FS_FileExtension(mod->name), "obj")) Mod_OBJ_Load(mod, buf, bufend);
423                 else if (!memcmp(buf, "IDPO", 4)) Mod_IDP0_Load(mod, buf, bufend);
424                 else if (!memcmp(buf, "IDP2", 4)) Mod_IDP2_Load(mod, buf, bufend);
425                 else if (!memcmp(buf, "IDP3", 4)) Mod_IDP3_Load(mod, buf, bufend);
426                 else if (!memcmp(buf, "IDSP", 4)) Mod_IDSP_Load(mod, buf, bufend);
427                 else if (!memcmp(buf, "IDS2", 4)) Mod_IDS2_Load(mod, buf, bufend);
428                 else if (!memcmp(buf, "IBSP", 4)) Mod_IBSP_Load(mod, buf, bufend);
429                 else if (!memcmp(buf, "ZYMOTICMODEL", 12)) Mod_ZYMOTICMODEL_Load(mod, buf, bufend);
430                 else if (!memcmp(buf, "DARKPLACESMODEL", 16)) Mod_DARKPLACESMODEL_Load(mod, buf, bufend);
431                 else if (!memcmp(buf, "ACTRHEAD", 8)) Mod_PSKMODEL_Load(mod, buf, bufend);
432                 else if (strlen(mod->name) >= 4 && !strcmp(mod->name + strlen(mod->name) - 4, ".map")) Mod_MAP_Load(mod, buf, bufend);
433                 else if (num == BSPVERSION || num == 30) Mod_Q1BSP_Load(mod, buf, bufend);
434                 else Con_Printf("Mod_LoadModel: model \"%s\" is of unknown/unsupported type\n", mod->name);
435                 Mem_Free(buf);
436
437                 buf = FS_LoadFile (va("%s.framegroups", mod->name), tempmempool, false, &filesize);
438                 if(buf)
439                 {
440                         Mod_FrameGroupify(mod, (const char *)buf);
441                         Mem_Free(buf);
442                 }
443
444                 Mod_BuildVBOs();
445         }
446         else if (crash)
447         {
448                 // LordHavoc: Sys_Error was *ANNOYING*
449                 Con_Printf ("Mod_LoadModel: %s not found\n", mod->name);
450         }
451
452         // no fatal errors occurred, so this model is ready to use.
453         mod->loaded = true;
454
455         SCR_PopLoadingScreen(false);
456
457         return mod;
458 }
459
460 void Mod_ClearUsed(void)
461 {
462         int i;
463         int nummodels = Mem_ExpandableArray_IndexRange(&models);
464         dp_model_t *mod;
465         for (i = 0;i < nummodels;i++)
466                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0])
467                         mod->used = false;
468 }
469
470 void Mod_PurgeUnused(void)
471 {
472         int i;
473         int nummodels = Mem_ExpandableArray_IndexRange(&models);
474         dp_model_t *mod;
475         for (i = 0;i < nummodels;i++)
476         {
477                 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !mod->used)
478                 {
479                         Mod_UnloadModel(mod);
480                         Mem_ExpandableArray_FreeRecord(&models, mod);
481                 }
482         }
483 }
484
485 /*
486 ==================
487 Mod_FindName
488
489 ==================
490 */
491 dp_model_t *Mod_FindName(const char *name, const char *parentname)
492 {
493         int i;
494         int nummodels;
495         dp_model_t *mod;
496
497         if (!parentname)
498                 parentname = "";
499
500         // if we're not dedicatd, the renderer calls will crash without video
501         Host_StartVideo();
502
503         nummodels = Mem_ExpandableArray_IndexRange(&models);
504
505         if (!name[0])
506                 Host_Error ("Mod_ForName: NULL name");
507
508         // search the currently loaded models
509         for (i = 0;i < nummodels;i++)
510         {
511                 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))))
512                 {
513                         mod->used = true;
514                         return mod;
515                 }
516         }
517
518         // no match found, create a new one
519         mod = (dp_model_t *) Mem_ExpandableArray_AllocRecord(&models);
520         strlcpy(mod->name, name, sizeof(mod->name));
521         if (parentname[0])
522                 mod->brush.parentmodel = Mod_FindName(parentname, NULL);
523         else
524                 mod->brush.parentmodel = NULL;
525         mod->loaded = false;
526         mod->used = true;
527         return mod;
528 }
529
530 /*
531 ==================
532 Mod_ForName
533
534 Loads in a model for the given name
535 ==================
536 */
537 dp_model_t *Mod_ForName(const char *name, qboolean crash, qboolean checkdisk, const char *parentname)
538 {
539         dp_model_t *model;
540         model = Mod_FindName(name, parentname);
541         if (!model->loaded || checkdisk)
542                 Mod_LoadModel(model, crash, checkdisk);
543         return model;
544 }
545
546 /*
547 ==================
548 Mod_Reload
549
550 Reloads all models if they have changed
551 ==================
552 */
553 void Mod_Reload(void)
554 {
555         int i, count;
556         int nummodels = Mem_ExpandableArray_IndexRange(&models);
557         dp_model_t *mod;
558
559         SCR_PushLoadingScreen(false, "Reloading models", 1.0);
560         count = 0;
561         for (i = 0;i < nummodels;i++)
562                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
563                         ++count;
564         for (i = 0;i < nummodels;i++)
565                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
566                 {
567                         SCR_PushLoadingScreen(true, mod->name, 1.0 / count);
568                         Mod_LoadModel(mod, true, true);
569                         SCR_PopLoadingScreen(false);
570                 }
571         SCR_PopLoadingScreen(false);
572 }
573
574 unsigned char *mod_base;
575
576
577 //=============================================================================
578
579 /*
580 ================
581 Mod_Print
582 ================
583 */
584 static void Mod_Print(void)
585 {
586         int i;
587         int nummodels = Mem_ExpandableArray_IndexRange(&models);
588         dp_model_t *mod;
589
590         Con_Print("Loaded models:\n");
591         for (i = 0;i < nummodels;i++)
592         {
593                 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
594                 {
595                         if (mod->brush.numsubmodels)
596                                 Con_Printf("%4iK %s (%i submodels)\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name, mod->brush.numsubmodels);
597                         else
598                                 Con_Printf("%4iK %s\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name);
599                 }
600         }
601 }
602
603 /*
604 ================
605 Mod_Precache
606 ================
607 */
608 static void Mod_Precache(void)
609 {
610         if (Cmd_Argc() == 2)
611                 Mod_ForName(Cmd_Argv(1), false, true, Cmd_Argv(1)[0] == '*' ? cl.model_name[1] : NULL);
612         else
613                 Con_Print("usage: modelprecache <filename>\n");
614 }
615
616 int Mod_BuildVertexRemapTableFromElements(int numelements, const int *elements, int numvertices, int *remapvertices)
617 {
618         int i, count;
619         unsigned char *used;
620         used = (unsigned char *)Mem_Alloc(tempmempool, numvertices);
621         memset(used, 0, numvertices);
622         for (i = 0;i < numelements;i++)
623                 used[elements[i]] = 1;
624         for (i = 0, count = 0;i < numvertices;i++)
625                 remapvertices[i] = used[i] ? count++ : -1;
626         Mem_Free(used);
627         return count;
628 }
629
630 #if 1
631 // fast way, using an edge hash
632 #define TRIANGLEEDGEHASH 8192
633 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
634 {
635         int i, j, p, e1, e2, *n, hashindex, count, match;
636         const int *e;
637         typedef struct edgehashentry_s
638         {
639                 struct edgehashentry_s *next;
640                 int triangle;
641                 int element[2];
642         }
643         edgehashentry_t;
644         edgehashentry_t *edgehash[TRIANGLEEDGEHASH], *edgehashentries, edgehashentriesbuffer[TRIANGLEEDGEHASH*3], *hash;
645         memset(edgehash, 0, sizeof(edgehash));
646         edgehashentries = edgehashentriesbuffer;
647         // if there are too many triangles for the stack array, allocate larger buffer
648         if (numtriangles > TRIANGLEEDGEHASH)
649                 edgehashentries = (edgehashentry_t *)Mem_Alloc(tempmempool, numtriangles * 3 * sizeof(edgehashentry_t));
650         // find neighboring triangles
651         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
652         {
653                 for (j = 0, p = 2;j < 3;p = j, j++)
654                 {
655                         e1 = e[p];
656                         e2 = e[j];
657                         // this hash index works for both forward and backward edges
658                         hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
659                         hash = edgehashentries + i * 3 + j;
660                         hash->next = edgehash[hashindex];
661                         edgehash[hashindex] = hash;
662                         hash->triangle = i;
663                         hash->element[0] = e1;
664                         hash->element[1] = e2;
665                 }
666         }
667         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
668         {
669                 for (j = 0, p = 2;j < 3;p = j, j++)
670                 {
671                         e1 = e[p];
672                         e2 = e[j];
673                         // this hash index works for both forward and backward edges
674                         hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
675                         count = 0;
676                         match = -1;
677                         for (hash = edgehash[hashindex];hash;hash = hash->next)
678                         {
679                                 if (hash->element[0] == e2 && hash->element[1] == e1)
680                                 {
681                                         if (hash->triangle != i)
682                                                 match = hash->triangle;
683                                         count++;
684                                 }
685                                 else if ((hash->element[0] == e1 && hash->element[1] == e2))
686                                         count++;
687                         }
688                         // detect edges shared by three triangles and make them seams
689                         if (count > 2)
690                                 match = -1;
691                         n[p] = match;
692                 }
693
694                 // also send a keepalive here (this can take a while too!)
695                 CL_KeepaliveMessage(false);
696         }
697         // free the allocated buffer
698         if (edgehashentries != edgehashentriesbuffer)
699                 Mem_Free(edgehashentries);
700 }
701 #else
702 // very slow but simple way
703 static int Mod_FindTriangleWithEdge(const int *elements, int numtriangles, int start, int end, int ignore)
704 {
705         int i, match, count;
706         count = 0;
707         match = -1;
708         for (i = 0;i < numtriangles;i++, elements += 3)
709         {
710                      if ((elements[0] == start && elements[1] == end)
711                       || (elements[1] == start && elements[2] == end)
712                       || (elements[2] == start && elements[0] == end))
713                 {
714                         if (i != ignore)
715                                 match = i;
716                         count++;
717                 }
718                 else if ((elements[1] == start && elements[0] == end)
719                       || (elements[2] == start && elements[1] == end)
720                       || (elements[0] == start && elements[2] == end))
721                         count++;
722         }
723         // detect edges shared by three triangles and make them seams
724         if (count > 2)
725                 match = -1;
726         return match;
727 }
728
729 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
730 {
731         int i, *n;
732         const int *e;
733         for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
734         {
735                 n[0] = Mod_FindTriangleWithEdge(elements, numtriangles, e[1], e[0], i);
736                 n[1] = Mod_FindTriangleWithEdge(elements, numtriangles, e[2], e[1], i);
737                 n[2] = Mod_FindTriangleWithEdge(elements, numtriangles, e[0], e[2], i);
738         }
739 }
740 #endif
741
742 void Mod_ValidateElements(int *elements, int numtriangles, int firstvertex, int numverts, const char *filename, int fileline)
743 {
744         int i, warned = false, endvertex = firstvertex + numverts;
745         for (i = 0;i < numtriangles * 3;i++)
746         {
747                 if (elements[i] < firstvertex || elements[i] >= endvertex)
748                 {
749                         if (!warned)
750                         {
751                                 warned = true;
752                                 Con_Printf("Mod_ValidateElements: out of bounds elements detected at %s:%d\n", filename, fileline);
753                         }
754                         elements[i] = firstvertex;
755                 }
756         }
757 }
758
759 // warning: this is an expensive function!
760 void Mod_BuildNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const int *elements, float *normal3f, qboolean areaweighting)
761 {
762         int i, j;
763         const int *element;
764         float *vectorNormal;
765         float areaNormal[3];
766         // clear the vectors
767         memset(normal3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
768         // process each vertex of each triangle and accumulate the results
769         // use area-averaging, to make triangles with a big area have a bigger
770         // weighting on the vertex normal than triangles with a small area
771         // to do so, just add the 'normals' together (the bigger the area
772         // the greater the length of the normal is
773         element = elements;
774         for (i = 0; i < numtriangles; i++, element += 3)
775         {
776                 TriangleNormal(
777                         vertex3f + element[0] * 3,
778                         vertex3f + element[1] * 3,
779                         vertex3f + element[2] * 3,
780                         areaNormal
781                         );
782
783                 if (!areaweighting)
784                         VectorNormalize(areaNormal);
785
786                 for (j = 0;j < 3;j++)
787                 {
788                         vectorNormal = normal3f + element[j] * 3;
789                         vectorNormal[0] += areaNormal[0];
790                         vectorNormal[1] += areaNormal[1];
791                         vectorNormal[2] += areaNormal[2];
792                 }
793         }
794         // and just normalize the accumulated vertex normal in the end
795         vectorNormal = normal3f + 3 * firstvertex;
796         for (i = 0; i < numvertices; i++, vectorNormal += 3)
797                 VectorNormalize(vectorNormal);
798 }
799
800 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)
801 {
802         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
803         // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
804         // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
805
806         // 6 multiply, 9 subtract
807         VectorSubtract(v1, v0, v10);
808         VectorSubtract(v2, v0, v20);
809         normal3f[0] = v20[1] * v10[2] - v20[2] * v10[1];
810         normal3f[1] = v20[2] * v10[0] - v20[0] * v10[2];
811         normal3f[2] = v20[0] * v10[1] - v20[1] * v10[0];
812         // 12 multiply, 10 subtract
813         tc10[1] = tc1[1] - tc0[1];
814         tc20[1] = tc2[1] - tc0[1];
815         svector3f[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
816         svector3f[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
817         svector3f[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
818         tc10[0] = tc1[0] - tc0[0];
819         tc20[0] = tc2[0] - tc0[0];
820         tvector3f[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
821         tvector3f[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
822         tvector3f[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
823         // 12 multiply, 4 add, 6 subtract
824         f = DotProduct(svector3f, normal3f);
825         svector3f[0] -= f * normal3f[0];
826         svector3f[1] -= f * normal3f[1];
827         svector3f[2] -= f * normal3f[2];
828         f = DotProduct(tvector3f, normal3f);
829         tvector3f[0] -= f * normal3f[0];
830         tvector3f[1] -= f * normal3f[1];
831         tvector3f[2] -= f * normal3f[2];
832         // if texture is mapped the wrong way (counterclockwise), the tangents
833         // have to be flipped, this is detected by calculating a normal from the
834         // two tangents, and seeing if it is opposite the surface normal
835         // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
836         CrossProduct(tvector3f, svector3f, tangentcross);
837         if (DotProduct(tangentcross, normal3f) < 0)
838         {
839                 VectorNegate(svector3f, svector3f);
840                 VectorNegate(tvector3f, tvector3f);
841         }
842 }
843
844 // warning: this is a very expensive function!
845 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)
846 {
847         int i, tnum;
848         float sdir[3], tdir[3], normal[3], *sv, *tv;
849         const float *v0, *v1, *v2, *tc0, *tc1, *tc2, *n;
850         float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
851         const int *e;
852         // clear the vectors
853         memset(svector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
854         memset(tvector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
855         // process each vertex of each triangle and accumulate the results
856         for (tnum = 0, e = elements;tnum < numtriangles;tnum++, e += 3)
857         {
858                 v0 = vertex3f + e[0] * 3;
859                 v1 = vertex3f + e[1] * 3;
860                 v2 = vertex3f + e[2] * 3;
861                 tc0 = texcoord2f + e[0] * 2;
862                 tc1 = texcoord2f + e[1] * 2;
863                 tc2 = texcoord2f + e[2] * 2;
864
865                 // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
866                 // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
867
868                 // calculate the edge directions and surface normal
869                 // 6 multiply, 9 subtract
870                 VectorSubtract(v1, v0, v10);
871                 VectorSubtract(v2, v0, v20);
872                 normal[0] = v20[1] * v10[2] - v20[2] * v10[1];
873                 normal[1] = v20[2] * v10[0] - v20[0] * v10[2];
874                 normal[2] = v20[0] * v10[1] - v20[1] * v10[0];
875
876                 // calculate the tangents
877                 // 12 multiply, 10 subtract
878                 tc10[1] = tc1[1] - tc0[1];
879                 tc20[1] = tc2[1] - tc0[1];
880                 sdir[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
881                 sdir[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
882                 sdir[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
883                 tc10[0] = tc1[0] - tc0[0];
884                 tc20[0] = tc2[0] - tc0[0];
885                 tdir[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
886                 tdir[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
887                 tdir[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
888
889                 // if texture is mapped the wrong way (counterclockwise), the tangents
890                 // have to be flipped, this is detected by calculating a normal from the
891                 // two tangents, and seeing if it is opposite the surface normal
892                 // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
893                 CrossProduct(tdir, sdir, tangentcross);
894                 if (DotProduct(tangentcross, normal) < 0)
895                 {
896                         VectorNegate(sdir, sdir);
897                         VectorNegate(tdir, tdir);
898                 }
899
900                 if (!areaweighting)
901                 {
902                         VectorNormalize(sdir);
903                         VectorNormalize(tdir);
904                 }
905                 for (i = 0;i < 3;i++)
906                 {
907                         VectorAdd(svector3f + e[i]*3, sdir, svector3f + e[i]*3);
908                         VectorAdd(tvector3f + e[i]*3, tdir, tvector3f + e[i]*3);
909                 }
910         }
911         // make the tangents completely perpendicular to the surface normal, and
912         // then normalize them
913         // 16 assignments, 2 divide, 2 sqrt, 2 negates, 14 adds, 24 multiplies
914         for (i = 0, sv = svector3f + 3 * firstvertex, tv = tvector3f + 3 * firstvertex, n = normal3f + 3 * firstvertex;i < numvertices;i++, sv += 3, tv += 3, n += 3)
915         {
916                 f = -DotProduct(sv, n);
917                 VectorMA(sv, f, n, sv);
918                 VectorNormalize(sv);
919                 f = -DotProduct(tv, n);
920                 VectorMA(tv, f, n, tv);
921                 VectorNormalize(tv);
922         }
923 }
924
925 void Mod_AllocSurfMesh(mempool_t *mempool, int numvertices, int numtriangles, qboolean lightmapoffsets, qboolean vertexcolors, qboolean neighbors)
926 {
927         unsigned char *data;
928         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));
929         loadmodel->surfmesh.num_vertices = numvertices;
930         loadmodel->surfmesh.num_triangles = numtriangles;
931         if (loadmodel->surfmesh.num_vertices)
932         {
933                 loadmodel->surfmesh.data_vertex3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
934                 loadmodel->surfmesh.data_svector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
935                 loadmodel->surfmesh.data_tvector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
936                 loadmodel->surfmesh.data_normal3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
937                 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
938                 loadmodel->surfmesh.data_texcoordlightmap2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
939                 if (vertexcolors)
940                         loadmodel->surfmesh.data_lightmapcolor4f = (float *)data, data += sizeof(float[4]) * loadmodel->surfmesh.num_vertices;
941                 if (lightmapoffsets)
942                         loadmodel->surfmesh.data_lightmapoffsets = (int *)data, data += sizeof(int) * loadmodel->surfmesh.num_vertices;
943         }
944         if (loadmodel->surfmesh.num_triangles)
945         {
946                 loadmodel->surfmesh.data_element3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
947                 if (neighbors)
948                         loadmodel->surfmesh.data_neighbor3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
949                 if (loadmodel->surfmesh.num_vertices <= 65536)
950                         loadmodel->surfmesh.data_element3s = (unsigned short *)data, data += sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles;
951         }
952 }
953
954 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)
955 {
956         shadowmesh_t *newmesh;
957         unsigned char *data;
958         int size;
959         size = sizeof(shadowmesh_t);
960         size += maxverts * sizeof(float[3]);
961         if (light)
962                 size += maxverts * sizeof(float[11]);
963         size += maxtriangles * sizeof(int[3]);
964         if (maxverts <= 65536)
965                 size += maxtriangles * sizeof(unsigned short[3]);
966         if (neighbors)
967                 size += maxtriangles * sizeof(int[3]);
968         if (expandable)
969                 size += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *) + maxverts * sizeof(shadowmeshvertexhash_t);
970         data = (unsigned char *)Mem_Alloc(mempool, size);
971         newmesh = (shadowmesh_t *)data;data += sizeof(*newmesh);
972         newmesh->map_diffuse = map_diffuse;
973         newmesh->map_specular = map_specular;
974         newmesh->map_normal = map_normal;
975         newmesh->maxverts = maxverts;
976         newmesh->maxtriangles = maxtriangles;
977         newmesh->numverts = 0;
978         newmesh->numtriangles = 0;
979         memset(newmesh->sideoffsets, 0, sizeof(newmesh->sideoffsets));
980         memset(newmesh->sidetotals, 0, sizeof(newmesh->sidetotals));
981
982         newmesh->vertex3f = (float *)data;data += maxverts * sizeof(float[3]);
983         if (light)
984         {
985                 newmesh->svector3f = (float *)data;data += maxverts * sizeof(float[3]);
986                 newmesh->tvector3f = (float *)data;data += maxverts * sizeof(float[3]);
987                 newmesh->normal3f = (float *)data;data += maxverts * sizeof(float[3]);
988                 newmesh->texcoord2f = (float *)data;data += maxverts * sizeof(float[2]);
989         }
990         newmesh->element3i = (int *)data;data += maxtriangles * sizeof(int[3]);
991         if (neighbors)
992         {
993                 newmesh->neighbor3i = (int *)data;data += maxtriangles * sizeof(int[3]);
994         }
995         if (expandable)
996         {
997                 newmesh->vertexhashtable = (shadowmeshvertexhash_t **)data;data += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *);
998                 newmesh->vertexhashentries = (shadowmeshvertexhash_t *)data;data += maxverts * sizeof(shadowmeshvertexhash_t);
999         }
1000         if (maxverts <= 65536)
1001                 newmesh->element3s = (unsigned short *)data;data += maxtriangles * sizeof(unsigned short[3]);
1002         return newmesh;
1003 }
1004
1005 shadowmesh_t *Mod_ShadowMesh_ReAlloc(mempool_t *mempool, shadowmesh_t *oldmesh, int light, int neighbors)
1006 {
1007         shadowmesh_t *newmesh;
1008         newmesh = Mod_ShadowMesh_Alloc(mempool, oldmesh->numverts, oldmesh->numtriangles, oldmesh->map_diffuse, oldmesh->map_specular, oldmesh->map_normal, light, neighbors, false);
1009         newmesh->numverts = oldmesh->numverts;
1010         newmesh->numtriangles = oldmesh->numtriangles;
1011         memcpy(newmesh->sideoffsets, oldmesh->sideoffsets, sizeof(oldmesh->sideoffsets));
1012         memcpy(newmesh->sidetotals, oldmesh->sidetotals, sizeof(oldmesh->sidetotals));
1013
1014         memcpy(newmesh->vertex3f, oldmesh->vertex3f, oldmesh->numverts * sizeof(float[3]));
1015         if (newmesh->svector3f && oldmesh->svector3f)
1016         {
1017                 memcpy(newmesh->svector3f, oldmesh->svector3f, oldmesh->numverts * sizeof(float[3]));
1018                 memcpy(newmesh->tvector3f, oldmesh->tvector3f, oldmesh->numverts * sizeof(float[3]));
1019                 memcpy(newmesh->normal3f, oldmesh->normal3f, oldmesh->numverts * sizeof(float[3]));
1020                 memcpy(newmesh->texcoord2f, oldmesh->texcoord2f, oldmesh->numverts * sizeof(float[2]));
1021         }
1022         memcpy(newmesh->element3i, oldmesh->element3i, oldmesh->numtriangles * sizeof(int[3]));
1023         if (newmesh->neighbor3i && oldmesh->neighbor3i)
1024                 memcpy(newmesh->neighbor3i, oldmesh->neighbor3i, oldmesh->numtriangles * sizeof(int[3]));
1025         return newmesh;
1026 }
1027
1028 int Mod_ShadowMesh_AddVertex(shadowmesh_t *mesh, float *vertex14f)
1029 {
1030         int hashindex, vnum;
1031         shadowmeshvertexhash_t *hash;
1032         // this uses prime numbers intentionally
1033         hashindex = (unsigned int) (vertex14f[0] * 2003 + vertex14f[1] * 4001 + vertex14f[2] * 7919) % SHADOWMESHVERTEXHASH;
1034         for (hash = mesh->vertexhashtable[hashindex];hash;hash = hash->next)
1035         {
1036                 vnum = (hash - mesh->vertexhashentries);
1037                 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]))
1038                  && (mesh->svector3f == NULL || (mesh->svector3f[vnum * 3 + 0] == vertex14f[3] && mesh->svector3f[vnum * 3 + 1] == vertex14f[4] && mesh->svector3f[vnum * 3 + 2] == vertex14f[5]))
1039                  && (mesh->tvector3f == NULL || (mesh->tvector3f[vnum * 3 + 0] == vertex14f[6] && mesh->tvector3f[vnum * 3 + 1] == vertex14f[7] && mesh->tvector3f[vnum * 3 + 2] == vertex14f[8]))
1040                  && (mesh->normal3f == NULL || (mesh->normal3f[vnum * 3 + 0] == vertex14f[9] && mesh->normal3f[vnum * 3 + 1] == vertex14f[10] && mesh->normal3f[vnum * 3 + 2] == vertex14f[11]))
1041                  && (mesh->texcoord2f == NULL || (mesh->texcoord2f[vnum * 2 + 0] == vertex14f[12] && mesh->texcoord2f[vnum * 2 + 1] == vertex14f[13])))
1042                         return hash - mesh->vertexhashentries;
1043         }
1044         vnum = mesh->numverts++;
1045         hash = mesh->vertexhashentries + vnum;
1046         hash->next = mesh->vertexhashtable[hashindex];
1047         mesh->vertexhashtable[hashindex] = hash;
1048         if (mesh->vertex3f) {mesh->vertex3f[vnum * 3 + 0] = vertex14f[0];mesh->vertex3f[vnum * 3 + 1] = vertex14f[1];mesh->vertex3f[vnum * 3 + 2] = vertex14f[2];}
1049         if (mesh->svector3f) {mesh->svector3f[vnum * 3 + 0] = vertex14f[3];mesh->svector3f[vnum * 3 + 1] = vertex14f[4];mesh->svector3f[vnum * 3 + 2] = vertex14f[5];}
1050         if (mesh->tvector3f) {mesh->tvector3f[vnum * 3 + 0] = vertex14f[6];mesh->tvector3f[vnum * 3 + 1] = vertex14f[7];mesh->tvector3f[vnum * 3 + 2] = vertex14f[8];}
1051         if (mesh->normal3f) {mesh->normal3f[vnum * 3 + 0] = vertex14f[9];mesh->normal3f[vnum * 3 + 1] = vertex14f[10];mesh->normal3f[vnum * 3 + 2] = vertex14f[11];}
1052         if (mesh->texcoord2f) {mesh->texcoord2f[vnum * 2 + 0] = vertex14f[12];mesh->texcoord2f[vnum * 2 + 1] = vertex14f[13];}
1053         return vnum;
1054 }
1055
1056 void Mod_ShadowMesh_AddTriangle(mempool_t *mempool, shadowmesh_t *mesh, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, float *vertex14f)
1057 {
1058         if (mesh->numtriangles == 0)
1059         {
1060                 // set the properties on this empty mesh to be more favorable...
1061                 // (note: this case only occurs for the first triangle added to a new mesh chain)
1062                 mesh->map_diffuse = map_diffuse;
1063                 mesh->map_specular = map_specular;
1064                 mesh->map_normal = map_normal;
1065         }
1066         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)
1067         {
1068                 if (mesh->next == NULL)
1069                         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);
1070                 mesh = mesh->next;
1071         }
1072         mesh->element3i[mesh->numtriangles * 3 + 0] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 0);
1073         mesh->element3i[mesh->numtriangles * 3 + 1] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 1);
1074         mesh->element3i[mesh->numtriangles * 3 + 2] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 2);
1075         mesh->numtriangles++;
1076 }
1077
1078 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)
1079 {
1080         int i, j, e;
1081         float vbuf[3*14], *v;
1082         memset(vbuf, 0, sizeof(vbuf));
1083         for (i = 0;i < numtris;i++)
1084         {
1085                 for (j = 0, v = vbuf;j < 3;j++, v += 14)
1086                 {
1087                         e = *element3i++;
1088                         if (vertex3f)
1089                         {
1090                                 v[0] = vertex3f[e * 3 + 0];
1091                                 v[1] = vertex3f[e * 3 + 1];
1092                                 v[2] = vertex3f[e * 3 + 2];
1093                         }
1094                         if (svector3f)
1095                         {
1096                                 v[3] = svector3f[e * 3 + 0];
1097                                 v[4] = svector3f[e * 3 + 1];
1098                                 v[5] = svector3f[e * 3 + 2];
1099                         }
1100                         if (tvector3f)
1101                         {
1102                                 v[6] = tvector3f[e * 3 + 0];
1103                                 v[7] = tvector3f[e * 3 + 1];
1104                                 v[8] = tvector3f[e * 3 + 2];
1105                         }
1106                         if (normal3f)
1107                         {
1108                                 v[9] = normal3f[e * 3 + 0];
1109                                 v[10] = normal3f[e * 3 + 1];
1110                                 v[11] = normal3f[e * 3 + 2];
1111                         }
1112                         if (texcoord2f)
1113                         {
1114                                 v[12] = texcoord2f[e * 2 + 0];
1115                                 v[13] = texcoord2f[e * 2 + 1];
1116                         }
1117                 }
1118                 Mod_ShadowMesh_AddTriangle(mempool, mesh, map_diffuse, map_specular, map_normal, vbuf);
1119         }
1120
1121         // the triangle calculation can take a while, so let's do a keepalive here
1122         CL_KeepaliveMessage(false);
1123 }
1124
1125 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)
1126 {
1127         // the preparation before shadow mesh initialization can take a while, so let's do a keepalive here
1128         CL_KeepaliveMessage(false);
1129
1130         return Mod_ShadowMesh_Alloc(mempool, maxverts, maxtriangles, map_diffuse, map_specular, map_normal, light, neighbors, expandable);
1131 }
1132
1133 static void Mod_ShadowMesh_CreateVBOs(shadowmesh_t *mesh)
1134 {
1135         if (!gl_support_arb_vertex_buffer_object)
1136                 return;
1137
1138         // element buffer is easy because it's just one array
1139         if (mesh->numtriangles)
1140         {
1141                 if (mesh->element3s)
1142                         mesh->ebo3s = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, mesh->element3s, mesh->numtriangles * sizeof(unsigned short[3]), "shadowmesh");
1143                 else
1144                         mesh->ebo3i = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, mesh->element3i, mesh->numtriangles * sizeof(unsigned int[3]), "shadowmesh");
1145         }
1146
1147         // vertex buffer is several arrays and we put them in the same buffer
1148         //
1149         // is this wise?  the texcoordtexture2f array is used with dynamic
1150         // vertex/svector/tvector/normal when rendering animated models, on the
1151         // other hand animated models don't use a lot of vertices anyway...
1152         if (mesh->numverts)
1153         {
1154                 size_t size;
1155                 unsigned char *mem;
1156                 size = 0;
1157                 mesh->vbooffset_vertex3f           = size;if (mesh->vertex3f          ) size += mesh->numverts * sizeof(float[3]);
1158                 mesh->vbooffset_svector3f          = size;if (mesh->svector3f         ) size += mesh->numverts * sizeof(float[3]);
1159                 mesh->vbooffset_tvector3f          = size;if (mesh->tvector3f         ) size += mesh->numverts * sizeof(float[3]);
1160                 mesh->vbooffset_normal3f           = size;if (mesh->normal3f          ) size += mesh->numverts * sizeof(float[3]);
1161                 mesh->vbooffset_texcoord2f         = size;if (mesh->texcoord2f        ) size += mesh->numverts * sizeof(float[2]);
1162                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
1163                 if (mesh->vertex3f          ) memcpy(mem + mesh->vbooffset_vertex3f          , mesh->vertex3f          , mesh->numverts * sizeof(float[3]));
1164                 if (mesh->svector3f         ) memcpy(mem + mesh->vbooffset_svector3f         , mesh->svector3f         , mesh->numverts * sizeof(float[3]));
1165                 if (mesh->tvector3f         ) memcpy(mem + mesh->vbooffset_tvector3f         , mesh->tvector3f         , mesh->numverts * sizeof(float[3]));
1166                 if (mesh->normal3f          ) memcpy(mem + mesh->vbooffset_normal3f          , mesh->normal3f          , mesh->numverts * sizeof(float[3]));
1167                 if (mesh->texcoord2f        ) memcpy(mem + mesh->vbooffset_texcoord2f        , mesh->texcoord2f        , mesh->numverts * sizeof(float[2]));
1168                 mesh->vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, "shadowmesh");
1169                 Mem_Free(mem);
1170         }
1171 }
1172
1173 shadowmesh_t *Mod_ShadowMesh_Finish(mempool_t *mempool, shadowmesh_t *firstmesh, qboolean light, qboolean neighbors, qboolean createvbo)
1174 {
1175         shadowmesh_t *mesh, *newmesh, *nextmesh;
1176         // reallocate meshs to conserve space
1177         for (mesh = firstmesh, firstmesh = NULL;mesh;mesh = nextmesh)
1178         {
1179                 nextmesh = mesh->next;
1180                 if (mesh->numverts >= 3 && mesh->numtriangles >= 1)
1181                 {
1182                         newmesh = Mod_ShadowMesh_ReAlloc(mempool, mesh, light, neighbors);
1183                         newmesh->next = firstmesh;
1184                         firstmesh = newmesh;
1185                         if (newmesh->element3s)
1186                         {
1187                                 int i;
1188                                 for (i = 0;i < newmesh->numtriangles*3;i++)
1189                                         newmesh->element3s[i] = newmesh->element3i[i];
1190                         }
1191                         if (createvbo)
1192                                 Mod_ShadowMesh_CreateVBOs(newmesh);
1193                 }
1194                 Mem_Free(mesh);
1195         }
1196
1197         // this can take a while, so let's do a keepalive here
1198         CL_KeepaliveMessage(false);
1199
1200         return firstmesh;
1201 }
1202
1203 void Mod_ShadowMesh_CalcBBox(shadowmesh_t *firstmesh, vec3_t mins, vec3_t maxs, vec3_t center, float *radius)
1204 {
1205         int i;
1206         shadowmesh_t *mesh;
1207         vec3_t nmins, nmaxs, ncenter, temp;
1208         float nradius2, dist2, *v;
1209         VectorClear(nmins);
1210         VectorClear(nmaxs);
1211         // calculate bbox
1212         for (mesh = firstmesh;mesh;mesh = mesh->next)
1213         {
1214                 if (mesh == firstmesh)
1215                 {
1216                         VectorCopy(mesh->vertex3f, nmins);
1217                         VectorCopy(mesh->vertex3f, nmaxs);
1218                 }
1219                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1220                 {
1221                         if (nmins[0] > v[0]) nmins[0] = v[0];if (nmaxs[0] < v[0]) nmaxs[0] = v[0];
1222                         if (nmins[1] > v[1]) nmins[1] = v[1];if (nmaxs[1] < v[1]) nmaxs[1] = v[1];
1223                         if (nmins[2] > v[2]) nmins[2] = v[2];if (nmaxs[2] < v[2]) nmaxs[2] = v[2];
1224                 }
1225         }
1226         // calculate center and radius
1227         ncenter[0] = (nmins[0] + nmaxs[0]) * 0.5f;
1228         ncenter[1] = (nmins[1] + nmaxs[1]) * 0.5f;
1229         ncenter[2] = (nmins[2] + nmaxs[2]) * 0.5f;
1230         nradius2 = 0;
1231         for (mesh = firstmesh;mesh;mesh = mesh->next)
1232         {
1233                 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1234                 {
1235                         VectorSubtract(v, ncenter, temp);
1236                         dist2 = DotProduct(temp, temp);
1237                         if (nradius2 < dist2)
1238                                 nradius2 = dist2;
1239                 }
1240         }
1241         // return data
1242         if (mins)
1243                 VectorCopy(nmins, mins);
1244         if (maxs)
1245                 VectorCopy(nmaxs, maxs);
1246         if (center)
1247                 VectorCopy(ncenter, center);
1248         if (radius)
1249                 *radius = sqrt(nradius2);
1250 }
1251
1252 void Mod_ShadowMesh_Free(shadowmesh_t *mesh)
1253 {
1254         shadowmesh_t *nextmesh;
1255         for (;mesh;mesh = nextmesh)
1256         {
1257                 if (mesh->ebo3i)
1258                         R_Mesh_DestroyBufferObject(mesh->ebo3i);
1259                 if (mesh->ebo3s)
1260                         R_Mesh_DestroyBufferObject(mesh->ebo3s);
1261                 if (mesh->vbo)
1262                         R_Mesh_DestroyBufferObject(mesh->vbo);
1263                 nextmesh = mesh->next;
1264                 Mem_Free(mesh);
1265         }
1266 }
1267
1268 void Mod_CreateCollisionMesh(dp_model_t *mod)
1269 {
1270         int k;
1271         int numcollisionmeshtriangles;
1272         const msurface_t *surface;
1273         mempool_t *mempool = mod->mempool;
1274         if (!mempool && mod->brush.parentmodel)
1275                 mempool = mod->brush.parentmodel->mempool;
1276         // make a single combined collision mesh for physics engine use
1277         // TODO rewrite this to use the collision brushes as source, to fix issues with e.g. common/caulk which creates no drawsurface
1278         numcollisionmeshtriangles = 0;
1279         for (k = 0;k < mod->nummodelsurfaces;k++)
1280         {
1281                 surface = mod->data_surfaces + mod->firstmodelsurface + k;
1282                 if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1283                         continue;
1284                 numcollisionmeshtriangles += surface->num_triangles;
1285         }
1286         mod->brush.collisionmesh = Mod_ShadowMesh_Begin(mempool, numcollisionmeshtriangles * 3, numcollisionmeshtriangles, NULL, NULL, NULL, false, false, true);
1287         for (k = 0;k < mod->nummodelsurfaces;k++)
1288         {
1289                 surface = mod->data_surfaces + mod->firstmodelsurface + k;
1290                 if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1291                         continue;
1292                 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));
1293         }
1294         mod->brush.collisionmesh = Mod_ShadowMesh_Finish(mempool, mod->brush.collisionmesh, false, true, false);
1295 }
1296
1297 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)
1298 {
1299         float v[3], tc[3];
1300         v[0] = ix;
1301         v[1] = iy;
1302         if (ix >= 0 && iy >= 0 && ix < imagewidth && iy < imageheight)
1303                 v[2] = (imagepixels[((iy*imagewidth)+ix)*4+0] + imagepixels[((iy*imagewidth)+ix)*4+1] + imagepixels[((iy*imagewidth)+ix)*4+2]) * (1.0f / 765.0f);
1304         else
1305                 v[2] = 0;
1306         Matrix4x4_Transform(pixelstepmatrix, v, vertex3f);
1307         Matrix4x4_Transform(pixeltexturestepmatrix, v, tc);
1308         texcoord2f[0] = tc[0];
1309         texcoord2f[1] = tc[1];
1310 }
1311
1312 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)
1313 {
1314         float vup[3], vdown[3], vleft[3], vright[3];
1315         float tcup[3], tcdown[3], tcleft[3], tcright[3];
1316         float sv[3], tv[3], nl[3];
1317         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, pixelstepmatrix, pixeltexturestepmatrix);
1318         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy - 1, vup, tcup, pixelstepmatrix, pixeltexturestepmatrix);
1319         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy + 1, vdown, tcdown, pixelstepmatrix, pixeltexturestepmatrix);
1320         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix - 1, iy, vleft, tcleft, pixelstepmatrix, pixeltexturestepmatrix);
1321         Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix + 1, iy, vright, tcright, pixelstepmatrix, pixeltexturestepmatrix);
1322         Mod_BuildBumpVectors(vertex3f, vup, vright, texcoord2f, tcup, tcright, svector3f, tvector3f, normal3f);
1323         Mod_BuildBumpVectors(vertex3f, vright, vdown, texcoord2f, tcright, tcdown, sv, tv, nl);
1324         VectorAdd(svector3f, sv, svector3f);
1325         VectorAdd(tvector3f, tv, tvector3f);
1326         VectorAdd(normal3f, nl, normal3f);
1327         Mod_BuildBumpVectors(vertex3f, vdown, vleft, texcoord2f, tcdown, tcleft, sv, tv, nl);
1328         VectorAdd(svector3f, sv, svector3f);
1329         VectorAdd(tvector3f, tv, tvector3f);
1330         VectorAdd(normal3f, nl, normal3f);
1331         Mod_BuildBumpVectors(vertex3f, vleft, vup, texcoord2f, tcleft, tcup, sv, tv, nl);
1332         VectorAdd(svector3f, sv, svector3f);
1333         VectorAdd(tvector3f, tv, tvector3f);
1334         VectorAdd(normal3f, nl, normal3f);
1335 }
1336
1337 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)
1338 {
1339         int x, y, ix, iy, *e;
1340         e = element3i;
1341         for (y = 0;y < height;y++)
1342         {
1343                 for (x = 0;x < width;x++)
1344                 {
1345                         e[0] = (y + 1) * (width + 1) + (x + 0);
1346                         e[1] = (y + 0) * (width + 1) + (x + 0);
1347                         e[2] = (y + 1) * (width + 1) + (x + 1);
1348                         e[3] = (y + 0) * (width + 1) + (x + 0);
1349                         e[4] = (y + 0) * (width + 1) + (x + 1);
1350                         e[5] = (y + 1) * (width + 1) + (x + 1);
1351                         e += 6;
1352                 }
1353         }
1354         Mod_BuildTriangleNeighbors(neighbor3i, element3i, width*height*2);
1355         for (y = 0, iy = y1;y < height + 1;y++, iy++)
1356                 for (x = 0, ix = x1;x < width + 1;x++, ix++, vertex3f += 3, texcoord2f += 2, svector3f += 3, tvector3f += 3, normal3f += 3)
1357                         Mod_GetTerrainVertexFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, svector3f, tvector3f, normal3f, pixelstepmatrix, pixeltexturestepmatrix);
1358 }
1359
1360 #if 0
1361 void Mod_Terrain_SurfaceRecurseChunk(dp_model_t *model, int stepsize, int x, int y)
1362 {
1363         float mins[3];
1364         float maxs[3];
1365         float chunkwidth = min(stepsize, model->terrain.width - 1 - x);
1366         float chunkheight = min(stepsize, model->terrain.height - 1 - y);
1367         float viewvector[3];
1368         unsigned int firstvertex;
1369         unsigned int *e;
1370         float *v;
1371         if (chunkwidth < 2 || chunkheight < 2)
1372                 return;
1373         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]);
1374         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]);
1375         viewvector[0] = bound(mins[0], localvieworigin, maxs[0]) - model->terrain.vieworigin[0];
1376         viewvector[1] = bound(mins[1], localvieworigin, maxs[1]) - model->terrain.vieworigin[1];
1377         viewvector[2] = bound(mins[2], localvieworigin, maxs[2]) - model->terrain.vieworigin[2];
1378         if (stepsize > 1 && VectorLength(viewvector) < stepsize*model->terrain.scale[0]*r_terrain_lodscale.value)
1379         {
1380                 // too close for this stepsize, emit as 4 chunks instead
1381                 stepsize /= 2;
1382                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y);
1383                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y);
1384                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y+stepsize);
1385                 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y+stepsize);
1386                 return;
1387         }
1388         // emit the geometry at stepsize into our vertex buffer / index buffer
1389         // we add two columns and two rows for skirt
1390         outwidth = chunkwidth+2;
1391         outheight = chunkheight+2;
1392         outwidth2 = outwidth-1;
1393         outheight2 = outheight-1;
1394         outwidth3 = outwidth+1;
1395         outheight3 = outheight+1;
1396         firstvertex = numvertices;
1397         e = model->terrain.element3i + numtriangles;
1398         numtriangles += chunkwidth*chunkheight*2+chunkwidth*2*2+chunkheight*2*2;
1399         v = model->terrain.vertex3f + numvertices;
1400         numvertices += (chunkwidth+1)*(chunkheight+1)+(chunkwidth+1)*2+(chunkheight+1)*2;
1401         // emit the triangles (note: the skirt is treated as two extra rows and two extra columns)
1402         for (ty = 0;ty < outheight;ty++)
1403         {
1404                 for (tx = 0;tx < outwidth;tx++)
1405                 {
1406                         *e++ = firstvertex + (ty  )*outwidth3+(tx  );
1407                         *e++ = firstvertex + (ty  )*outwidth3+(tx+1);
1408                         *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1409                         *e++ = firstvertex + (ty  )*outwidth3+(tx  );
1410                         *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1411                         *e++ = firstvertex + (ty+1)*outwidth3+(tx  );
1412                 }
1413         }
1414         // TODO: emit surface vertices (x+tx*stepsize, y+ty*stepsize)
1415         for (ty = 0;ty <= outheight;ty++)
1416         {
1417                 skirtrow = ty == 0 || ty == outheight;
1418                 ry = y+bound(1, ty, outheight)*stepsize;
1419                 for (tx = 0;tx <= outwidth;tx++)
1420                 {
1421                         skirt = skirtrow || tx == 0 || tx == outwidth;
1422                         rx = x+bound(1, tx, outwidth)*stepsize;
1423                         v[0] = rx*scale[0];
1424                         v[1] = ry*scale[1];
1425                         v[2] = heightmap[ry*terrainwidth+rx]*scale[2];
1426                         v += 3;
1427                 }
1428         }
1429         // TODO: emit skirt vertices
1430 }
1431
1432 void Mod_Terrain_UpdateSurfacesForViewOrigin(dp_model_t *model)
1433 {
1434         for (y = 0;y < model->terrain.size[1];y += model->terrain.
1435         Mod_Terrain_SurfaceRecurseChunk(model, model->terrain.maxstepsize, x, y);
1436         Mod_Terrain_BuildChunk(model, 
1437 }
1438 #endif
1439
1440 q3wavefunc_t Mod_LoadQ3Shaders_EnumerateWaveFunc(const char *s)
1441 {
1442         if (!strcasecmp(s, "sin"))             return Q3WAVEFUNC_SIN;
1443         if (!strcasecmp(s, "square"))          return Q3WAVEFUNC_SQUARE;
1444         if (!strcasecmp(s, "triangle"))        return Q3WAVEFUNC_TRIANGLE;
1445         if (!strcasecmp(s, "sawtooth"))        return Q3WAVEFUNC_SAWTOOTH;
1446         if (!strcasecmp(s, "inversesawtooth")) return Q3WAVEFUNC_INVERSESAWTOOTH;
1447         if (!strcasecmp(s, "noise"))           return Q3WAVEFUNC_NOISE;
1448         Con_DPrintf("Mod_LoadQ3Shaders: unknown wavefunc %s\n", s);
1449         return Q3WAVEFUNC_NONE;
1450 }
1451
1452 void Mod_FreeQ3Shaders(void)
1453 {
1454         Mem_FreePool(&q3shaders_mem);
1455 }
1456
1457 static void Q3Shader_AddToHash (q3shaderinfo_t* shader)
1458 {
1459         unsigned short hash = CRC_Block_CaseInsensitive ((const unsigned char *)shader->name, strlen (shader->name));
1460         q3shader_hash_entry_t* entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
1461         q3shader_hash_entry_t* lastEntry = NULL;
1462         while (entry != NULL)
1463         {
1464                 if (strcasecmp (entry->shader.name, shader->name) == 0)
1465                 {
1466                         unsigned char *start, *end, *start2;
1467                         start = (unsigned char *) (&shader->Q3SHADERINFO_COMPARE_START);
1468                         end = ((unsigned char *) (&shader->Q3SHADERINFO_COMPARE_END)) + sizeof(shader->Q3SHADERINFO_COMPARE_END);
1469                         start2 = (unsigned char *) (&entry->shader.Q3SHADERINFO_COMPARE_START);
1470                         if(memcmp(start, start2, end - start))
1471                                 Con_Printf("Shader '%s' already defined, ignoring mismatching redeclaration\n", shader->name);
1472                         else
1473                                 Con_DPrintf("Shader '%s' already defined\n", shader->name);
1474                         return;
1475                 }
1476                 lastEntry = entry;
1477                 entry = entry->chain;
1478         }
1479         if (entry == NULL)
1480         {
1481                 if (lastEntry->shader.name[0] != 0)
1482                 {
1483                         /* Add to chain */
1484                         q3shader_hash_entry_t* newEntry = (q3shader_hash_entry_t*)
1485                           Mem_ExpandableArray_AllocRecord (&q3shader_data->hash_entries);
1486
1487                         while (lastEntry->chain != NULL) lastEntry = lastEntry->chain;
1488                         lastEntry->chain = newEntry;
1489                         newEntry->chain = NULL;
1490                         lastEntry = newEntry;
1491                 }
1492                 /* else: head of chain, in hash entry array */
1493                 entry = lastEntry;
1494         }
1495         memcpy (&entry->shader, shader, sizeof (q3shaderinfo_t));
1496 }
1497
1498 extern cvar_t r_picmipworld;
1499 void Mod_LoadQ3Shaders(void)
1500 {
1501         int j;
1502         int fileindex;
1503         fssearch_t *search;
1504         char *f;
1505         const char *text;
1506         q3shaderinfo_t shader;
1507         q3shaderinfo_layer_t *layer;
1508         int numparameters;
1509         char parameter[TEXTURE_MAXFRAMES + 4][Q3PATHLENGTH];
1510
1511         Mod_FreeQ3Shaders();
1512
1513         q3shaders_mem = Mem_AllocPool("q3shaders", 0, NULL);
1514         q3shader_data = (q3shader_data_t*)Mem_Alloc (q3shaders_mem,
1515                 sizeof (q3shader_data_t));
1516         Mem_ExpandableArray_NewArray (&q3shader_data->hash_entries,
1517                 q3shaders_mem, sizeof (q3shader_hash_entry_t), 256);
1518         Mem_ExpandableArray_NewArray (&q3shader_data->char_ptrs,
1519                 q3shaders_mem, sizeof (char**), 256);
1520
1521         search = FS_Search("scripts/*.shader", true, false);
1522         if (!search)
1523                 return;
1524         for (fileindex = 0;fileindex < search->numfilenames;fileindex++)
1525         {
1526                 text = f = (char *)FS_LoadFile(search->filenames[fileindex], tempmempool, false, NULL);
1527                 if (!f)
1528                         continue;
1529                 while (COM_ParseToken_QuakeC(&text, false))
1530                 {
1531                         memset (&shader, 0, sizeof(shader));
1532                         shader.reflectmin = 0;
1533                         shader.reflectmax = 1;
1534                         shader.refractfactor = 1;
1535                         Vector4Set(shader.refractcolor4f, 1, 1, 1, 1);
1536                         shader.reflectfactor = 1;
1537                         Vector4Set(shader.reflectcolor4f, 1, 1, 1, 1);
1538                         shader.r_water_wateralpha = 1;
1539                         shader.specularscalemod = 1;
1540                         shader.specularpowermod = 1;
1541
1542                         strlcpy(shader.name, com_token, sizeof(shader.name));
1543                         if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1544                         {
1545                                 Con_Printf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[fileindex], com_token);
1546                                 break;
1547                         }
1548                         while (COM_ParseToken_QuakeC(&text, false))
1549                         {
1550                                 if (!strcasecmp(com_token, "}"))
1551                                         break;
1552                                 if (!strcasecmp(com_token, "{"))
1553                                 {
1554                                         static q3shaderinfo_layer_t dummy;
1555                                         if (shader.numlayers < Q3SHADER_MAXLAYERS)
1556                                         {
1557                                                 layer = shader.layers + shader.numlayers++;
1558                                         }
1559                                         else
1560                                         {
1561                                                 // parse and process it anyway, just don't store it (so a map $lightmap or such stuff still is found)
1562                                                 memset(&dummy, 0, sizeof(dummy));
1563                                                 layer = &dummy;
1564                                         }
1565                                         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1566                                         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1567                                         layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1568                                         layer->blendfunc[0] = GL_ONE;
1569                                         layer->blendfunc[1] = GL_ZERO;
1570                                         while (COM_ParseToken_QuakeC(&text, false))
1571                                         {
1572                                                 if (!strcasecmp(com_token, "}"))
1573                                                         break;
1574                                                 if (!strcasecmp(com_token, "\n"))
1575                                                         continue;
1576                                                 numparameters = 0;
1577                                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1578                                                 {
1579                                                         if (j < TEXTURE_MAXFRAMES + 4)
1580                                                         {
1581                                                                 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1582                                                                 numparameters = j + 1;
1583                                                         }
1584                                                         if (!COM_ParseToken_QuakeC(&text, true))
1585                                                                 break;
1586                                                 }
1587                                                 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1588                                                 //      parameter[j][0] = 0;
1589                                                 if (developer.integer >= 100)
1590                                                 {
1591                                                         Con_Printf("%s %i: ", shader.name, shader.numlayers - 1);
1592                                                         for (j = 0;j < numparameters;j++)
1593                                                                 Con_Printf(" %s", parameter[j]);
1594                                                         Con_Print("\n");
1595                                                 }
1596                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "blendfunc"))
1597                                                 {
1598                                                         if (numparameters == 2)
1599                                                         {
1600                                                                 if (!strcasecmp(parameter[1], "add"))
1601                                                                 {
1602                                                                         layer->blendfunc[0] = GL_ONE;
1603                                                                         layer->blendfunc[1] = GL_ONE;
1604                                                                 }
1605                                                                 else if (!strcasecmp(parameter[1], "filter"))
1606                                                                 {
1607                                                                         layer->blendfunc[0] = GL_DST_COLOR;
1608                                                                         layer->blendfunc[1] = GL_ZERO;
1609                                                                 }
1610                                                                 else if (!strcasecmp(parameter[1], "blend"))
1611                                                                 {
1612                                                                         layer->blendfunc[0] = GL_SRC_ALPHA;
1613                                                                         layer->blendfunc[1] = GL_ONE_MINUS_SRC_ALPHA;
1614                                                                 }
1615                                                         }
1616                                                         else if (numparameters == 3)
1617                                                         {
1618                                                                 int k;
1619                                                                 for (k = 0;k < 2;k++)
1620                                                                 {
1621                                                                         if (!strcasecmp(parameter[k+1], "GL_ONE"))
1622                                                                                 layer->blendfunc[k] = GL_ONE;
1623                                                                         else if (!strcasecmp(parameter[k+1], "GL_ZERO"))
1624                                                                                 layer->blendfunc[k] = GL_ZERO;
1625                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_COLOR"))
1626                                                                                 layer->blendfunc[k] = GL_SRC_COLOR;
1627                                                                         else if (!strcasecmp(parameter[k+1], "GL_SRC_ALPHA"))
1628                                                                                 layer->blendfunc[k] = GL_SRC_ALPHA;
1629                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_COLOR"))
1630                                                                                 layer->blendfunc[k] = GL_DST_COLOR;
1631                                                                         else if (!strcasecmp(parameter[k+1], "GL_DST_ALPHA"))
1632                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1633                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_COLOR"))
1634                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_COLOR;
1635                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_ALPHA"))
1636                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_SRC_ALPHA;
1637                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_COLOR"))
1638                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_COLOR;
1639                                                                         else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_ALPHA"))
1640                                                                                 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1641                                                                         else
1642                                                                                 layer->blendfunc[k] = GL_ONE; // default in case of parsing error
1643                                                                 }
1644                                                         }
1645                                                 }
1646                                                 if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
1647                                                         layer->alphatest = true;
1648                                                 if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
1649                                                 {
1650                                                         if (!strcasecmp(parameter[0], "clampmap"))
1651                                                                 layer->clampmap = true;
1652                                                         layer->numframes = 1;
1653                                                         layer->framerate = 1;
1654                                                         layer->texturename = (char**)Mem_ExpandableArray_AllocRecord (
1655                                                                 &q3shader_data->char_ptrs);
1656                                                         layer->texturename[0] = Mem_strdup (q3shaders_mem, parameter[1]);
1657                                                         if (!strcasecmp(parameter[1], "$lightmap"))
1658                                                                 shader.lighting = true;
1659                                                 }
1660                                                 else if (numparameters >= 3 && (!strcasecmp(parameter[0], "animmap") || !strcasecmp(parameter[0], "animclampmap")))
1661                                                 {
1662                                                         int i;
1663                                                         layer->numframes = min(numparameters - 2, TEXTURE_MAXFRAMES);
1664                                                         layer->framerate = atof(parameter[1]);
1665                                                         layer->texturename = (char **) Mem_Alloc (q3shaders_mem, sizeof (char*) * layer->numframes);
1666                                                         for (i = 0;i < layer->numframes;i++)
1667                                                                 layer->texturename[i] = Mem_strdup (q3shaders_mem, parameter[i + 2]);
1668                                                 }
1669                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "rgbgen"))
1670                                                 {
1671                                                         int i;
1672                                                         for (i = 0;i < numparameters - 2 && i < Q3RGBGEN_MAXPARMS;i++)
1673                                                                 layer->rgbgen.parms[i] = atof(parameter[i+2]);
1674                                                              if (!strcasecmp(parameter[1], "identity"))         layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1675                                                         else if (!strcasecmp(parameter[1], "const"))            layer->rgbgen.rgbgen = Q3RGBGEN_CONST;
1676                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->rgbgen.rgbgen = Q3RGBGEN_ENTITY;
1677                                                         else if (!strcasecmp(parameter[1], "exactvertex"))      layer->rgbgen.rgbgen = Q3RGBGEN_EXACTVERTEX;
1678                                                         else if (!strcasecmp(parameter[1], "identitylighting")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITYLIGHTING;
1679                                                         else if (!strcasecmp(parameter[1], "lightingdiffuse"))  layer->rgbgen.rgbgen = Q3RGBGEN_LIGHTINGDIFFUSE;
1680                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSENTITY;
1681                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSVERTEX;
1682                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->rgbgen.rgbgen = Q3RGBGEN_VERTEX;
1683                                                         else if (!strcasecmp(parameter[1], "wave"))
1684                                                         {
1685                                                                 layer->rgbgen.rgbgen = Q3RGBGEN_WAVE;
1686                                                                 layer->rgbgen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1687                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1688                                                                         layer->rgbgen.waveparms[i] = atof(parameter[i+3]);
1689                                                         }
1690                                                         else Con_DPrintf("%s parsing warning: unknown rgbgen %s\n", search->filenames[fileindex], parameter[1]);
1691                                                 }
1692                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphagen"))
1693                                                 {
1694                                                         int i;
1695                                                         for (i = 0;i < numparameters - 2 && i < Q3ALPHAGEN_MAXPARMS;i++)
1696                                                                 layer->alphagen.parms[i] = atof(parameter[i+2]);
1697                                                              if (!strcasecmp(parameter[1], "identity"))         layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1698                                                         else if (!strcasecmp(parameter[1], "const"))            layer->alphagen.alphagen = Q3ALPHAGEN_CONST;
1699                                                         else if (!strcasecmp(parameter[1], "entity"))           layer->alphagen.alphagen = Q3ALPHAGEN_ENTITY;
1700                                                         else if (!strcasecmp(parameter[1], "lightingspecular")) layer->alphagen.alphagen = Q3ALPHAGEN_LIGHTINGSPECULAR;
1701                                                         else if (!strcasecmp(parameter[1], "oneminusentity"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSENTITY;
1702                                                         else if (!strcasecmp(parameter[1], "oneminusvertex"))   layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSVERTEX;
1703                                                         else if (!strcasecmp(parameter[1], "portal"))           layer->alphagen.alphagen = Q3ALPHAGEN_PORTAL;
1704                                                         else if (!strcasecmp(parameter[1], "vertex"))           layer->alphagen.alphagen = Q3ALPHAGEN_VERTEX;
1705                                                         else if (!strcasecmp(parameter[1], "wave"))
1706                                                         {
1707                                                                 layer->alphagen.alphagen = Q3ALPHAGEN_WAVE;
1708                                                                 layer->alphagen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1709                                                                 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1710                                                                         layer->alphagen.waveparms[i] = atof(parameter[i+3]);
1711                                                         }
1712                                                         else Con_DPrintf("%s parsing warning: unknown alphagen %s\n", search->filenames[fileindex], parameter[1]);
1713                                                 }
1714                                                 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "texgen") || !strcasecmp(parameter[0], "tcgen")))
1715                                                 {
1716                                                         int i;
1717                                                         // observed values: tcgen environment
1718                                                         // no other values have been observed in real shaders
1719                                                         for (i = 0;i < numparameters - 2 && i < Q3TCGEN_MAXPARMS;i++)
1720                                                                 layer->tcgen.parms[i] = atof(parameter[i+2]);
1721                                                              if (!strcasecmp(parameter[1], "base"))        layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1722                                                         else if (!strcasecmp(parameter[1], "texture"))     layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1723                                                         else if (!strcasecmp(parameter[1], "environment")) layer->tcgen.tcgen = Q3TCGEN_ENVIRONMENT;
1724                                                         else if (!strcasecmp(parameter[1], "lightmap"))    layer->tcgen.tcgen = Q3TCGEN_LIGHTMAP;
1725                                                         else if (!strcasecmp(parameter[1], "vector"))      layer->tcgen.tcgen = Q3TCGEN_VECTOR;
1726                                                         else Con_DPrintf("%s parsing warning: unknown tcgen mode %s\n", search->filenames[fileindex], parameter[1]);
1727                                                 }
1728                                                 else if (numparameters >= 2 && !strcasecmp(parameter[0], "tcmod"))
1729                                                 {
1730                                                         int i, tcmodindex;
1731                                                         // observed values:
1732                                                         // tcmod rotate #
1733                                                         // tcmod scale # #
1734                                                         // tcmod scroll # #
1735                                                         // tcmod stretch sin # # # #
1736                                                         // tcmod stretch triangle # # # #
1737                                                         // tcmod transform # # # # # #
1738                                                         // tcmod turb # # # #
1739                                                         // tcmod turb sin # # # #  (this is bogus)
1740                                                         // no other values have been observed in real shaders
1741                                                         for (tcmodindex = 0;tcmodindex < Q3MAXTCMODS;tcmodindex++)
1742                                                                 if (!layer->tcmods[tcmodindex].tcmod)
1743                                                                         break;
1744                                                         if (tcmodindex < Q3MAXTCMODS)
1745                                                         {
1746                                                                 for (i = 0;i < numparameters - 2 && i < Q3TCMOD_MAXPARMS;i++)
1747                                                                         layer->tcmods[tcmodindex].parms[i] = atof(parameter[i+2]);
1748                                                                          if (!strcasecmp(parameter[1], "entitytranslate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ENTITYTRANSLATE;
1749                                                                 else if (!strcasecmp(parameter[1], "rotate"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ROTATE;
1750                                                                 else if (!strcasecmp(parameter[1], "scale"))           layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCALE;
1751                                                                 else if (!strcasecmp(parameter[1], "scroll"))          layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCROLL;
1752                                                                 else if (!strcasecmp(parameter[1], "page"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_PAGE;
1753                                                                 else if (!strcasecmp(parameter[1], "stretch"))
1754                                                                 {
1755                                                                         layer->tcmods[tcmodindex].tcmod = Q3TCMOD_STRETCH;
1756                                                                         layer->tcmods[tcmodindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1757                                                                         for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1758                                                                                 layer->tcmods[tcmodindex].waveparms[i] = atof(parameter[i+3]);
1759                                                                 }
1760                                                                 else if (!strcasecmp(parameter[1], "transform"))       layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TRANSFORM;
1761                                                                 else if (!strcasecmp(parameter[1], "turb"))            layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TURBULENT;
1762                                                                 else Con_DPrintf("%s parsing warning: unknown tcmod mode %s\n", search->filenames[fileindex], parameter[1]);
1763                                                         }
1764                                                         else
1765                                                                 Con_DPrintf("%s parsing warning: too many tcmods on one layer\n", search->filenames[fileindex]);
1766                                                 }
1767                                                 // break out a level if it was a closing brace (not using the character here to not confuse vim)
1768                                                 if (!strcasecmp(com_token, "}"))
1769                                                         break;
1770                                         }
1771                                         if (layer->rgbgen.rgbgen == Q3RGBGEN_LIGHTINGDIFFUSE || layer->rgbgen.rgbgen == Q3RGBGEN_VERTEX)
1772                                                 shader.lighting = true;
1773                                         if (layer->alphagen.alphagen == Q3ALPHAGEN_VERTEX)
1774                                         {
1775                                                 if (layer == shader.layers + 0)
1776                                                 {
1777                                                         // vertex controlled transparency
1778                                                         shader.vertexalpha = true;
1779                                                 }
1780                                                 else
1781                                                 {
1782                                                         // multilayer terrain shader or similar
1783                                                         shader.textureblendalpha = true;
1784                                                 }
1785                                         }
1786                                         layer->texflags = TEXF_ALPHA | TEXF_PRECACHE;
1787                                         if (!(shader.surfaceparms & Q3SURFACEPARM_NOMIPMAPS))
1788                                                 layer->texflags |= TEXF_MIPMAP;
1789                                         if (!(shader.textureflags & Q3TEXTUREFLAG_NOPICMIP))
1790                                                 layer->texflags |= TEXF_PICMIP | TEXF_COMPRESS;
1791                                         if (layer->clampmap)
1792                                                 layer->texflags |= TEXF_CLAMP;
1793                                         continue;
1794                                 }
1795                                 numparameters = 0;
1796                                 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1797                                 {
1798                                         if (j < TEXTURE_MAXFRAMES + 4)
1799                                         {
1800                                                 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1801                                                 numparameters = j + 1;
1802                                         }
1803                                         if (!COM_ParseToken_QuakeC(&text, true))
1804                                                 break;
1805                                 }
1806                                 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1807                                 //      parameter[j][0] = 0;
1808                                 if (fileindex == 0 && !strcasecmp(com_token, "}"))
1809                                         break;
1810                                 if (developer.integer >= 100)
1811                                 {
1812                                         Con_Printf("%s: ", shader.name);
1813                                         for (j = 0;j < numparameters;j++)
1814                                                 Con_Printf(" %s", parameter[j]);
1815                                         Con_Print("\n");
1816                                 }
1817                                 if (numparameters < 1)
1818                                         continue;
1819                                 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
1820                                 {
1821                                         if (!strcasecmp(parameter[1], "alphashadow"))
1822                                                 shader.surfaceparms |= Q3SURFACEPARM_ALPHASHADOW;
1823                                         else if (!strcasecmp(parameter[1], "areaportal"))
1824                                                 shader.surfaceparms |= Q3SURFACEPARM_AREAPORTAL;
1825                                         else if (!strcasecmp(parameter[1], "botclip"))
1826                                                 shader.surfaceparms |= Q3SURFACEPARM_BOTCLIP;
1827                                         else if (!strcasecmp(parameter[1], "clusterportal"))
1828                                                 shader.surfaceparms |= Q3SURFACEPARM_CLUSTERPORTAL;
1829                                         else if (!strcasecmp(parameter[1], "detail"))
1830                                                 shader.surfaceparms |= Q3SURFACEPARM_DETAIL;
1831                                         else if (!strcasecmp(parameter[1], "donotenter"))
1832                                                 shader.surfaceparms |= Q3SURFACEPARM_DONOTENTER;
1833                                         else if (!strcasecmp(parameter[1], "dust"))
1834                                                 shader.surfaceparms |= Q3SURFACEPARM_DUST;
1835                                         else if (!strcasecmp(parameter[1], "hint"))
1836                                                 shader.surfaceparms |= Q3SURFACEPARM_HINT;
1837                                         else if (!strcasecmp(parameter[1], "fog"))
1838                                                 shader.surfaceparms |= Q3SURFACEPARM_FOG;
1839                                         else if (!strcasecmp(parameter[1], "lava"))
1840                                                 shader.surfaceparms |= Q3SURFACEPARM_LAVA;
1841                                         else if (!strcasecmp(parameter[1], "lightfilter"))
1842                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTFILTER;
1843                                         else if (!strcasecmp(parameter[1], "lightgrid"))
1844                                                 shader.surfaceparms |= Q3SURFACEPARM_LIGHTGRID;
1845                                         else if (!strcasecmp(parameter[1], "metalsteps"))
1846                                                 shader.surfaceparms |= Q3SURFACEPARM_METALSTEPS;
1847                                         else if (!strcasecmp(parameter[1], "nodamage"))
1848                                                 shader.surfaceparms |= Q3SURFACEPARM_NODAMAGE;
1849                                         else if (!strcasecmp(parameter[1], "nodlight"))
1850                                                 shader.surfaceparms |= Q3SURFACEPARM_NODLIGHT;
1851                                         else if (!strcasecmp(parameter[1], "nodraw"))
1852                                                 shader.surfaceparms |= Q3SURFACEPARM_NODRAW;
1853                                         else if (!strcasecmp(parameter[1], "nodrop"))
1854                                                 shader.surfaceparms |= Q3SURFACEPARM_NODROP;
1855                                         else if (!strcasecmp(parameter[1], "noimpact"))
1856                                                 shader.surfaceparms |= Q3SURFACEPARM_NOIMPACT;
1857                                         else if (!strcasecmp(parameter[1], "nolightmap"))
1858                                                 shader.surfaceparms |= Q3SURFACEPARM_NOLIGHTMAP;
1859                                         else if (!strcasecmp(parameter[1], "nomarks"))
1860                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMARKS;
1861                                         else if (!strcasecmp(parameter[1], "nomipmaps"))
1862                                                 shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1863                                         else if (!strcasecmp(parameter[1], "nonsolid"))
1864                                                 shader.surfaceparms |= Q3SURFACEPARM_NONSOLID;
1865                                         else if (!strcasecmp(parameter[1], "origin"))
1866                                                 shader.surfaceparms |= Q3SURFACEPARM_ORIGIN;
1867                                         else if (!strcasecmp(parameter[1], "playerclip"))
1868                                                 shader.surfaceparms |= Q3SURFACEPARM_PLAYERCLIP;
1869                                         else if (!strcasecmp(parameter[1], "sky"))
1870                                                 shader.surfaceparms |= Q3SURFACEPARM_SKY;
1871                                         else if (!strcasecmp(parameter[1], "slick"))
1872                                                 shader.surfaceparms |= Q3SURFACEPARM_SLICK;
1873                                         else if (!strcasecmp(parameter[1], "slime"))
1874                                                 shader.surfaceparms |= Q3SURFACEPARM_SLIME;
1875                                         else if (!strcasecmp(parameter[1], "structural"))
1876                                                 shader.surfaceparms |= Q3SURFACEPARM_STRUCTURAL;
1877                                         else if (!strcasecmp(parameter[1], "trans"))
1878                                                 shader.surfaceparms |= Q3SURFACEPARM_TRANS;
1879                                         else if (!strcasecmp(parameter[1], "water"))
1880                                                 shader.surfaceparms |= Q3SURFACEPARM_WATER;
1881                                         else if (!strcasecmp(parameter[1], "pointlight"))
1882                                                 shader.surfaceparms |= Q3SURFACEPARM_POINTLIGHT;
1883                                         else if (!strcasecmp(parameter[1], "antiportal"))
1884                                                 shader.surfaceparms |= Q3SURFACEPARM_ANTIPORTAL;
1885                                         else
1886                                                 Con_DPrintf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[fileindex], parameter[1]);
1887                                 }
1888                                 else if (!strcasecmp(parameter[0], "dpshadow"))
1889                                         shader.dpshadow = true;
1890                                 else if (!strcasecmp(parameter[0], "dpnoshadow"))
1891                                         shader.dpnoshadow = true;
1892                                 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
1893                                 {
1894                                         // some q3 skies don't have the sky parm set
1895                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
1896                                         strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
1897                                 }
1898                                 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
1899                                 {
1900                                         // some q3 skies don't have the sky parm set
1901                                         shader.surfaceparms |= Q3SURFACEPARM_SKY;
1902                                         if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
1903                                                 strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
1904                                 }
1905                                 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
1906                                 {
1907                                         if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
1908                                                 shader.textureflags |= Q3TEXTUREFLAG_TWOSIDED;
1909                                 }
1910                                 else if (!strcasecmp(parameter[0], "nomipmaps"))
1911                                         shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1912                                 else if (!strcasecmp(parameter[0], "nopicmip"))
1913                                         shader.textureflags |= Q3TEXTUREFLAG_NOPICMIP;
1914                                 else if (!strcasecmp(parameter[0], "polygonoffset"))
1915                                         shader.textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
1916                                 else if (!strcasecmp(parameter[0], "dp_refract") && numparameters >= 5)
1917                                 {
1918                                         shader.textureflags |= Q3TEXTUREFLAG_REFRACTION;
1919                                         shader.refractfactor = atof(parameter[1]);
1920                                         Vector4Set(shader.refractcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), 1);
1921                                 }
1922                                 else if (!strcasecmp(parameter[0], "dp_reflect") && numparameters >= 6)
1923                                 {
1924                                         shader.textureflags |= Q3TEXTUREFLAG_REFLECTION;
1925                                         shader.reflectfactor = atof(parameter[1]);
1926                                         Vector4Set(shader.reflectcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), atof(parameter[5]));
1927                                 }
1928                                 else if (!strcasecmp(parameter[0], "dp_water") && numparameters >= 12)
1929                                 {
1930                                         shader.textureflags |= Q3TEXTUREFLAG_WATERSHADER;
1931                                         shader.reflectmin = atof(parameter[1]);
1932                                         shader.reflectmax = atof(parameter[2]);
1933                                         shader.refractfactor = atof(parameter[3]);
1934                                         shader.reflectfactor = atof(parameter[4]);
1935                                         Vector4Set(shader.refractcolor4f, atof(parameter[5]), atof(parameter[6]), atof(parameter[7]), 1);
1936                                         Vector4Set(shader.reflectcolor4f, atof(parameter[8]), atof(parameter[9]), atof(parameter[10]), 1);
1937                                         shader.r_water_wateralpha = atof(parameter[11]);
1938                                 }
1939                                 else if (!strcasecmp(parameter[0], "dp_glossintensitymod") && numparameters >= 2)
1940                                 {
1941                                         shader.specularscalemod = atof(parameter[1]);
1942                                 }
1943                                 else if (!strcasecmp(parameter[0], "dp_glossexponentmod") && numparameters >= 2)
1944                                 {
1945                                         shader.specularpowermod = atof(parameter[1]);
1946                                 }
1947                                 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
1948                                 {
1949                                         int i, deformindex;
1950                                         for (deformindex = 0;deformindex < Q3MAXDEFORMS;deformindex++)
1951                                                 if (!shader.deforms[deformindex].deform)
1952                                                         break;
1953                                         if (deformindex < Q3MAXDEFORMS)
1954                                         {
1955                                                 for (i = 0;i < numparameters - 2 && i < Q3DEFORM_MAXPARMS;i++)
1956                                                         shader.deforms[deformindex].parms[i] = atof(parameter[i+2]);
1957                                                      if (!strcasecmp(parameter[1], "projectionshadow")) shader.deforms[deformindex].deform = Q3DEFORM_PROJECTIONSHADOW;
1958                                                 else if (!strcasecmp(parameter[1], "autosprite"      )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE;
1959                                                 else if (!strcasecmp(parameter[1], "autosprite2"     )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE2;
1960                                                 else if (!strcasecmp(parameter[1], "text0"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT0;
1961                                                 else if (!strcasecmp(parameter[1], "text1"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT1;
1962                                                 else if (!strcasecmp(parameter[1], "text2"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT2;
1963                                                 else if (!strcasecmp(parameter[1], "text3"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT3;
1964                                                 else if (!strcasecmp(parameter[1], "text4"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT4;
1965                                                 else if (!strcasecmp(parameter[1], "text5"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT5;
1966                                                 else if (!strcasecmp(parameter[1], "text6"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT6;
1967                                                 else if (!strcasecmp(parameter[1], "text7"           )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT7;
1968                                                 else if (!strcasecmp(parameter[1], "bulge"           )) shader.deforms[deformindex].deform = Q3DEFORM_BULGE;
1969                                                 else if (!strcasecmp(parameter[1], "normal"          )) shader.deforms[deformindex].deform = Q3DEFORM_NORMAL;
1970                                                 else if (!strcasecmp(parameter[1], "wave"            ))
1971                                                 {
1972                                                         shader.deforms[deformindex].deform = Q3DEFORM_WAVE;
1973                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[3]);
1974                                                         for (i = 0;i < numparameters - 4 && i < Q3WAVEPARMS;i++)
1975                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+4]);
1976                                                 }
1977                                                 else if (!strcasecmp(parameter[1], "move"            ))
1978                                                 {
1979                                                         shader.deforms[deformindex].deform = Q3DEFORM_MOVE;
1980                                                         shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[5]);
1981                                                         for (i = 0;i < numparameters - 6 && i < Q3WAVEPARMS;i++)
1982                                                                 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+6]);
1983                                                 }
1984                                         }
1985                                 }
1986                         }
1987                         // pick the primary layer to render with
1988                         if (shader.numlayers)
1989                         {
1990                                 shader.backgroundlayer = -1;
1991                                 shader.primarylayer = 0;
1992                                 // if lightmap comes first this is definitely an ordinary texture
1993                                 // if the first two layers have the correct blendfuncs and use vertex alpha, it is a blended terrain shader
1994                                 if ((shader.layers[shader.primarylayer].texturename != NULL)
1995                                   && !strcasecmp(shader.layers[shader.primarylayer].texturename[0], "$lightmap"))
1996                                 {
1997                                         shader.backgroundlayer = -1;
1998                                         shader.primarylayer = 1;
1999                                 }
2000                                 else if (shader.numlayers >= 2
2001                                 &&   shader.layers[1].alphagen.alphagen == Q3ALPHAGEN_VERTEX
2002                                 &&  (shader.layers[0].blendfunc[0] == GL_ONE       && shader.layers[0].blendfunc[1] == GL_ZERO                && !shader.layers[0].alphatest)
2003                                 && ((shader.layers[1].blendfunc[0] == GL_SRC_ALPHA && shader.layers[1].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2004                                 ||  (shader.layers[1].blendfunc[0] == GL_ONE       && shader.layers[1].blendfunc[1] == GL_ZERO                &&  shader.layers[1].alphatest)))
2005                                 {
2006                                         // terrain blending or other effects
2007                                         shader.backgroundlayer = 0;
2008                                         shader.primarylayer = 1;
2009                                 }
2010                         }
2011                         // fix up multiple reflection types
2012                         if(shader.textureflags & Q3TEXTUREFLAG_WATERSHADER)
2013                                 shader.textureflags &= ~(Q3TEXTUREFLAG_REFRACTION | Q3TEXTUREFLAG_REFLECTION);
2014
2015                         Q3Shader_AddToHash (&shader);
2016                 }
2017                 Mem_Free(f);
2018         }
2019         FS_FreeSearch(search);
2020 }
2021
2022 q3shaderinfo_t *Mod_LookupQ3Shader(const char *name)
2023 {
2024         unsigned short hash;
2025         q3shader_hash_entry_t* entry;
2026         if (!q3shaders_mem)
2027                 Mod_LoadQ3Shaders();
2028         hash = CRC_Block_CaseInsensitive ((const unsigned char *)name, strlen (name));
2029         entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
2030         while (entry != NULL)
2031         {
2032                 if (strcasecmp (entry->shader.name, name) == 0)
2033                         return &entry->shader;
2034                 entry = entry->chain;
2035         }
2036         return NULL;
2037 }
2038
2039 qboolean Mod_LoadTextureFromQ3Shader(texture_t *texture, const char *name, qboolean warnmissing, qboolean fallback, int defaulttexflags)
2040 {
2041         int j;
2042         int texflagsmask;
2043         qboolean success = true;
2044         q3shaderinfo_t *shader;
2045         if (!name)
2046                 name = "";
2047         strlcpy(texture->name, name, sizeof(texture->name));
2048         shader = name[0] ? Mod_LookupQ3Shader(name) : NULL;
2049
2050         texflagsmask = ~0;
2051         if(!(defaulttexflags & TEXF_PICMIP))
2052                 texflagsmask &= ~TEXF_PICMIP;
2053         if(!(defaulttexflags & TEXF_COMPRESS))
2054                 texflagsmask &= ~TEXF_COMPRESS;
2055         texture->specularscalemod = 1; // unless later loaded from the shader
2056         texture->specularpowermod = 1; // unless later loaded from the shader
2057
2058         if (shader)
2059         {
2060                 if (developer_loading.integer)
2061                         Con_Printf("%s: loaded shader for %s\n", loadmodel->name, name);
2062                 texture->surfaceparms = shader->surfaceparms;
2063
2064                 // allow disabling of picmip or compression by defaulttexflags
2065                 texture->textureflags = shader->textureflags & texflagsmask;
2066
2067                 if (shader->surfaceparms & Q3SURFACEPARM_SKY)
2068                 {
2069                         texture->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2070                         if (shader->skyboxname[0])
2071                         {
2072                                 // quake3 seems to append a _ to the skybox name, so this must do so as well
2073                                 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", shader->skyboxname);
2074                         }
2075                 }
2076                 else if ((texture->surfaceflags & Q3SURFACEFLAG_NODRAW) || shader->numlayers == 0)
2077                         texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2078                 else
2079                         texture->basematerialflags = MATERIALFLAG_WALL;
2080
2081                 if (shader->layers[0].alphatest)
2082                         texture->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
2083                 if (shader->textureflags & Q3TEXTUREFLAG_TWOSIDED)
2084                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
2085                 if (shader->textureflags & Q3TEXTUREFLAG_POLYGONOFFSET)
2086                         texture->biaspolygonoffset -= 2;
2087                 if (shader->textureflags & Q3TEXTUREFLAG_REFRACTION)
2088                         texture->basematerialflags |= MATERIALFLAG_REFRACTION;
2089                 if (shader->textureflags & Q3TEXTUREFLAG_REFLECTION)
2090                         texture->basematerialflags |= MATERIALFLAG_REFLECTION;
2091                 if (shader->textureflags & Q3TEXTUREFLAG_WATERSHADER)
2092                         texture->basematerialflags |= MATERIALFLAG_WATERSHADER;
2093                 texture->customblendfunc[0] = GL_ONE;
2094                 texture->customblendfunc[1] = GL_ZERO;
2095                 if (shader->numlayers > 0)
2096                 {
2097                         texture->customblendfunc[0] = shader->layers[0].blendfunc[0];
2098                         texture->customblendfunc[1] = shader->layers[0].blendfunc[1];
2099 /*
2100 Q3 shader blendfuncs actually used in the game (* = supported by DP)
2101 * additive               GL_ONE GL_ONE
2102 additive weird         GL_ONE GL_SRC_ALPHA
2103 additive weird 2       GL_ONE GL_ONE_MINUS_SRC_ALPHA
2104 * alpha                  GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
2105 alpha inverse          GL_ONE_MINUS_SRC_ALPHA GL_SRC_ALPHA
2106 brighten               GL_DST_COLOR GL_ONE
2107 brighten               GL_ONE GL_SRC_COLOR
2108 brighten weird         GL_DST_COLOR GL_ONE_MINUS_DST_ALPHA
2109 brighten weird 2       GL_DST_COLOR GL_SRC_ALPHA
2110 * modulate               GL_DST_COLOR GL_ZERO
2111 * modulate               GL_ZERO GL_SRC_COLOR
2112 modulate inverse       GL_ZERO GL_ONE_MINUS_SRC_COLOR
2113 modulate inverse alpha GL_ZERO GL_SRC_ALPHA
2114 modulate weird inverse GL_ONE_MINUS_DST_COLOR GL_ZERO
2115 * modulate x2            GL_DST_COLOR GL_SRC_COLOR
2116 * no blend               GL_ONE GL_ZERO
2117 nothing                GL_ZERO GL_ONE
2118 */
2119                         // if not opaque, figure out what blendfunc to use
2120                         if (shader->layers[0].blendfunc[0] != GL_ONE || shader->layers[0].blendfunc[1] != GL_ZERO)
2121                         {
2122                                 if (shader->layers[0].blendfunc[0] == GL_ONE && shader->layers[0].blendfunc[1] == GL_ONE)
2123                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2124                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE)
2125                                         texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2126                                 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2127                                         texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2128                                 else
2129                                         texture->basematerialflags |= MATERIALFLAG_CUSTOMBLEND | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2130                         }
2131                 }
2132                 if (!shader->lighting)
2133                         texture->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
2134                 if (shader->primarylayer >= 0)
2135                 {
2136                         q3shaderinfo_layer_t* primarylayer = shader->layers + shader->primarylayer;
2137                         // copy over many primarylayer parameters
2138                         texture->rgbgen = primarylayer->rgbgen;
2139                         texture->alphagen = primarylayer->alphagen;
2140                         texture->tcgen = primarylayer->tcgen;
2141                         memcpy(texture->tcmods, primarylayer->tcmods, sizeof(texture->tcmods));
2142                         // load the textures
2143                         texture->numskinframes = primarylayer->numframes;
2144                         texture->skinframerate = primarylayer->framerate;
2145                         for (j = 0;j < primarylayer->numframes;j++)
2146                         {
2147                                 if(cls.state == ca_dedicated)
2148                                 {
2149                                         texture->skinframes[j] = NULL;
2150                                 }
2151                                 else if (!(texture->skinframes[j] = R_SkinFrame_LoadExternal(primarylayer->texturename[j], primarylayer->texflags & texflagsmask, false)))
2152                                 {
2153                                         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);
2154                                         texture->skinframes[j] = R_SkinFrame_LoadMissing();
2155                                 }
2156                         }
2157                 }
2158                 if (shader->backgroundlayer >= 0)
2159                 {
2160                         q3shaderinfo_layer_t* backgroundlayer = shader->layers + shader->backgroundlayer;
2161                         // copy over one secondarylayer parameter
2162                         memcpy(texture->backgroundtcmods, backgroundlayer->tcmods, sizeof(texture->backgroundtcmods));
2163                         // load the textures
2164                         texture->backgroundnumskinframes = backgroundlayer->numframes;
2165                         texture->backgroundskinframerate = backgroundlayer->framerate;
2166                         for (j = 0;j < backgroundlayer->numframes;j++)
2167                         {
2168                                 if(cls.state == ca_dedicated)
2169                                 {
2170                                         texture->skinframes[j] = NULL;
2171                                 }
2172                                 else if (!(texture->backgroundskinframes[j] = R_SkinFrame_LoadExternal(backgroundlayer->texturename[j], backgroundlayer->texflags & texflagsmask, false)))
2173                                 {
2174                                         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);
2175                                         texture->backgroundskinframes[j] = R_SkinFrame_LoadMissing();
2176                                 }
2177                         }
2178                 }
2179                 if (shader->dpshadow)
2180                         texture->basematerialflags &= ~MATERIALFLAG_NOSHADOW;
2181                 if (shader->dpnoshadow)
2182                         texture->basematerialflags |= MATERIALFLAG_NOSHADOW;
2183                 memcpy(texture->deforms, shader->deforms, sizeof(texture->deforms));
2184                 texture->reflectmin = shader->reflectmin;
2185                 texture->reflectmax = shader->reflectmax;
2186                 texture->refractfactor = shader->refractfactor;
2187                 Vector4Copy(shader->refractcolor4f, texture->refractcolor4f);
2188                 texture->reflectfactor = shader->reflectfactor;
2189                 Vector4Copy(shader->reflectcolor4f, texture->reflectcolor4f);
2190                 texture->r_water_wateralpha = shader->r_water_wateralpha;
2191                 texture->specularscalemod = shader->specularscalemod;
2192                 texture->specularpowermod = shader->specularpowermod;
2193         }
2194         else if (!strcmp(texture->name, "noshader") || !texture->name[0])
2195         {
2196                 if (developer.integer >= 100)
2197                         Con_Printf("^1%s:^7 using fallback noshader material for ^3\"%s\"\n", loadmodel->name, name);
2198                 texture->surfaceparms = 0;
2199         }
2200         else if (!strcmp(texture->name, "common/nodraw") || !strcmp(texture->name, "textures/common/nodraw"))
2201         {
2202                 if (developer.integer >= 100)
2203                         Con_Printf("^1%s:^7 using fallback nodraw material for ^3\"%s\"\n", loadmodel->name, name);
2204                 texture->surfaceparms = 0;
2205                 texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2206         }
2207         else
2208         {
2209                 if (developer.integer >= 100)
2210                         Con_Printf("^1%s:^7 No shader found for texture ^3\"%s\"\n", loadmodel->name, texture->name);
2211                 texture->surfaceparms = 0;
2212                 if (texture->surfaceflags & Q3SURFACEFLAG_NODRAW)
2213                         texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2214                 else if (texture->surfaceflags & Q3SURFACEFLAG_SKY)
2215                         texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2216                 else
2217                         texture->basematerialflags |= MATERIALFLAG_WALL;
2218                 texture->numskinframes = 1;
2219                 if(cls.state == ca_dedicated)
2220                 {
2221                         texture->skinframes[0] = NULL;
2222                 }
2223                 else
2224                 {
2225                         if (fallback)
2226                         {
2227                                 qboolean has_alpha;
2228                                 if ((texture->skinframes[0] = R_SkinFrame_LoadExternal_CheckAlpha(texture->name, defaulttexflags, false, &has_alpha)))
2229                                 {
2230                                         if(has_alpha && (defaulttexflags & TEXF_ALPHA))
2231                                                 texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2232                                 }
2233                                 else
2234                                         success = false;
2235                         }
2236                         else
2237                                 success = false;
2238                         if (!success && warnmissing)
2239                                 Con_Printf("^1%s:^7 could not load texture ^3\"%s\"\n", loadmodel->name, texture->name);
2240                 }
2241         }
2242         // init the animation variables
2243         texture->currentframe = texture;
2244         if (texture->numskinframes < 1)
2245                 texture->numskinframes = 1;
2246         if (!texture->skinframes[0])
2247                 texture->skinframes[0] = R_SkinFrame_LoadMissing();
2248         texture->currentskinframe = texture->skinframes[0];
2249         texture->backgroundcurrentskinframe = texture->backgroundskinframes[0];
2250         return success;
2251 }
2252
2253 skinfile_t *Mod_LoadSkinFiles(void)
2254 {
2255         int i, words, line, wordsoverflow;
2256         char *text;
2257         const char *data;
2258         skinfile_t *skinfile = NULL, *first = NULL;
2259         skinfileitem_t *skinfileitem;
2260         char word[10][MAX_QPATH];
2261
2262 /*
2263 sample file:
2264 U_bodyBox,models/players/Legoman/BikerA2.tga
2265 U_RArm,models/players/Legoman/BikerA1.tga
2266 U_LArm,models/players/Legoman/BikerA1.tga
2267 U_armor,common/nodraw
2268 U_sword,common/nodraw
2269 U_shield,common/nodraw
2270 U_homb,common/nodraw
2271 U_backpack,common/nodraw
2272 U_colcha,common/nodraw
2273 tag_head,
2274 tag_weapon,
2275 tag_torso,
2276 */
2277         memset(word, 0, sizeof(word));
2278         for (i = 0;i < 256 && (data = text = (char *)FS_LoadFile(va("%s_%i.skin", loadmodel->name, i), tempmempool, true, NULL));i++)
2279         {
2280                 // If it's the first file we parse
2281                 if (skinfile == NULL)
2282                 {
2283                         skinfile = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2284                         first = skinfile;
2285                 }
2286                 else
2287                 {
2288                         skinfile->next = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2289                         skinfile = skinfile->next;
2290                 }
2291                 skinfile->next = NULL;
2292
2293                 for(line = 0;;line++)
2294                 {
2295                         // parse line
2296                         if (!COM_ParseToken_QuakeC(&data, true))
2297                                 break;
2298                         if (!strcmp(com_token, "\n"))
2299                                 continue;
2300                         words = 0;
2301                         wordsoverflow = false;
2302                         do
2303                         {
2304                                 if (words < 10)
2305                                         strlcpy(word[words++], com_token, sizeof (word[0]));
2306                                 else
2307                                         wordsoverflow = true;
2308                         }
2309                         while (COM_ParseToken_QuakeC(&data, true) && strcmp(com_token, "\n"));
2310                         if (wordsoverflow)
2311                         {
2312                                 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);
2313                                 continue;
2314                         }
2315                         // words is always >= 1
2316                         if (!strcmp(word[0], "replace"))
2317                         {
2318                                 if (words == 3)
2319                                 {
2320                                         if (developer_loading.integer)
2321                                                 Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[1], word[2]);
2322                                         skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2323                                         skinfileitem->next = skinfile->items;
2324                                         skinfile->items = skinfileitem;
2325                                         strlcpy (skinfileitem->name, word[1], sizeof (skinfileitem->name));
2326                                         strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2327                                 }
2328                                 else
2329                                         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]);
2330                         }
2331                         else if (words >= 2 && !strncmp(word[0], "tag_", 4))
2332                         {
2333                                 // tag name, like "tag_weapon,"
2334                                 // not used for anything (not even in Quake3)
2335                         }
2336                         else if (words >= 2 && !strcmp(word[1], ","))
2337                         {
2338                                 // mesh shader name, like "U_RArm,models/players/Legoman/BikerA1.tga"
2339                                 if (developer_loading.integer)
2340                                         Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[0], word[2]);
2341                                 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2342                                 skinfileitem->next = skinfile->items;
2343                                 skinfile->items = skinfileitem;
2344                                 strlcpy (skinfileitem->name, word[0], sizeof (skinfileitem->name));
2345                                 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2346                         }
2347                         else
2348                                 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);
2349                 }
2350                 Mem_Free(text);
2351         }
2352         if (i)
2353                 loadmodel->numskins = i;
2354         return first;
2355 }
2356
2357 void Mod_FreeSkinFiles(skinfile_t *skinfile)
2358 {
2359         skinfile_t *next;
2360         skinfileitem_t *skinfileitem, *nextitem;
2361         for (;skinfile;skinfile = next)
2362         {
2363                 next = skinfile->next;
2364                 for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = nextitem)
2365                 {
2366                         nextitem = skinfileitem->next;
2367                         Mem_Free(skinfileitem);
2368                 }
2369                 Mem_Free(skinfile);
2370         }
2371 }
2372
2373 int Mod_CountSkinFiles(skinfile_t *skinfile)
2374 {
2375         int i;
2376         for (i = 0;skinfile;skinfile = skinfile->next, i++);
2377         return i;
2378 }
2379
2380 void Mod_SnapVertices(int numcomponents, int numvertices, float *vertices, float snap)
2381 {
2382         int i;
2383         double isnap = 1.0 / snap;
2384         for (i = 0;i < numvertices*numcomponents;i++)
2385                 vertices[i] = floor(vertices[i]*isnap)*snap;
2386 }
2387
2388 int Mod_RemoveDegenerateTriangles(int numtriangles, const int *inelement3i, int *outelement3i, const float *vertex3f)
2389 {
2390         int i, outtriangles;
2391         float edgedir1[3], edgedir2[3], temp[3];
2392         // a degenerate triangle is one with no width (thickness, surface area)
2393         // these are characterized by having all 3 points colinear (along a line)
2394         // or having two points identical
2395         // the simplest check is to calculate the triangle's area
2396         for (i = 0, outtriangles = 0;i < numtriangles;i++, inelement3i += 3)
2397         {
2398                 // calculate first edge
2399                 VectorSubtract(vertex3f + inelement3i[1] * 3, vertex3f + inelement3i[0] * 3, edgedir1);
2400                 VectorSubtract(vertex3f + inelement3i[2] * 3, vertex3f + inelement3i[0] * 3, edgedir2);
2401                 CrossProduct(edgedir1, edgedir2, temp);
2402                 if (VectorLength2(temp) < 0.001f)
2403                         continue; // degenerate triangle (no area)
2404                 // valid triangle (has area)
2405                 VectorCopy(inelement3i, outelement3i);
2406                 outelement3i += 3;
2407                 outtriangles++;
2408         }
2409         return outtriangles;
2410 }
2411
2412 void Mod_VertexRangeFromElements(int numelements, const int *elements, int *firstvertexpointer, int *lastvertexpointer)
2413 {
2414         int i, e;
2415         int firstvertex, lastvertex;
2416         if (numelements > 0 && elements)
2417         {
2418                 firstvertex = lastvertex = elements[0];
2419                 for (i = 1;i < numelements;i++)
2420                 {
2421                         e = elements[i];
2422                         firstvertex = min(firstvertex, e);
2423                         lastvertex = max(lastvertex, e);
2424                 }
2425         }
2426         else
2427                 firstvertex = lastvertex = 0;
2428         if (firstvertexpointer)
2429                 *firstvertexpointer = firstvertex;
2430         if (lastvertexpointer)
2431                 *lastvertexpointer = lastvertex;
2432 }
2433
2434 void Mod_MakeSortedSurfaces(dp_model_t *mod)
2435 {
2436         // make an optimal set of texture-sorted batches to draw...
2437         int j, t;
2438         int *firstsurfacefortexture;
2439         int *numsurfacesfortexture;
2440         if (!mod->sortedmodelsurfaces)
2441                 mod->sortedmodelsurfaces = (int *) Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
2442         firstsurfacefortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*firstsurfacefortexture));
2443         numsurfacesfortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*numsurfacesfortexture));
2444         memset(numsurfacesfortexture, 0, mod->num_textures * sizeof(*numsurfacesfortexture));
2445         for (j = 0;j < mod->nummodelsurfaces;j++)
2446         {
2447                 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2448                 int t = (int)(surface->texture - mod->data_textures);
2449                 numsurfacesfortexture[t]++;
2450         }
2451         j = 0;
2452         for (t = 0;t < mod->num_textures;t++)
2453         {
2454                 firstsurfacefortexture[t] = j;
2455                 j += numsurfacesfortexture[t];
2456         }
2457         for (j = 0;j < mod->nummodelsurfaces;j++)
2458         {
2459                 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2460                 int t = (int)(surface->texture - mod->data_textures);
2461                 mod->sortedmodelsurfaces[firstsurfacefortexture[t]++] = j + mod->firstmodelsurface;
2462         }
2463         Mem_Free(firstsurfacefortexture);
2464         Mem_Free(numsurfacesfortexture);
2465 }
2466
2467 static void Mod_BuildVBOs(void)
2468 {
2469         if (developer.integer && loadmodel->surfmesh.data_element3s && loadmodel->surfmesh.data_element3i)
2470         {
2471                 int i;
2472                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2473                 {
2474                         if (loadmodel->surfmesh.data_element3s[i] != loadmodel->surfmesh.data_element3i[i])
2475                         {
2476                                 Con_Printf("Mod_BuildVBOs: element %u is incorrect (%u should be %u)\n", i, loadmodel->surfmesh.data_element3s[i], loadmodel->surfmesh.data_element3i[i]);
2477                                 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2478                         }
2479                 }
2480         }
2481
2482         if (!gl_support_arb_vertex_buffer_object)
2483                 return;
2484
2485         // element buffer is easy because it's just one array
2486         if (loadmodel->surfmesh.num_triangles)
2487         {
2488                 if (loadmodel->surfmesh.data_element3s)
2489                         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);
2490                 else
2491                         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);
2492         }
2493
2494         // vertex buffer is several arrays and we put them in the same buffer
2495         //
2496         // is this wise?  the texcoordtexture2f array is used with dynamic
2497         // vertex/svector/tvector/normal when rendering animated models, on the
2498         // other hand animated models don't use a lot of vertices anyway...
2499         if (loadmodel->surfmesh.num_vertices)
2500         {
2501                 size_t size;
2502                 unsigned char *mem;
2503                 size = 0;
2504                 loadmodel->surfmesh.vbooffset_vertex3f           = size;if (loadmodel->surfmesh.data_vertex3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2505                 loadmodel->surfmesh.vbooffset_svector3f          = size;if (loadmodel->surfmesh.data_svector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2506                 loadmodel->surfmesh.vbooffset_tvector3f          = size;if (loadmodel->surfmesh.data_tvector3f         ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2507                 loadmodel->surfmesh.vbooffset_normal3f           = size;if (loadmodel->surfmesh.data_normal3f          ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2508                 loadmodel->surfmesh.vbooffset_texcoordtexture2f  = size;if (loadmodel->surfmesh.data_texcoordtexture2f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2509                 loadmodel->surfmesh.vbooffset_texcoordlightmap2f = size;if (loadmodel->surfmesh.data_texcoordlightmap2f) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2510                 loadmodel->surfmesh.vbooffset_lightmapcolor4f    = size;if (loadmodel->surfmesh.data_lightmapcolor4f   ) size += loadmodel->surfmesh.num_vertices * sizeof(float[4]);
2511                 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
2512                 if (loadmodel->surfmesh.data_vertex3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_vertex3f          , loadmodel->surfmesh.data_vertex3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2513                 if (loadmodel->surfmesh.data_svector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_svector3f         , loadmodel->surfmesh.data_svector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2514                 if (loadmodel->surfmesh.data_tvector3f         ) memcpy(mem + loadmodel->surfmesh.vbooffset_tvector3f         , loadmodel->surfmesh.data_tvector3f         , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2515                 if (loadmodel->surfmesh.data_normal3f          ) memcpy(mem + loadmodel->surfmesh.vbooffset_normal3f          , loadmodel->surfmesh.data_normal3f          , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2516                 if (loadmodel->surfmesh.data_texcoordtexture2f ) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordtexture2f , loadmodel->surfmesh.data_texcoordtexture2f , loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2517                 if (loadmodel->surfmesh.data_texcoordlightmap2f) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordlightmap2f, loadmodel->surfmesh.data_texcoordlightmap2f, loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2518                 if (loadmodel->surfmesh.data_lightmapcolor4f   ) memcpy(mem + loadmodel->surfmesh.vbooffset_lightmapcolor4f   , loadmodel->surfmesh.data_lightmapcolor4f   , loadmodel->surfmesh.num_vertices * sizeof(float[4]));
2519                 loadmodel->surfmesh.vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, loadmodel->name);
2520                 Mem_Free(mem);
2521         }
2522 }
2523
2524 static void Mod_Decompile_OBJ(dp_model_t *model, const char *filename, const char *mtlfilename, const char *originalfilename)
2525 {
2526         int vertexindex, surfaceindex, triangleindex, textureindex, countvertices = 0, countsurfaces = 0, countfaces = 0, counttextures = 0;
2527         int a, b, c;
2528         const char *texname;
2529         const int *e;
2530         const float *v, *vn, *vt;
2531         size_t l;
2532         size_t outbufferpos = 0;
2533         size_t outbuffermax = 0x100000;
2534         char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
2535         const msurface_t *surface;
2536         const int maxtextures = 256;
2537         char *texturenames = (char *) Z_Malloc(maxtextures * MAX_QPATH);
2538
2539         // construct the mtllib file
2540         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "# mtllib for %s exported by darkplaces engine\n", originalfilename);
2541         if (l > 0)
2542                 outbufferpos += l;
2543         for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2544         {
2545                 countsurfaces++;
2546                 countvertices += surface->num_vertices;
2547                 countfaces += surface->num_triangles;
2548                 texname = (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default";
2549                 for (textureindex = 0;textureindex < counttextures;textureindex++)
2550                         if (!strcmp(texturenames + textureindex * MAX_QPATH, texname))
2551                                 break;
2552                 if (textureindex < counttextures)
2553                         continue; // already wrote this material entry
2554                 if (textureindex >= maxtextures)
2555                         continue; // just a precaution
2556                 textureindex = counttextures++;
2557                 strlcpy(texturenames + textureindex * MAX_QPATH, texname, MAX_QPATH);
2558                 if (outbufferpos >= outbuffermax >> 1)
2559                 {
2560                         outbuffermax *= 2;
2561                         oldbuffer = outbuffer;
2562                         outbuffer = (char *) Z_Malloc(outbuffermax);
2563                         memcpy(outbuffer, oldbuffer, outbufferpos);
2564                         Z_Free(oldbuffer);
2565                 }
2566                 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");
2567                 if (l > 0)
2568                         outbufferpos += l;
2569         }
2570
2571         // write the mtllib file
2572         FS_WriteFile(mtlfilename, outbuffer, outbufferpos);
2573         outbufferpos = 0;
2574
2575         // construct the obj file
2576         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);
2577         if (l > 0)
2578                 outbufferpos += l;
2579         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)
2580         {
2581                 if (outbufferpos >= outbuffermax >> 1)
2582                 {
2583                         outbuffermax *= 2;
2584                         oldbuffer = outbuffer;
2585                         outbuffer = (char *) Z_Malloc(outbuffermax);
2586                         memcpy(outbuffer, oldbuffer, outbufferpos);
2587                         Z_Free(oldbuffer);
2588                 }
2589                 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]);
2590                 if (l > 0)
2591                         outbufferpos += l;
2592         }
2593         for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2594         {
2595                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "usemtl %s\n", (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default");
2596                 if (l > 0)
2597                         outbufferpos += l;
2598                 for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
2599                 {
2600                         if (outbufferpos >= outbuffermax >> 1)
2601                         {
2602                                 outbuffermax *= 2;
2603                                 oldbuffer = outbuffer;
2604                                 outbuffer = (char *) Z_Malloc(outbuffermax);
2605                                 memcpy(outbuffer, oldbuffer, outbufferpos);
2606                                 Z_Free(oldbuffer);
2607                         }
2608                         a = e[0]+1;
2609                         b = e[2]+1;
2610                         c = e[1]+1;
2611                         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);
2612                         if (l > 0)
2613                                 outbufferpos += l;
2614                 }
2615         }
2616
2617         // write the obj file
2618         FS_WriteFile(filename, outbuffer, outbufferpos);
2619
2620         // clean up
2621         Z_Free(outbuffer);
2622         Z_Free(texturenames);
2623
2624         // print some stats
2625         Con_Printf("Wrote %s (%i bytes, %i vertices, %i faces, %i surfaces with %i distinct textures)\n", filename, (int)outbufferpos, countvertices, countfaces, countsurfaces, counttextures);
2626 }
2627
2628 static void Mod_Decompile_SMD(dp_model_t *model, const char *filename, int firstpose, int numposes, qboolean writetriangles)
2629 {
2630         int countnodes = 0, counttriangles = 0, countframes = 0;
2631         int surfaceindex;
2632         int triangleindex;
2633         int transformindex;
2634         int poseindex;
2635         int cornerindex;
2636         float modelscale;
2637         const int *e;
2638         const float *pose;
2639         size_t l;
2640         size_t outbufferpos = 0;
2641         size_t outbuffermax = 0x100000;
2642         char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
2643         const msurface_t *surface;
2644         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "version 1\nnodes\n");
2645         if (l > 0)
2646                 outbufferpos += l;
2647         modelscale = 1;
2648         if(model->num_poses >= 0)
2649                 modelscale = sqrt(model->data_poses[0] * model->data_poses[0] + model->data_poses[1] * model->data_poses[1] + model->data_poses[2] * model->data_poses[2]);
2650         if(fabs(modelscale - 1) > 1e-4)
2651         {
2652                 if(firstpose == 0) // only print the when writing the reference pose
2653                         Con_Printf("The model has an old-style model scale of %f\n", modelscale);
2654         }
2655         else
2656                 modelscale = 1;
2657         for (transformindex = 0;transformindex < model->num_bones;transformindex++)
2658         {
2659                 if (outbufferpos >= outbuffermax >> 1)
2660                 {
2661                         outbuffermax *= 2;
2662                         oldbuffer = outbuffer;
2663                         outbuffer = (char *) Z_Malloc(outbuffermax);
2664                         memcpy(outbuffer, oldbuffer, outbufferpos);
2665                         Z_Free(oldbuffer);
2666                 }
2667                 countnodes++;
2668                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i \"%s\" %3i\n", transformindex, model->data_bones[transformindex].name, model->data_bones[transformindex].parent);
2669                 if (l > 0)
2670                         outbufferpos += l;
2671         }
2672         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\nskeleton\n");
2673         if (l > 0)
2674                 outbufferpos += l;
2675         for (poseindex = 0, pose = model->data_poses + model->num_bones * 12 * firstpose;poseindex < numposes;poseindex++)
2676         {
2677                 countframes++;
2678                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "time %i\n", poseindex);
2679                 if (l > 0)
2680                         outbufferpos += l;
2681                 for (transformindex = 0;transformindex < model->num_bones;transformindex++, pose += 12)
2682                 {
2683                         float a, b, c;
2684                         float angles[3];
2685                         float mtest[3][4];
2686                         if (outbufferpos >= outbuffermax >> 1)
2687                         {
2688                                 outbuffermax *= 2;
2689                                 oldbuffer = outbuffer;
2690                                 outbuffer = (char *) Z_Malloc(outbuffermax);
2691                                 memcpy(outbuffer, oldbuffer, outbufferpos);
2692                                 Z_Free(oldbuffer);
2693                         }
2694
2695                         // strangely the smd angles are for a transposed matrix, so we
2696                         // have to generate a transposed matrix, then convert that...
2697                         mtest[0][0] = pose[ 0];
2698                         mtest[0][1] = pose[ 4];
2699                         mtest[0][2] = pose[ 8];
2700                         mtest[0][3] = pose[ 3];
2701                         mtest[1][0] = pose[ 1];
2702                         mtest[1][1] = pose[ 5];
2703                         mtest[1][2] = pose[ 9];
2704                         mtest[1][3] = pose[ 7];
2705                         mtest[2][0] = pose[ 2];
2706                         mtest[2][1] = pose[ 6];
2707                         mtest[2][2] = pose[10];
2708                         mtest[2][3] = pose[11];
2709                         AnglesFromVectors(angles, mtest[0], mtest[2], false);
2710                         if (angles[0] >= 180) angles[0] -= 360;
2711                         if (angles[1] >= 180) angles[1] -= 360;
2712                         if (angles[2] >= 180) angles[2] -= 360;
2713
2714                         a = DEG2RAD(angles[ROLL]);
2715                         b = DEG2RAD(angles[PITCH]);
2716                         c = DEG2RAD(angles[YAW]);
2717
2718 #if 0
2719 {
2720                         float cy, sy, cp, sp, cr, sr;
2721                         float test[3][4];
2722                         // smd matrix construction, for comparing to non-transposed m
2723                         sy = sin(c);
2724                         cy = cos(c);
2725                         sp = sin(b);
2726                         cp = cos(b);
2727                         sr = sin(a);
2728                         cr = cos(a);
2729
2730                         test[0][0] = cp*cy;
2731                         test[1][0] = cp*sy;
2732                         test[2][0] = -sp;
2733                         test[0][1] = sr*sp*cy+cr*-sy;
2734                         test[1][1] = sr*sp*sy+cr*cy;
2735                         test[2][1] = sr*cp;
2736                         test[0][2] = (cr*sp*cy+-sr*-sy);
2737                         test[1][2] = (cr*sp*sy+-sr*cy);
2738                         test[2][2] = cr*cp;
2739                         test[0][3] = pose[3];
2740                         test[1][3] = pose[7];
2741                         test[2][3] = pose[11];
2742 }
2743 #endif
2744                         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f\n", transformindex, pose[3] * modelscale, pose[7] * modelscale, pose[11] * modelscale, DEG2RAD(angles[ROLL]), DEG2RAD(angles[PITCH]), DEG2RAD(angles[YAW]));
2745                         if (l > 0)
2746                                 outbufferpos += l;
2747                 }
2748         }
2749         l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
2750         if (l > 0)
2751                 outbufferpos += l;
2752         if (writetriangles)
2753         {
2754                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "triangles\n");
2755                 if (l > 0)
2756                         outbufferpos += l;
2757                 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2758                 {
2759                         for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
2760                         {
2761                                 counttriangles++;
2762                                 if (outbufferpos >= outbuffermax >> 1)
2763                                 {
2764                                         outbuffermax *= 2;
2765                                         oldbuffer = outbuffer;
2766                                         outbuffer = (char *) Z_Malloc(outbuffermax);
2767                                         memcpy(outbuffer, oldbuffer, outbufferpos);
2768                                         Z_Free(oldbuffer);
2769                                 }
2770                                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%s\n", surface->texture && surface->texture->name[0] ? surface->texture->name : "default.bmp");
2771                                 if (l > 0)
2772                                         outbufferpos += l;
2773                                 for (cornerindex = 0;cornerindex < 3;cornerindex++)
2774                                 {
2775                                         const int index = e[2-cornerindex];
2776                                         const float *v = model->surfmesh.data_vertex3f + index * 3;
2777                                         const float *vn = model->surfmesh.data_normal3f + index * 3;
2778                                         const float *vt = model->surfmesh.data_texcoordtexture2f + index * 2;
2779                                         const int *wi = model->surfmesh.data_vertexweightindex4i + index * 4;
2780                                         const float *wf = model->surfmesh.data_vertexweightinfluence4f + index * 4;
2781                                              if (wf[3]) l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f 4 %i %f %i %f %i %f %i %f\n", wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1], wi[0], wf[0], wi[1], wf[1], wi[2], wf[2], wi[3], wf[3]);
2782                                         else if (wf[2]) l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f 3 %i %f %i %f %i %f\n"      , wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1], wi[0], wf[0], wi[1], wf[1], wi[2], wf[2]);
2783                                         else if (wf[1]) l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f 2 %i %f %i %f\n"            , wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1], wi[0], wf[0], wi[1], wf[1]);
2784                                         else            l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f\n"                          , wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1]);
2785                                         if (l > 0)
2786                                                 outbufferpos += l;
2787                                 }
2788                         }
2789                 }
2790                 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
2791                 if (l > 0)
2792                         outbufferpos += l;
2793         }
2794
2795         FS_WriteFile(filename, outbuffer, outbufferpos);
2796         Z_Free(outbuffer);
2797
2798         Con_Printf("Wrote %s (%i bytes, %i nodes, %i frames, %i triangles)\n", filename, (int)outbufferpos, countnodes, countframes, counttriangles);
2799 }
2800
2801 /*
2802 ================
2803 Mod_Decompile_f
2804
2805 decompiles a model to editable files
2806 ================
2807 */
2808 static void Mod_Decompile_f(void)
2809 {
2810         int i, j, k, l, first, count;
2811         dp_model_t *mod;
2812         char inname[MAX_QPATH];
2813         char outname[MAX_QPATH];
2814         char mtlname[MAX_QPATH];
2815         char basename[MAX_QPATH];
2816         char animname[MAX_QPATH];
2817         char animname2[MAX_QPATH];
2818         char zymtextbuffer[16384];
2819         char dpmtextbuffer[16384];
2820         int zymtextsize = 0;
2821         int dpmtextsize = 0;
2822
2823         if (Cmd_Argc() != 2)
2824         {
2825                 Con_Print("usage: modeldecompile <filename>\n");
2826                 return;
2827         }
2828
2829         strlcpy(inname, Cmd_Argv(1), sizeof(inname));
2830         FS_StripExtension(inname, basename, sizeof(basename));
2831
2832         mod = Mod_ForName(inname, false, true, inname[0] == '*' ? cl.model_name[1] : NULL);
2833         if (mod->brush.submodel)
2834         {
2835                 // if we're decompiling a submodel, be sure to give it a proper name based on its parent
2836                 FS_StripExtension(cl.model_name[1], outname, sizeof(outname));
2837                 dpsnprintf(basename, sizeof(basename), "%s/%s", outname, mod->name);
2838                 outname[0] = 0;
2839         }
2840         if (!mod)
2841         {
2842                 Con_Print("No such model\n");
2843                 return;
2844         }
2845         if (!mod->surfmesh.num_triangles)
2846         {
2847                 Con_Print("Empty model (or sprite)\n");
2848                 return;
2849         }
2850
2851         // export OBJ if possible (not on sprites)
2852         if (mod->surfmesh.num_triangles)
2853         {
2854                 dpsnprintf(outname, sizeof(outname), "%s_decompiled.obj", basename);
2855                 dpsnprintf(mtlname, sizeof(mtlname), "%s_decompiled.mtl", basename);
2856                 Mod_Decompile_OBJ(mod, outname, mtlname, inname);
2857         }
2858
2859         // export SMD if possible (only for skeletal models)
2860         if (mod->surfmesh.num_triangles && mod->num_bones)
2861         {
2862                 dpsnprintf(outname, sizeof(outname), "%s_decompiled/ref1.smd", basename);
2863                 Mod_Decompile_SMD(mod, outname, 0, 1, true);
2864                 l = dpsnprintf(zymtextbuffer + zymtextsize, sizeof(zymtextbuffer) - zymtextsize, "output out.zym\nscale 1\norigin 0 0 0\nmesh ref1.smd\n");
2865                 if (l > 0) zymtextsize += l;
2866                 l = dpsnprintf(dpmtextbuffer + dpmtextsize, sizeof(dpmtextbuffer) - dpmtextsize, "outputdir .\nmodel out\nscale 1\norigin 0 0 0\nscene ref1.smd\n");
2867                 if (l > 0) dpmtextsize += l;
2868                 for (i = 0;i < mod->numframes;i = j)
2869                 {
2870                         strlcpy(animname, mod->animscenes[i].name, sizeof(animname));
2871                         first = mod->animscenes[i].firstframe;
2872                         if (mod->animscenes[i].framecount > 1)
2873                         {
2874                                 // framegroup anim
2875                                 count = mod->animscenes[i].framecount;
2876                                 j = i + 1;
2877                         }
2878                         else
2879                         {
2880                                 // individual frame
2881                                 // check for additional frames with same name
2882                                 for (l = 0, k = strlen(animname);animname[l];l++)
2883                                         if ((animname[l] < '0' || animname[l] > '9') && animname[l] != '_')
2884                                                 k = l + 1;
2885                                 animname[k] = 0;
2886                                 count = mod->num_poses - first;
2887                                 for (j = i + 1;j < mod->numframes;j++)
2888                                 {
2889                                         strlcpy(animname2, mod->animscenes[j].name, sizeof(animname2));
2890                                         for (l = 0, k = strlen(animname2);animname2[l];l++)
2891                                                 if ((animname2[l] < '0' || animname2[l] > '9') && animname2[l] != '_')
2892                                                         k = l + 1;
2893                                         animname2[k] = 0;
2894                                         if (strcmp(animname2, animname) || mod->animscenes[j].framecount > 1)
2895                                         {
2896                                                 count = mod->animscenes[j].firstframe - first;
2897                                                 break;
2898                                         }
2899                                 }
2900                                 // if it's only one frame, use the original frame name
2901                                 if (j == i + 1)
2902                                         strlcpy(animname, mod->animscenes[i].name, sizeof(animname));
2903                                 
2904                         }
2905                         dpsnprintf(outname, sizeof(outname), "%s_decompiled/%s.smd", basename, animname);
2906                         Mod_Decompile_SMD(mod, outname, first, count, false);
2907                         if (zymtextsize < (int)sizeof(zymtextbuffer) - 100)
2908                         {
2909                                 l = dpsnprintf(zymtextbuffer + zymtextsize, sizeof(zymtextbuffer) - zymtextsize, "scene %s.smd fps %g\n", animname, mod->animscenes[i].framerate);
2910                                 if (l > 0) zymtextsize += l;
2911                         }
2912                         if (dpmtextsize < (int)sizeof(dpmtextbuffer) - 100)
2913                         {
2914                                 l = dpsnprintf(dpmtextbuffer + dpmtextsize, sizeof(dpmtextbuffer) - dpmtextsize, "scene %s.smd\n", animname);
2915                                 if (l > 0) dpmtextsize += l;
2916                         }
2917                 }
2918                 if (zymtextsize)
2919                         FS_WriteFile(va("%s_decompiled/out_zym.txt", basename), zymtextbuffer, (fs_offset_t)zymtextsize);
2920                 if (dpmtextsize)
2921                         FS_WriteFile(va("%s_decompiled/out_dpm.txt", basename), dpmtextbuffer, (fs_offset_t)dpmtextsize);
2922         }
2923 }
2924
2925 void Mod_AllocLightmap_Init(mod_alloclightmap_state_t *state, int width, int height)
2926 {
2927         int y;
2928         memset(state, 0, sizeof(*state));
2929         state->width = width;
2930         state->height = height;
2931         state->currentY = 0;
2932         state->rows = Mem_Alloc(tempmempool, state->height * sizeof(*state->rows));
2933         for (y = 0;y < state->height;y++)
2934         {
2935                 state->rows[y].currentX = 0;
2936                 state->rows[y].rowY = -1;
2937         }
2938 }
2939
2940 void Mod_AllocLightmap_Reset(mod_alloclightmap_state_t *state)
2941 {
2942         int y;
2943         state->currentY = 0;
2944         for (y = 0;y < state->height;y++)
2945         {
2946                 state->rows[y].currentX = 0;
2947                 state->rows[y].rowY = -1;
2948         }
2949 }
2950
2951 void Mod_AllocLightmap_Free(mod_alloclightmap_state_t *state)
2952 {
2953         if (state->rows)
2954                 Mem_Free(state->rows);
2955         memset(state, 0, sizeof(*state));
2956 }
2957
2958 qboolean Mod_AllocLightmap_Block(mod_alloclightmap_state_t *state, int blockwidth, int blockheight, int *outx, int *outy)
2959 {
2960         mod_alloclightmap_row_t *row;
2961         int y;
2962
2963         row = state->rows + blockheight;
2964         if ((row->rowY < 0) || (row->currentX + blockwidth > state->width))
2965         {
2966                 if (state->currentY + blockheight <= state->height)
2967                 {
2968                         // use the current allocation position
2969                         row->rowY = state->currentY;
2970                         row->currentX = 0;
2971                         state->currentY += blockheight;
2972                 }
2973                 else
2974                 {
2975                         // find another position
2976                         for (y = blockheight;y < state->height;y++)
2977                         {
2978                                 if ((state->rows[y].rowY >= 0) && (state->rows[y].currentX + blockwidth <= state->width))
2979                                 {
2980                                         row = state->rows + y;
2981                                         break;
2982                                 }
2983                         }
2984                         if (y == state->height)
2985                                 return false;
2986                 }
2987         }
2988         *outy = row->rowY;
2989         *outx = row->currentX;
2990         row->currentX += blockwidth;
2991
2992         return true;
2993 }
2994
2995 typedef struct lightmapsample_s
2996 {
2997         float pos[3];
2998         float sh1[4][3];
2999         float *vertex_color;
3000         unsigned char *lm_bgr;
3001         unsigned char *lm_dir;
3002 }
3003 lightmapsample_t;
3004
3005 typedef struct lightmapvertex_s
3006 {
3007         int index;
3008         float pos[3];
3009         float normal[3];
3010         float texcoordbase[2];
3011         float texcoordlightmap[2];
3012         float lightcolor[4];
3013 }
3014 lightmapvertex_t;
3015
3016 typedef struct lightmaptriangle_s
3017 {
3018         int triangleindex;
3019         int surfaceindex;
3020         int lightmapindex;
3021         int axis;
3022         int lmoffset[2];
3023         int lmsize[2];
3024         // 2D modelspace coordinates of min corner
3025         // snapped to lightmap grid but not in grid coordinates
3026         float lmbase[2];
3027         // 2D modelspace to lightmap coordinate scale
3028         float lmscale[2];
3029         float vertex[3][3];
3030 }
3031 lightmaptriangle_t;
3032
3033 lightmaptriangle_t *mod_generatelightmaps_lightmaptriangles;
3034
3035 extern void R_SampleRTLights(const float *pos, float *sh1);
3036
3037 static void Mod_GenerateLightmaps_SamplePoint(const float *pos, float *sh1)
3038 {
3039         int i;
3040         for (i = 0;i < 4*3;i++)
3041                 sh1[i] = 0.0f;
3042         R_SampleRTLights(pos, sh1);
3043 }
3044
3045 static void Mod_GenerateLightmaps_LightmapSample(const float *pos, const float *normal, unsigned char *lm_bgr, unsigned char *lm_dir)
3046 {
3047         float sh1[4*3];
3048         float color[3];
3049         float dir[3];
3050         Mod_GenerateLightmaps_SamplePoint(pos, sh1);
3051         VectorSet(dir, VectorLength(sh1 + 3), VectorLength(sh1 + 6), VectorLength(sh1 + 9));
3052         VectorNormalize(dir);
3053         VectorScale(sh1, 127.5f, color);
3054         VectorSet(dir, (dir[0]+1.0f)*127.5f, (dir[1]+1.0f)*127.5f, (dir[2]+1.0f)*127.5f);
3055         lm_bgr[0] = (unsigned char)bound(0.0f, color[2], 255.0f);
3056         lm_bgr[1] = (unsigned char)bound(0.0f, color[1], 255.0f);
3057         lm_bgr[2] = (unsigned char)bound(0.0f, color[0], 255.0f);
3058         lm_bgr[3] = 255;
3059         lm_dir[0] = (unsigned char)dir[0];
3060         lm_dir[1] = (unsigned char)dir[1];
3061         lm_dir[2] = (unsigned char)dir[2];
3062         lm_dir[3] = 255;
3063 }
3064
3065 static void Mod_GenerateLightmaps_VertexSample(const float *pos, const float *normal, float *vertex_color)
3066 {
3067         float sh1[4*3];
3068         Mod_GenerateLightmaps_SamplePoint(pos, sh1);
3069         VectorCopy(sh1, vertex_color);
3070 }
3071
3072 static void Mod_GenerateLightmaps_GridSample(const float *pos, q3dlightgrid_t *s)
3073 {
3074         float sh1[4*3];
3075         float ambient[3];
3076         float diffuse[3];
3077         float dir[3];
3078         Mod_GenerateLightmaps_SamplePoint(pos, sh1);
3079         // calculate the direction we'll use to reduce the sh1 to a directional light source
3080         VectorSet(dir, VectorLength(sh1 + 3), VectorLength(sh1 + 6), VectorLength(sh1 + 9));
3081         VectorNormalize(dir);
3082         // scale the ambient from 0-2 to 0-255
3083         VectorScale(sh1, 127.5f, ambient);
3084         // extract the diffuse color along the chosen direction and scale it
3085         diffuse[0] = (dir[0]*sh1[3] + dir[1]*sh1[6] + dir[2]*sh1[ 9] + sh1[0]) * 127.5f;
3086         diffuse[1] = (dir[0]*sh1[4] + dir[1]*sh1[7] + dir[2]*sh1[10] + sh1[1]) * 127.5f;
3087         diffuse[2] = (dir[0]*sh1[5] + dir[1]*sh1[8] + dir[2]*sh1[11] + sh1[2]) * 127.5f;
3088         // encode to the grid format
3089         s->ambientrgb[0] = (unsigned char)bound(0.0f, ambient[0], 255.0f);
3090         s->ambientrgb[1] = (unsigned char)bound(0.0f, ambient[1], 255.0f);
3091         s->ambientrgb[2] = (unsigned char)bound(0.0f, ambient[2], 255.0f);
3092         s->diffusergb[0] = (unsigned char)bound(0.0f, diffuse[0], 255.0f);
3093         s->diffusergb[1] = (unsigned char)bound(0.0f, diffuse[1], 255.0f);
3094         s->diffusergb[2] = (unsigned char)bound(0.0f, diffuse[2], 255.0f);
3095         if (dir[2] >= 0.99f) {s->diffuseyaw = 0;s->diffusepitch = 0;}
3096         else if (dir[2] <= -0.99f) {s->diffuseyaw = 0;s->diffusepitch = 128;}
3097         else {s->diffuseyaw = (unsigned char)(acos(dir[2]) * (127.5f/M_PI));s->diffusepitch = (unsigned char)(atan2(dir[1], dir[0]) * (127.5f/M_PI));}
3098 }
3099
3100 static void Mod_GenerateLightmaps_DestroyLightmaps(dp_model_t *model)
3101 {
3102         msurface_t *surface;
3103         int surfaceindex;
3104         int i;
3105         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3106         {
3107                 surface = model->data_surfaces + surfaceindex;
3108                 surface->lightmaptexture = NULL;
3109                 surface->deluxemaptexture = NULL;
3110         }
3111         if (model->brushq3.data_lightmaps)
3112         {
3113                 for (i = 0;i < model->brushq3.num_mergedlightmaps;i++)
3114                         R_FreeTexture(model->brushq3.data_lightmaps[i]);
3115                 Mem_Free(model->brushq3.data_lightmaps);
3116                 model->brushq3.data_lightmaps = NULL;
3117         }
3118         if (model->brushq3.data_deluxemaps)
3119         {
3120                 for (i = 0;i < model->brushq3.num_mergedlightmaps;i++)
3121                         R_FreeTexture(model->brushq3.data_deluxemaps[i]);
3122                 Mem_Free(model->brushq3.data_deluxemaps);
3123                 model->brushq3.data_deluxemaps = NULL;
3124         }
3125 }
3126
3127 static void Mod_GenerateLightmaps_UnweldTriangles(dp_model_t *model)
3128 {
3129         msurface_t *surface;
3130         int surfaceindex;
3131         int vertexindex;
3132         int outvertexindex;
3133         int i;
3134         const int *e;
3135         surfmesh_t oldsurfmesh;
3136         size_t size;
3137         unsigned char *data;
3138         oldsurfmesh = model->surfmesh;
3139         model->surfmesh.num_triangles = oldsurfmesh.num_triangles;
3140         model->surfmesh.num_vertices = oldsurfmesh.num_triangles * 3;
3141         size = 0;
3142         size += model->surfmesh.num_vertices * sizeof(float[3]);
3143         size += model->surfmesh.num_vertices * sizeof(float[3]);
3144         size += model->surfmesh.num_vertices * sizeof(float[3]);
3145         size += model->surfmesh.num_vertices * sizeof(float[3]);
3146         size += model->surfmesh.num_vertices * sizeof(float[2]);
3147         size += model->surfmesh.num_vertices * sizeof(float[2]);
3148         size += model->surfmesh.num_vertices * sizeof(float[4]);
3149         data = (unsigned char *)Mem_Alloc(model->mempool, size);
3150         model->surfmesh.data_vertex3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3151         model->surfmesh.data_normal3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3152         model->surfmesh.data_svector3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3153         model->surfmesh.data_tvector3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3154         model->surfmesh.data_texcoordtexture2f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[2]);
3155         model->surfmesh.data_texcoordlightmap2f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[2]);
3156         model->surfmesh.data_lightmapcolor4f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[4]);
3157         if (model->surfmesh.num_vertices > 65536)
3158                 model->surfmesh.data_element3s = NULL;
3159
3160         if (model->surfmesh.vbo)
3161                 R_Mesh_DestroyBufferObject(model->surfmesh.vbo);
3162         model->surfmesh.vbo = 0;
3163         if (model->surfmesh.ebo3i)
3164                 R_Mesh_DestroyBufferObject(model->surfmesh.ebo3i);
3165         model->surfmesh.ebo3i = 0;
3166         if (model->surfmesh.ebo3s)
3167                 R_Mesh_DestroyBufferObject(model->surfmesh.ebo3s);
3168         model->surfmesh.ebo3s = 0;
3169
3170         // convert all triangles to unique vertex data
3171         outvertexindex = 0;
3172         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3173         {
3174                 surface = model->data_surfaces + surfaceindex;
3175                 surface->num_firstvertex = outvertexindex;
3176                 surface->num_vertices = surface->num_triangles*3;
3177                 e = oldsurfmesh.data_element3i + surface->num_firsttriangle*3;
3178                 for (i = 0;i < surface->num_triangles*3;i++)
3179                 {
3180                         vertexindex = e[i];
3181                         model->surfmesh.data_vertex3f[outvertexindex*3+0] = oldsurfmesh.data_vertex3f[vertexindex*3+0];
3182                         model->surfmesh.data_vertex3f[outvertexindex*3+1] = oldsurfmesh.data_vertex3f[vertexindex*3+1];
3183                         model->surfmesh.data_vertex3f[outvertexindex*3+2] = oldsurfmesh.data_vertex3f[vertexindex*3+2];
3184                         model->surfmesh.data_normal3f[outvertexindex*3+0] = oldsurfmesh.data_normal3f[vertexindex*3+0];
3185                         model->surfmesh.data_normal3f[outvertexindex*3+1] = oldsurfmesh.data_normal3f[vertexindex*3+1];
3186                         model->surfmesh.data_normal3f[outvertexindex*3+2] = oldsurfmesh.data_normal3f[vertexindex*3+2];
3187                         model->surfmesh.data_svector3f[outvertexindex*3+0] = oldsurfmesh.data_svector3f[vertexindex*3+0];
3188                         model->surfmesh.data_svector3f[outvertexindex*3+1] = oldsurfmesh.data_svector3f[vertexindex*3+1];
3189                         model->surfmesh.data_svector3f[outvertexindex*3+2] = oldsurfmesh.data_svector3f[vertexindex*3+2];
3190                         model->surfmesh.data_tvector3f[outvertexindex*3+0] = oldsurfmesh.data_tvector3f[vertexindex*3+0];
3191                         model->surfmesh.data_tvector3f[outvertexindex*3+1] = oldsurfmesh.data_tvector3f[vertexindex*3+1];
3192                         model->surfmesh.data_tvector3f[outvertexindex*3+2] = oldsurfmesh.data_tvector3f[vertexindex*3+2];
3193                         model->surfmesh.data_texcoordtexture2f[outvertexindex*2+0] = oldsurfmesh.data_texcoordtexture2f[vertexindex*2+0];
3194                         model->surfmesh.data_texcoordtexture2f[outvertexindex*2+1] = oldsurfmesh.data_texcoordtexture2f[vertexindex*2+1];
3195                         model->surfmesh.data_texcoordlightmap2f[outvertexindex*2+0] = oldsurfmesh.data_texcoordlightmap2f[vertexindex*2+0];
3196                         model->surfmesh.data_texcoordlightmap2f[outvertexindex*2+1] = oldsurfmesh.data_texcoordlightmap2f[vertexindex*2+1];
3197                         model->surfmesh.data_lightmapcolor4f[outvertexindex*4+0] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+0];
3198                         model->surfmesh.data_lightmapcolor4f[outvertexindex*4+1] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+1];
3199                         model->surfmesh.data_lightmapcolor4f[outvertexindex*4+2] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+2];
3200                         model->surfmesh.data_lightmapcolor4f[outvertexindex*4+3] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+3];
3201                         model->surfmesh.data_element3i[surface->num_firsttriangle*3+i] = outvertexindex;
3202                         outvertexindex++;
3203                 }
3204         }
3205         if (model->surfmesh.data_element3s)
3206                 for (i = 0;i < model->surfmesh.num_triangles*3;i++)
3207                         model->surfmesh.data_element3s[i] = model->surfmesh.data_element3i[i];
3208
3209         // find and update all submodels to use this new surfmesh data
3210         for (i = 0;i < model->brush.numsubmodels;i++)
3211                 model->brush.submodels[i]->surfmesh = model->surfmesh;
3212 }
3213
3214 static void Mod_GenerateLightmaps_CreateTriangleInformation(dp_model_t *model)
3215 {
3216         msurface_t *surface;
3217         int surfaceindex;
3218         int i;
3219         const int *e;
3220         lightmaptriangle_t *triangle;
3221         // generate lightmap triangle structs
3222         mod_generatelightmaps_lightmaptriangles = Mem_Alloc(model->mempool, model->surfmesh.num_triangles * sizeof(lightmaptriangle_t));
3223         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3224         {
3225                 surface = model->data_surfaces + surfaceindex;
3226                 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
3227                 for (i = 0;i < surface->num_triangles;i++)
3228                 {
3229                         triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
3230                         triangle->triangleindex = surface->num_firsttriangle+i;
3231                         triangle->surfaceindex = surfaceindex;
3232                         VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+0], triangle->vertex[0]);
3233                         VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+1], triangle->vertex[1]);
3234                         VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+2], triangle->vertex[2]);
3235                 }
3236         }
3237 }
3238
3239 #if 0
3240 float lmprojection[3][3][3] =
3241 {
3242         {{0, 1, 0}, {0, 0, 1}, {1, 0, 0}},
3243         {{1, 0, 0}, {0, 0, 1}, {0, 1, 0}},
3244         {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}},
3245 };
3246 #endif
3247
3248 static void Mod_GenerateLightmaps_ClassifyTriangles(dp_model_t *model)
3249 {
3250         msurface_t *surface;
3251         int surfaceindex;
3252         int i;
3253         int axis;
3254         float mins[3];
3255         float maxs[3];
3256         float aabbsize[3];
3257         const int *e;
3258         lightmaptriangle_t *triangle;
3259
3260         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3261         {
3262                 surface = model->data_surfaces + surfaceindex;
3263                 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
3264                 for (i = 0;i < surface->num_triangles;i++)
3265                 {
3266                         triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
3267                         // calculate bounds of triangle
3268                         mins[0] = min(triangle->vertex[0][0], min(triangle->vertex[1][0], triangle->vertex[2][0]));
3269                         mins[1] = min(triangle->vertex[0][1], min(triangle->vertex[1][1], triangle->vertex[2][1]));
3270                         mins[2] = min(triangle->vertex[0][2], min(triangle->vertex[1][2], triangle->vertex[2][2]));
3271                         maxs[0] = max(triangle->vertex[0][0], max(triangle->vertex[1][0], triangle->vertex[2][0]));
3272                         maxs[1] = max(triangle->vertex[0][1], max(triangle->vertex[1][1], triangle->vertex[2][1]));
3273                         maxs[2] = max(triangle->vertex[0][2], max(triangle->vertex[1][2], triangle->vertex[2][2]));
3274                         // pick an axial projection based on the shortest dimension of the
3275                         // axially aligned bounding box, this is almost equivalent to
3276                         // calculating a triangle normal and classifying its primary axis.
3277                         //
3278                         // one difference is that this method can pick a workable
3279                         // projection axis even for a degenerate triangle whose only shape
3280                         // is a line (where the chosen projection will always map the line
3281                         // to non-zero coordinates in texture space)
3282                         VectorSubtract(maxs, mins, aabbsize);
3283                         axis = 0;
3284                         if (aabbsize[1] < aabbsize[axis])
3285                                 axis = 1;
3286                         if (aabbsize[2] < aabbsize[axis])
3287                                 axis = 2;
3288                         triangle->axis = axis;
3289                 }
3290         }
3291 }
3292
3293 static void Mod_GenerateLightmaps_CreateLightmaps(dp_model_t *model)
3294 {
3295         msurface_t *surface;
3296         int surfaceindex;
3297         int lightmapindex;
3298         int lightmapnumber;
3299         int i;
3300         int j;
3301         int k;
3302         int x;
3303         int y;
3304         int retry;
3305         int pixeloffset;
3306         int row_numpoints;
3307         int column_numpoints;
3308         float f;
3309         float row_plane[3];
3310         float column_plane[3];
3311         float trianglenormal[3];
3312         float clipbuf[5][8][3];
3313         float samplecenter[3];
3314         float samplenormal[3];
3315         float mins[3];
3316         float lmscalepixels;
3317         float lmmins;
3318         float lmmaxs;
3319         float lm_basescalepixels;
3320         int lm_borderpixels;
3321         int lm_texturesize;
3322         int lm_maxpixels;
3323         const int *e;
3324         lightmaptriangle_t *triangle;
3325         unsigned char *lightmappixels;
3326         unsigned char *deluxemappixels;
3327         mod_alloclightmap_state_t lmstate;
3328
3329         // generate lightmap projection information for all triangles
3330         if (model->texturepool == NULL)
3331                 model->texturepool = R_AllocTexturePool();
3332         lm_basescalepixels = 1.0f / max(0.0001f, mod_generatelightmaps_unitspersample.value);
3333         lm_borderpixels = mod_generatelightmaps_borderpixels.integer;
3334         lm_texturesize = bound(lm_borderpixels*2+1, 64, gl_max_texture_size);
3335         lm_maxpixels = lm_texturesize-(lm_borderpixels*2+1);
3336         Mod_AllocLightmap_Init(&lmstate, lm_texturesize, lm_texturesize);
3337         lightmapnumber = 0;
3338         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3339         {
3340                 surface = model->data_surfaces + surfaceindex;
3341                 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
3342                 lmscalepixels = lm_basescalepixels;
3343                 for (retry = 0;retry < 30;retry++)
3344                 {
3345                         // after a couple failed attempts, degrade quality to make it fit
3346                         if (retry > 1)
3347                                 lmscalepixels *= 0.5f;
3348                         for (i = 0;i < surface->num_triangles;i++)
3349                         {
3350                                 triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
3351                                 triangle->lightmapindex = lightmapnumber;
3352                                 // calculate lightmap bounds in 3D pixel coordinates, limit size,
3353                                 // pick two planar axes for projection
3354                                 // lightmap coordinates here are in pixels
3355                                 // lightmap projections are snapped to pixel grid explicitly, such
3356                                 // that two neighboring triangles sharing an edge and projection
3357                                 // axis will have identical sampl espacing along their shared edge
3358                                 k = 0;
3359                                 for (j = 0;j < 3;j++)
3360                                 {
3361                                         if (j == triangle->axis)
3362                                                 continue;
3363                                         lmmins = floor(mins[j]*lmscalepixels)-lm_borderpixels;
3364                                         lmmaxs = floor(mins[j]*lmscalepixels)+lm_borderpixels;
3365                                         triangle->lmsize[k] = (int)(lmmaxs-lmmins);
3366                                         triangle->lmbase[k] = lmmins/lmscalepixels;
3367                                         triangle->lmscale[k] = lmscalepixels;
3368                                         k++;
3369                                 }
3370                                 if (!Mod_AllocLightmap_Block(&lmstate, triangle->lmsize[0], triangle->lmsize[1], &triangle->lmoffset[0], &triangle->lmoffset[1]))
3371                                         break;
3372                         }
3373                         // if all fit in this texture, we're done with this surface
3374                         if (i == surface->num_triangles)
3375                                 break;
3376                         // if we haven't maxed out the lightmap size yet, we retry the
3377                         // entire surface batch...
3378                         if (lm_texturesize * 2 <= min(mod_generatelightmaps_texturesize.integer, gl_max_texture_size))
3379                         {
3380                                 lm_texturesize *= 2;
3381                                 surfaceindex = -1;
3382                                 lightmapnumber = 0;
3383                                 Mod_AllocLightmap_Free(&lmstate);
3384                                 Mod_AllocLightmap_Init(&lmstate, lm_texturesize, lm_texturesize);
3385                                 break;
3386                         }
3387                         // if we have maxed out the lightmap size, and this triangle does
3388                         // not fit in the same texture as the rest of the surface, we have
3389                         // to retry the entire surface in a new texture (can only use one)
3390                         // with multiple retries, the lightmap quality degrades until it
3391                         // fits (or gives up)
3392                         if (surfaceindex > 0)
3393                                 lightmapnumber++;
3394                         Mod_AllocLightmap_Reset(&lmstate);
3395                 }
3396         }
3397         lightmapnumber++;
3398         Mod_AllocLightmap_Free(&lmstate);
3399
3400         // now together lightmap textures
3401         model->brushq3.num_mergedlightmaps = lightmapnumber;
3402         model->brushq3.data_lightmaps = Mem_Alloc(model->mempool, model->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
3403         model->brushq3.data_deluxemaps = Mem_Alloc(model->mempool, model->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
3404         lightmappixels = Mem_Alloc(tempmempool, model->brushq3.num_mergedlightmaps * lm_texturesize * lm_texturesize * 4);
3405         deluxemappixels = Mem_Alloc(tempmempool, model->brushq3.num_mergedlightmaps * lm_texturesize * lm_texturesize * 4);
3406         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3407         {
3408                 surface = model->data_surfaces + surfaceindex;
3409                 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
3410                 for (i = 0;i < surface->num_triangles;i++)
3411                 {
3412                         triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
3413                         VectorClear(row_plane);
3414                         VectorClear(column_plane);
3415                         row_plane[triangle->axis] = 1.0f;
3416                         column_plane[!triangle->axis] = 1.0f;
3417 #if 0
3418                         switch (axis)
3419                         {
3420                         default:
3421                         case 0:
3422                                 forward[0] = 0;
3423                                 forward[1] = 1.0f / triangle->lmscale[0];
3424                                 forward[2] = 0;
3425                                 left[0] = 0;
3426                                 left[1] = 0;
3427                                 left[2] = 1.0f / triangle->lmscale[1];
3428                                 up[0] = 1.0f;
3429                                 up[1] = 0;
3430                                 up[2] = 0;
3431                                 origin[0] = 0;
3432                                 origin[1] = triangle->lmbase[0];
3433                                 origin[2] = triangle->lmbase[1];
3434                                 break;
3435                         case 1:
3436                                 forward[0] = 1.0f / triangle->lmscale[0];
3437                                 forward[1] = 0;
3438                                 forward[2] = 0;
3439                                 left[0] = 0;
3440                                 left[1] = 0;
3441                                 left[2] = 1.0f / triangle->lmscale[1];
3442                                 up[0] = 0;
3443                                 up[1] = 1.0f;
3444                                 up[2] = 0;
3445                                 origin[0] = triangle->lmbase[0];
3446                                 origin[1] = 0;
3447                                 origin[2] = triangle->lmbase[1];
3448                                 break;
3449                         case 2:
3450                                 forward[0] = 1.0f / triangle->lmscale[0];
3451                                 forward[1] = 0;
3452                                 forward[2] = 0;
3453                                 left[0] = 0;
3454                                 left[1] = 1.0f / triangle->lmscale[1];
3455                                 left[2] = 0;
3456                                 up[0] = 0;
3457                                 up[1] = 0;
3458                                 up[2] = 1.0f;
3459                                 origin[0] = triangle->lmbase[0];
3460                                 origin[1] = triangle->lmbase[1];
3461                                 origin[2] = 0;
3462                                 break;
3463                         }
3464                         Matrix4x4_FromVectors(&backmatrix, forward, left, up, origin);
3465 #endif
3466 #define LM_DIST_EPSILON (1.0f / 32.0f)
3467                         TriangleNormal(triangle->vertex[0], triangle->vertex[1], triangle->vertex[2], trianglenormal);
3468                         VectorNormalize(trianglenormal);
3469                         PolygonF_QuadForPlane(clipbuf[0][0], trianglenormal[0], trianglenormal[1], trianglenormal[2], DotProduct(trianglenormal, triangle->vertex[0]), model->radius * 2);
3470                         VectorCopy(trianglenormal, samplenormal); // FIXME!
3471                         for (y = 0;y < triangle->lmsize[1];y++)
3472                         {
3473                                 row_numpoints = PolygonF_Clip(4            , clipbuf[0][0],  row_plane[0],  row_plane[1],  row_plane[2],   triangle->lmbase[1] +  y    / triangle->lmscale[1] , LM_DIST_EPSILON, 8, clipbuf[1][0]);
3474                                 if (!row_numpoints)
3475                                         continue;
3476                                 row_numpoints = PolygonF_Clip(row_numpoints, clipbuf[1][0], -row_plane[0], -row_plane[1], -row_plane[2], -(triangle->lmbase[1] + (y+1) / triangle->lmscale[1]), LM_DIST_EPSILON, 8, clipbuf[2][0]);
3477                                 if (!row_numpoints)
3478                                         continue;
3479                                 pixeloffset = triangle->lightmapindex * lm_texturesize * lm_texturesize * 4 + (y+triangle->lmoffset[1]) * lm_texturesize * 4 + triangle->lmoffset[0] * 4;
3480                                 for (x = 0;x < triangle->lmsize[0];x++, pixeloffset += 4)
3481                                 {
3482                                         column_numpoints = PolygonF_Clip(row_numpoints   , clipbuf[2][0],  column_plane[0],  column_plane[1],  column_plane[2],   triangle->lmbase[0] +  x    / triangle->lmscale[0] , LM_DIST_EPSILON, 8, clipbuf[3][0]);
3483                                         if (!column_numpoints)
3484                                                 continue;
3485                                         column_numpoints = PolygonF_Clip(column_numpoints, clipbuf[3][0], -column_plane[0], -column_plane[1], -column_plane[2], -(triangle->lmbase[0] + (x+1) / triangle->lmscale[0]), LM_DIST_EPSILON, 8, clipbuf[4][0]);
3486                                         if (!column_numpoints)
3487                                                 continue;
3488                                         // we now have a polygon fragment in clipbuf[4], we can
3489                                         // sample its center or subdivide it further for
3490                                         // antialiasing
3491                                         VectorClear(samplecenter);
3492                                         for (j = 0;j < column_numpoints;j++)
3493                                                 VectorAdd(samplecenter, clipbuf[4][j], samplecenter);
3494                                         f = 1.0f / column_numpoints;
3495                                         VectorScale(samplecenter, f, samplecenter);
3496                                         VectorMA(samplecenter, 0.125f, trianglenormal, samplecenter);
3497                                         Mod_GenerateLightmaps_LightmapSample(samplecenter, samplenormal, lightmappixels + pixeloffset, deluxemappixels + pixeloffset);
3498                                 }
3499                         }
3500                 }
3501         }
3502
3503         for (lightmapindex = 0;lightmapindex < model->brushq3.num_mergedlightmaps;lightmapindex++)
3504         {
3505                 model->brushq3.data_lightmaps[lightmapindex] = R_LoadTexture2D(model->texturepool, va("lightmap%i", lightmapindex), lm_texturesize, lm_texturesize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_PRECACHE, NULL);
3506                 model->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(model->texturepool, va("deluxemap%i", lightmapindex), lm_texturesize, lm_texturesize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_PRECACHE, NULL);
3507         }
3508
3509         if (lightmappixels)
3510                 Mem_Free(lightmappixels);
3511         if (deluxemappixels)
3512                 Mem_Free(deluxemappixels);
3513
3514         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3515         {
3516                 surface = model->data_surfaces + surfaceindex;
3517                 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
3518                 if (!surface->num_triangles)
3519                         continue;
3520                 lightmapindex = mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle].lightmapindex;
3521                 surface->lightmaptexture = model->brushq3.data_lightmaps[lightmapindex];
3522                 surface->deluxemaptexture = model->brushq3.data_deluxemaps[lightmapindex];
3523         }
3524 }
3525
3526 static void Mod_GenerateLightmaps_UpdateVertexColors(dp_model_t *model)
3527 {
3528         int i;
3529         for (i = 0;i < model->surfmesh.num_vertices;i++)
3530                 Mod_GenerateLightmaps_VertexSample(model->surfmesh.data_vertex3f + 3*i, model->surfmesh.data_normal3f + 3*i, model->surfmesh.data_lightmapcolor4f + 4*i);
3531 }
3532
3533 static void Mod_GenerateLightmaps_UpdateLightGrid(dp_model_t *model)
3534 {
3535         int x;
3536         int y;
3537         int z;
3538         int index = 0;
3539         float pos[3];
3540         for (z = 0;z < model->brushq3.num_lightgrid_isize[2];z++)
3541         {
3542                 pos[2] = (model->brushq3.num_lightgrid_imins[2] + z + 0.5f) * model->brushq3.num_lightgrid_cellsize[2];
3543                 for (y = 0;y < model->brushq3.num_lightgrid_isize[1];y++)
3544                 {
3545                         pos[1] = (model->brushq3.num_lightgrid_imins[1] + y + 0.5f) * model->brushq3.num_lightgrid_cellsize[1];
3546                         for (x = 0;x < model->brushq3.num_lightgrid_isize[0];x++, index++)
3547                         {
3548                                 pos[0] = (model->brushq3.num_lightgrid_imins[0] + x + 0.5f) * model->brushq3.num_lightgrid_cellsize[0];
3549                                 Mod_GenerateLightmaps_GridSample(pos, model->brushq3.data_lightgrid + index);
3550                         }
3551                 }
3552         }
3553 }
3554
3555 extern cvar_t mod_q3bsp_nolightmaps;
3556 static void Mod_GenerateLightmaps(dp_model_t *model)
3557 {
3558         //lightmaptriangle_t *lightmaptriangles = Mem_Alloc(model->mempool, model->surfmesh.num_triangles * sizeof(lightmaptriangle_t));
3559         dp_model_t *oldloadmodel = loadmodel;
3560         loadmodel = model;
3561
3562         Mod_GenerateLightmaps_DestroyLightmaps(model);
3563         Mod_GenerateLightmaps_UnweldTriangles(model);
3564         Mod_GenerateLightmaps_CreateTriangleInformation(model);
3565         Mod_GenerateLightmaps_ClassifyTriangles(model);
3566         if(!mod_q3bsp_nolightmaps.integer)
3567                 Mod_GenerateLightmaps_CreateLightmaps(model);
3568         Mod_GenerateLightmaps_UpdateVertexColors(model);
3569         Mod_GenerateLightmaps_UpdateLightGrid(model);
3570 #if 0
3571         // stage 1:
3572         // first step is deleting the lightmaps
3573         for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3574         {
3575                 surface = model->data_surfaces + surfaceindex;
3576                 surface->lightmap = NULL;
3577                 surface->deluxemap = NULL;
3578                 // add a sample for each vertex of surface
3579                 for (i = 0, vertexindex = surface->num_firstvertex;i < surface->num_vertices;i++, vertexindex++)
3580                         Mod_GenerateLightmaps_AddSample(model->surfmesh.data_vertex3f + 3*vertexindex, model->surfmesh.data_normal3f + 3*vertexindex, model->surfmesh.data_lightmapcolor4f + 4*vertexindex, NULL, NULL);
3581                 // generate lightmaptriangle_t for each triangle of surface
3582                 for (i = 0, triangleindex = surface->num_firstvertex;i < surface->num_triangles;i++, triangleindex++)
3583                 {
3584         }
3585 #endif
3586
3587         if (mod_generatelightmaps_lightmaptriangles)
3588                 Mem_Free(mod_generatelightmaps_lightmaptriangles);
3589         mod_generatelightmaps_lightmaptriangles = NULL;
3590
3591         loadmodel = oldloadmodel;
3592 }
3593
3594 static void Mod_GenerateLightmaps_f(void)
3595 {
3596         if (Cmd_Argc() != 1)
3597         {
3598                 Con_Printf("usage: mod_generatelightmaps\n");
3599                 return;
3600         }
3601         if (!cl.worldmodel)
3602         {
3603                 Con_Printf("no worldmodel loaded\n");
3604                 return;
3605         }
3606         Mod_GenerateLightmaps(cl.worldmodel);
3607 }