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