2 Copyright (C) 1996-1997 Id Software, Inc.
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.
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.
13 See the GNU General Public License for more details.
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.
20 // models.c -- model loading and caching
22 // models are the only shared resource between a client and server running
23 // on the same machine.
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"};
35 dp_model_t *loadmodel;
37 static mempool_t *mod_mempool;
38 static memexpandablearray_t models;
40 static mempool_t* q3shaders_mem;
41 typedef struct q3shader_hash_entry_s
43 q3shaderinfo_t shader;
44 struct q3shader_hash_entry_s* chain;
45 } q3shader_hash_entry_t;
46 #define Q3SHADER_HASH_SIZE 1021
47 typedef struct q3shader_data_s
49 memexpandablearray_t hash_entries;
50 q3shader_hash_entry_t hash[Q3SHADER_HASH_SIZE];
51 memexpandablearray_t char_ptrs;
53 static q3shader_data_t* q3shader_data;
55 static void mod_start(void)
58 int nummodels = Mem_ExpandableArray_IndexRange(&models);
61 SCR_PushLoadingScreen(false, "Loading models", 1.0);
63 for (i = 0;i < nummodels;i++)
64 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
67 for (i = 0;i < nummodels;i++)
68 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
71 SCR_PushLoadingScreen(true, mod->name, 1.0 / count);
72 Mod_LoadModel(mod, true, false);
73 SCR_PopLoadingScreen(false);
75 SCR_PopLoadingScreen(false);
78 static void mod_shutdown(void)
81 int nummodels = Mem_ExpandableArray_IndexRange(&models);
84 for (i = 0;i < nummodels;i++)
85 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && (mod->loaded || mod->mempool))
91 static void mod_newmap(void)
94 int i, j, k, surfacenum, ssize, tsize;
95 int nummodels = Mem_ExpandableArray_IndexRange(&models);
98 for (i = 0;i < nummodels;i++)
100 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool)
102 for (j = 0;j < mod->num_textures && mod->data_textures;j++)
104 for (k = 0;k < mod->data_textures[j].numskinframes;k++)
105 R_SkinFrame_MarkUsed(mod->data_textures[j].skinframes[k]);
106 for (k = 0;k < mod->data_textures[j].backgroundnumskinframes;k++)
107 R_SkinFrame_MarkUsed(mod->data_textures[j].backgroundskinframes[k]);
109 if (mod->brush.solidskyskinframe)
110 R_SkinFrame_MarkUsed(mod->brush.solidskyskinframe);
111 if (mod->brush.alphaskyskinframe)
112 R_SkinFrame_MarkUsed(mod->brush.alphaskyskinframe);
116 if (!cl_stainmaps_clearonload.integer)
119 for (i = 0;i < nummodels;i++)
121 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->mempool && mod->data_surfaces)
123 for (surfacenum = 0, surface = mod->data_surfaces;surfacenum < mod->num_surfaces;surfacenum++, surface++)
125 if (surface->lightmapinfo && surface->lightmapinfo->stainsamples)
127 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
128 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
129 memset(surface->lightmapinfo->stainsamples, 255, ssize * tsize * 3);
130 mod->brushq1.lightmapupdateflags[surfacenum] = true;
142 static void Mod_Print(void);
143 static void Mod_Precache (void);
144 static void Mod_Decompile_f(void);
145 static void Mod_BuildVBOs(void);
146 static void Mod_GenerateLightmaps_f(void);
149 mod_mempool = Mem_AllocPool("modelinfo", 0, NULL);
150 Mem_ExpandableArray_NewArray(&models, mod_mempool, sizeof(dp_model_t), 16);
156 Cvar_RegisterVariable(&r_mipskins);
157 Cvar_RegisterVariable(&mod_generatelightmaps_unitspersample);
158 Cvar_RegisterVariable(&mod_generatelightmaps_borderpixels);
159 Cvar_RegisterVariable(&mod_generatelightmaps_texturesize);
160 Cmd_AddCommand ("modellist", Mod_Print, "prints a list of loaded models");
161 Cmd_AddCommand ("modelprecache", Mod_Precache, "load a model");
162 Cmd_AddCommand ("modeldecompile", Mod_Decompile_f, "exports a model in several formats for editing purposes");
163 Cmd_AddCommand ("mod_generatelightmaps", Mod_GenerateLightmaps_f, "rebuilds lighting on current worldmodel");
166 void Mod_RenderInit(void)
168 R_RegisterModule("Models", mod_start, mod_shutdown, mod_newmap);
171 void Mod_UnloadModel (dp_model_t *mod)
173 char name[MAX_QPATH];
175 dp_model_t *parentmodel;
177 if (developer_loading.integer)
178 Con_Printf("unloading model %s\n", mod->name);
180 strlcpy(name, mod->name, sizeof(name));
181 parentmodel = mod->brush.parentmodel;
183 if (mod->surfmesh.ebo3i)
184 R_Mesh_DestroyBufferObject(mod->surfmesh.ebo3i);
185 if (mod->surfmesh.ebo3s)
186 R_Mesh_DestroyBufferObject(mod->surfmesh.ebo3s);
187 if (mod->surfmesh.vbo)
188 R_Mesh_DestroyBufferObject(mod->surfmesh.vbo);
189 // free textures/memory attached to the model
190 R_FreeTexturePool(&mod->texturepool);
191 Mem_FreePool(&mod->mempool);
192 // clear the struct to make it available
193 memset(mod, 0, sizeof(dp_model_t));
194 // restore the fields we want to preserve
195 strlcpy(mod->name, name, sizeof(mod->name));
196 mod->brush.parentmodel = parentmodel;
201 void R_Model_Null_Draw(entity_render_t *ent)
207 typedef void (*mod_framegroupify_parsegroups_t) (unsigned int i, int start, int len, float fps, qboolean loop, void *pass);
209 int Mod_FrameGroupify_ParseGroups(const char *buf, mod_framegroupify_parsegroups_t cb, void *pass)
222 if (!COM_ParseToken_Simple(&bufptr, true, false))
224 if (!strcmp(com_token, "\n"))
225 continue; // empty line
226 start = atoi(com_token);
227 if (!COM_ParseToken_Simple(&bufptr, true, false))
229 if (!strcmp(com_token, "\n"))
231 Con_Printf("framegroups file: missing number of frames\n");
234 len = atoi(com_token);
235 if (!COM_ParseToken_Simple(&bufptr, true, false))
237 // we default to looping as it's usually wanted, so to NOT loop you append a 0
238 if (strcmp(com_token, "\n"))
240 fps = atof(com_token);
241 if (!COM_ParseToken_Simple(&bufptr, true, false))
243 if (strcmp(com_token, "\n"))
244 loop = atoi(com_token) != 0;
255 cb(i, start, len, fps, loop, pass);
262 void Mod_FrameGroupify_ParseGroups_Count (unsigned int i, int start, int len, float fps, qboolean loop, void *pass)
264 unsigned int *cnt = (unsigned int *) pass;
268 void Mod_FrameGroupify_ParseGroups_Store (unsigned int i, int start, int len, float fps, qboolean loop, void *pass)
270 dp_model_t *mod = (dp_model_t *) pass;
271 animscene_t *anim = &mod->animscenes[i];
272 dpsnprintf(anim->name, sizeof(anim[i].name), "groupified_%d", i);
273 anim->firstframe = bound(0, start, mod->num_poses - 1);
274 anim->framecount = bound(1, len, mod->num_poses - anim->firstframe);
275 anim->framerate = max(1, fps);
277 //Con_Printf("frame group %d is %d %d %f %d\n", i, start, len, fps, loop);
280 void Mod_FrameGroupify(dp_model_t *mod, const char *buf)
285 cnt = Mod_FrameGroupify_ParseGroups(buf, NULL, NULL);
288 Con_Printf("no scene found in framegroups file, aborting\n");
291 mod->numframes = cnt;
294 // (we do not free the previous animscenes, but model unloading will free the pool owning them, so it's okay)
295 mod->animscenes = (animscene_t *) Mem_Alloc(mod->mempool, sizeof(animscene_t) * mod->numframes);
298 Mod_FrameGroupify_ParseGroups(buf, Mod_FrameGroupify_ParseGroups_Store, mod);
308 dp_model_t *Mod_LoadModel(dp_model_t *mod, qboolean crash, qboolean checkdisk)
313 fs_offset_t filesize;
317 if (mod->name[0] == '*') // submodel
320 if (!strcmp(mod->name, "null"))
325 if (mod->loaded || mod->mempool)
326 Mod_UnloadModel(mod);
328 if (developer_loading.integer)
329 Con_Printf("loading model %s\n", mod->name);
332 mod->crc = (unsigned int)-1;
335 VectorClear(mod->normalmins);
336 VectorClear(mod->normalmaxs);
337 VectorClear(mod->yawmins);
338 VectorClear(mod->yawmaxs);
339 VectorClear(mod->rotatedmins);
340 VectorClear(mod->rotatedmaxs);
342 mod->modeldatatypestring = "null";
343 mod->type = mod_null;
344 mod->Draw = R_Model_Null_Draw;
348 // no fatal errors occurred, so this model is ready to use.
357 // even if the model is loaded it still may need reloading...
359 // if it is not loaded or checkdisk is true we need to calculate the crc
360 if (!mod->loaded || checkdisk)
362 if (checkdisk && mod->loaded)
363 Con_DPrintf("checking model %s\n", mod->name);
364 buf = FS_LoadFile (mod->name, tempmempool, false, &filesize);
367 crc = CRC_Block((unsigned char *)buf, filesize);
368 // we need to reload the model if the crc does not match
374 // if the model is already loaded and checks passed, just return
382 if (developer_loading.integer)
383 Con_Printf("loading model %s\n", mod->name);
385 SCR_PushLoadingScreen(true, mod->name, 1);
387 // LordHavoc: unload the existing model in this slot (if there is one)
388 if (mod->loaded || mod->mempool)
389 Mod_UnloadModel(mod);
394 // errors can prevent the corresponding mod->loaded = true;
397 // default model radius and bounding box (mainly for missing models)
399 VectorSet(mod->normalmins, -mod->radius, -mod->radius, -mod->radius);
400 VectorSet(mod->normalmaxs, mod->radius, mod->radius, mod->radius);
401 VectorSet(mod->yawmins, -mod->radius, -mod->radius, -mod->radius);
402 VectorSet(mod->yawmaxs, mod->radius, mod->radius, mod->radius);
403 VectorSet(mod->rotatedmins, -mod->radius, -mod->radius, -mod->radius);
404 VectorSet(mod->rotatedmaxs, mod->radius, mod->radius, mod->radius);
408 // load q3 shaders for the first time, or after a level change
414 char *bufend = (char *)buf + filesize;
416 // all models use memory, so allocate a memory pool
417 mod->mempool = Mem_AllocPool(mod->name, 0, NULL);
419 num = LittleLong(*((int *)buf));
420 // call the apropriate loader
422 if (!strcasecmp(FS_FileExtension(mod->name), "obj")) Mod_OBJ_Load(mod, buf, bufend);
423 else if (!memcmp(buf, "IDPO", 4)) Mod_IDP0_Load(mod, buf, bufend);
424 else if (!memcmp(buf, "IDP2", 4)) Mod_IDP2_Load(mod, buf, bufend);
425 else if (!memcmp(buf, "IDP3", 4)) Mod_IDP3_Load(mod, buf, bufend);
426 else if (!memcmp(buf, "IDSP", 4)) Mod_IDSP_Load(mod, buf, bufend);
427 else if (!memcmp(buf, "IDS2", 4)) Mod_IDS2_Load(mod, buf, bufend);
428 else if (!memcmp(buf, "IBSP", 4)) Mod_IBSP_Load(mod, buf, bufend);
429 else if (!memcmp(buf, "ZYMOTICMODEL", 12)) Mod_ZYMOTICMODEL_Load(mod, buf, bufend);
430 else if (!memcmp(buf, "DARKPLACESMODEL", 16)) Mod_DARKPLACESMODEL_Load(mod, buf, bufend);
431 else if (!memcmp(buf, "ACTRHEAD", 8)) Mod_PSKMODEL_Load(mod, buf, bufend);
432 else if (strlen(mod->name) >= 4 && !strcmp(mod->name + strlen(mod->name) - 4, ".map")) Mod_MAP_Load(mod, buf, bufend);
433 else if (num == BSPVERSION || num == 30) Mod_Q1BSP_Load(mod, buf, bufend);
434 else Con_Printf("Mod_LoadModel: model \"%s\" is of unknown/unsupported type\n", mod->name);
437 buf = FS_LoadFile (va("%s.framegroups", mod->name), tempmempool, false, &filesize);
440 Mod_FrameGroupify(mod, (const char *)buf);
448 // LordHavoc: Sys_Error was *ANNOYING*
449 Con_Printf ("Mod_LoadModel: %s not found\n", mod->name);
452 // no fatal errors occurred, so this model is ready to use.
455 SCR_PopLoadingScreen(false);
460 void Mod_ClearUsed(void)
463 int nummodels = Mem_ExpandableArray_IndexRange(&models);
465 for (i = 0;i < nummodels;i++)
466 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0])
470 void Mod_PurgeUnused(void)
473 int nummodels = Mem_ExpandableArray_IndexRange(&models);
475 for (i = 0;i < nummodels;i++)
477 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !mod->used)
479 Mod_UnloadModel(mod);
480 Mem_ExpandableArray_FreeRecord(&models, mod);
491 dp_model_t *Mod_FindName(const char *name, const char *parentname)
500 // if we're not dedicatd, the renderer calls will crash without video
503 nummodels = Mem_ExpandableArray_IndexRange(&models);
506 Host_Error ("Mod_ForName: NULL name");
508 // search the currently loaded models
509 for (i = 0;i < nummodels;i++)
511 if ((mod = (dp_model_t*) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && !strcmp(mod->name, name) && ((!mod->brush.parentmodel && !parentname[0]) || (mod->brush.parentmodel && parentname[0] && !strcmp(mod->brush.parentmodel->name, parentname))))
518 // no match found, create a new one
519 mod = (dp_model_t *) Mem_ExpandableArray_AllocRecord(&models);
520 strlcpy(mod->name, name, sizeof(mod->name));
522 mod->brush.parentmodel = Mod_FindName(parentname, NULL);
524 mod->brush.parentmodel = NULL;
534 Loads in a model for the given name
537 dp_model_t *Mod_ForName(const char *name, qboolean crash, qboolean checkdisk, const char *parentname)
540 model = Mod_FindName(name, parentname);
541 if (!model->loaded || checkdisk)
542 Mod_LoadModel(model, crash, checkdisk);
550 Reloads all models if they have changed
553 void Mod_Reload(void)
556 int nummodels = Mem_ExpandableArray_IndexRange(&models);
559 SCR_PushLoadingScreen(false, "Reloading models", 1.0);
561 for (i = 0;i < nummodels;i++)
562 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
564 for (i = 0;i < nummodels;i++)
565 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*' && mod->used)
567 SCR_PushLoadingScreen(true, mod->name, 1.0 / count);
568 Mod_LoadModel(mod, true, true);
569 SCR_PopLoadingScreen(false);
571 SCR_PopLoadingScreen(false);
574 unsigned char *mod_base;
577 //=============================================================================
584 static void Mod_Print(void)
587 int nummodels = Mem_ExpandableArray_IndexRange(&models);
590 Con_Print("Loaded models:\n");
591 for (i = 0;i < nummodels;i++)
593 if ((mod = (dp_model_t *) Mem_ExpandableArray_RecordAtIndex(&models, i)) && mod->name[0] && mod->name[0] != '*')
595 if (mod->brush.numsubmodels)
596 Con_Printf("%4iK %s (%i submodels)\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name, mod->brush.numsubmodels);
598 Con_Printf("%4iK %s\n", mod->mempool ? (int)((mod->mempool->totalsize + 1023) / 1024) : 0, mod->name);
608 static void Mod_Precache(void)
611 Mod_ForName(Cmd_Argv(1), false, true, Cmd_Argv(1)[0] == '*' ? cl.model_name[1] : NULL);
613 Con_Print("usage: modelprecache <filename>\n");
616 int Mod_BuildVertexRemapTableFromElements(int numelements, const int *elements, int numvertices, int *remapvertices)
620 used = (unsigned char *)Mem_Alloc(tempmempool, numvertices);
621 memset(used, 0, numvertices);
622 for (i = 0;i < numelements;i++)
623 used[elements[i]] = 1;
624 for (i = 0, count = 0;i < numvertices;i++)
625 remapvertices[i] = used[i] ? count++ : -1;
631 // fast way, using an edge hash
632 #define TRIANGLEEDGEHASH 8192
633 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
635 int i, j, p, e1, e2, *n, hashindex, count, match;
637 typedef struct edgehashentry_s
639 struct edgehashentry_s *next;
644 edgehashentry_t *edgehash[TRIANGLEEDGEHASH], *edgehashentries, edgehashentriesbuffer[TRIANGLEEDGEHASH*3], *hash;
645 memset(edgehash, 0, sizeof(edgehash));
646 edgehashentries = edgehashentriesbuffer;
647 // if there are too many triangles for the stack array, allocate larger buffer
648 if (numtriangles > TRIANGLEEDGEHASH)
649 edgehashentries = (edgehashentry_t *)Mem_Alloc(tempmempool, numtriangles * 3 * sizeof(edgehashentry_t));
650 // find neighboring triangles
651 for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
653 for (j = 0, p = 2;j < 3;p = j, j++)
657 // this hash index works for both forward and backward edges
658 hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
659 hash = edgehashentries + i * 3 + j;
660 hash->next = edgehash[hashindex];
661 edgehash[hashindex] = hash;
663 hash->element[0] = e1;
664 hash->element[1] = e2;
667 for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
669 for (j = 0, p = 2;j < 3;p = j, j++)
673 // this hash index works for both forward and backward edges
674 hashindex = (unsigned int)(e1 + e2) % TRIANGLEEDGEHASH;
677 for (hash = edgehash[hashindex];hash;hash = hash->next)
679 if (hash->element[0] == e2 && hash->element[1] == e1)
681 if (hash->triangle != i)
682 match = hash->triangle;
685 else if ((hash->element[0] == e1 && hash->element[1] == e2))
688 // detect edges shared by three triangles and make them seams
694 // also send a keepalive here (this can take a while too!)
695 CL_KeepaliveMessage(false);
697 // free the allocated buffer
698 if (edgehashentries != edgehashentriesbuffer)
699 Mem_Free(edgehashentries);
702 // very slow but simple way
703 static int Mod_FindTriangleWithEdge(const int *elements, int numtriangles, int start, int end, int ignore)
708 for (i = 0;i < numtriangles;i++, elements += 3)
710 if ((elements[0] == start && elements[1] == end)
711 || (elements[1] == start && elements[2] == end)
712 || (elements[2] == start && elements[0] == end))
718 else if ((elements[1] == start && elements[0] == end)
719 || (elements[2] == start && elements[1] == end)
720 || (elements[0] == start && elements[2] == end))
723 // detect edges shared by three triangles and make them seams
729 void Mod_BuildTriangleNeighbors(int *neighbors, const int *elements, int numtriangles)
733 for (i = 0, e = elements, n = neighbors;i < numtriangles;i++, e += 3, n += 3)
735 n[0] = Mod_FindTriangleWithEdge(elements, numtriangles, e[1], e[0], i);
736 n[1] = Mod_FindTriangleWithEdge(elements, numtriangles, e[2], e[1], i);
737 n[2] = Mod_FindTriangleWithEdge(elements, numtriangles, e[0], e[2], i);
742 void Mod_ValidateElements(int *elements, int numtriangles, int firstvertex, int numverts, const char *filename, int fileline)
744 int i, warned = false, endvertex = firstvertex + numverts;
745 for (i = 0;i < numtriangles * 3;i++)
747 if (elements[i] < firstvertex || elements[i] >= endvertex)
752 Con_Printf("Mod_ValidateElements: out of bounds elements detected at %s:%d\n", filename, fileline);
754 elements[i] = firstvertex;
759 // warning: this is an expensive function!
760 void Mod_BuildNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const int *elements, float *normal3f, qboolean areaweighting)
767 memset(normal3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
768 // process each vertex of each triangle and accumulate the results
769 // use area-averaging, to make triangles with a big area have a bigger
770 // weighting on the vertex normal than triangles with a small area
771 // to do so, just add the 'normals' together (the bigger the area
772 // the greater the length of the normal is
774 for (i = 0; i < numtriangles; i++, element += 3)
777 vertex3f + element[0] * 3,
778 vertex3f + element[1] * 3,
779 vertex3f + element[2] * 3,
784 VectorNormalize(areaNormal);
786 for (j = 0;j < 3;j++)
788 vectorNormal = normal3f + element[j] * 3;
789 vectorNormal[0] += areaNormal[0];
790 vectorNormal[1] += areaNormal[1];
791 vectorNormal[2] += areaNormal[2];
794 // and just normalize the accumulated vertex normal in the end
795 vectorNormal = normal3f + 3 * firstvertex;
796 for (i = 0; i < numvertices; i++, vectorNormal += 3)
797 VectorNormalize(vectorNormal);
800 void Mod_BuildBumpVectors(const float *v0, const float *v1, const float *v2, const float *tc0, const float *tc1, const float *tc2, float *svector3f, float *tvector3f, float *normal3f)
802 float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
803 // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
804 // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
806 // 6 multiply, 9 subtract
807 VectorSubtract(v1, v0, v10);
808 VectorSubtract(v2, v0, v20);
809 normal3f[0] = v20[1] * v10[2] - v20[2] * v10[1];
810 normal3f[1] = v20[2] * v10[0] - v20[0] * v10[2];
811 normal3f[2] = v20[0] * v10[1] - v20[1] * v10[0];
812 // 12 multiply, 10 subtract
813 tc10[1] = tc1[1] - tc0[1];
814 tc20[1] = tc2[1] - tc0[1];
815 svector3f[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
816 svector3f[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
817 svector3f[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
818 tc10[0] = tc1[0] - tc0[0];
819 tc20[0] = tc2[0] - tc0[0];
820 tvector3f[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
821 tvector3f[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
822 tvector3f[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
823 // 12 multiply, 4 add, 6 subtract
824 f = DotProduct(svector3f, normal3f);
825 svector3f[0] -= f * normal3f[0];
826 svector3f[1] -= f * normal3f[1];
827 svector3f[2] -= f * normal3f[2];
828 f = DotProduct(tvector3f, normal3f);
829 tvector3f[0] -= f * normal3f[0];
830 tvector3f[1] -= f * normal3f[1];
831 tvector3f[2] -= f * normal3f[2];
832 // if texture is mapped the wrong way (counterclockwise), the tangents
833 // have to be flipped, this is detected by calculating a normal from the
834 // two tangents, and seeing if it is opposite the surface normal
835 // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
836 CrossProduct(tvector3f, svector3f, tangentcross);
837 if (DotProduct(tangentcross, normal3f) < 0)
839 VectorNegate(svector3f, svector3f);
840 VectorNegate(tvector3f, tvector3f);
844 // warning: this is a very expensive function!
845 void Mod_BuildTextureVectorsFromNormals(int firstvertex, int numvertices, int numtriangles, const float *vertex3f, const float *texcoord2f, const float *normal3f, const int *elements, float *svector3f, float *tvector3f, qboolean areaweighting)
848 float sdir[3], tdir[3], normal[3], *sv, *tv;
849 const float *v0, *v1, *v2, *tc0, *tc1, *tc2, *n;
850 float f, tangentcross[3], v10[3], v20[3], tc10[2], tc20[2];
853 memset(svector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
854 memset(tvector3f + 3 * firstvertex, 0, numvertices * sizeof(float[3]));
855 // process each vertex of each triangle and accumulate the results
856 for (tnum = 0, e = elements;tnum < numtriangles;tnum++, e += 3)
858 v0 = vertex3f + e[0] * 3;
859 v1 = vertex3f + e[1] * 3;
860 v2 = vertex3f + e[2] * 3;
861 tc0 = texcoord2f + e[0] * 2;
862 tc1 = texcoord2f + e[1] * 2;
863 tc2 = texcoord2f + e[2] * 2;
865 // 79 add/sub/negate/multiply (1 cycle), 1 compare (3 cycle?), total cycles not counting load/store/exchange roughly 82 cycles
866 // 6 add, 28 subtract, 39 multiply, 1 compare, 50% chance of 6 negates
868 // calculate the edge directions and surface normal
869 // 6 multiply, 9 subtract
870 VectorSubtract(v1, v0, v10);
871 VectorSubtract(v2, v0, v20);
872 normal[0] = v20[1] * v10[2] - v20[2] * v10[1];
873 normal[1] = v20[2] * v10[0] - v20[0] * v10[2];
874 normal[2] = v20[0] * v10[1] - v20[1] * v10[0];
876 // calculate the tangents
877 // 12 multiply, 10 subtract
878 tc10[1] = tc1[1] - tc0[1];
879 tc20[1] = tc2[1] - tc0[1];
880 sdir[0] = tc10[1] * v20[0] - tc20[1] * v10[0];
881 sdir[1] = tc10[1] * v20[1] - tc20[1] * v10[1];
882 sdir[2] = tc10[1] * v20[2] - tc20[1] * v10[2];
883 tc10[0] = tc1[0] - tc0[0];
884 tc20[0] = tc2[0] - tc0[0];
885 tdir[0] = tc10[0] * v20[0] - tc20[0] * v10[0];
886 tdir[1] = tc10[0] * v20[1] - tc20[0] * v10[1];
887 tdir[2] = tc10[0] * v20[2] - tc20[0] * v10[2];
889 // if texture is mapped the wrong way (counterclockwise), the tangents
890 // have to be flipped, this is detected by calculating a normal from the
891 // two tangents, and seeing if it is opposite the surface normal
892 // 9 multiply, 2 add, 3 subtract, 1 compare, 50% chance of: 6 negates
893 CrossProduct(tdir, sdir, tangentcross);
894 if (DotProduct(tangentcross, normal) < 0)
896 VectorNegate(sdir, sdir);
897 VectorNegate(tdir, tdir);
902 VectorNormalize(sdir);
903 VectorNormalize(tdir);
905 for (i = 0;i < 3;i++)
907 VectorAdd(svector3f + e[i]*3, sdir, svector3f + e[i]*3);
908 VectorAdd(tvector3f + e[i]*3, tdir, tvector3f + e[i]*3);
911 // make the tangents completely perpendicular to the surface normal, and
912 // then normalize them
913 // 16 assignments, 2 divide, 2 sqrt, 2 negates, 14 adds, 24 multiplies
914 for (i = 0, sv = svector3f + 3 * firstvertex, tv = tvector3f + 3 * firstvertex, n = normal3f + 3 * firstvertex;i < numvertices;i++, sv += 3, tv += 3, n += 3)
916 f = -DotProduct(sv, n);
917 VectorMA(sv, f, n, sv);
919 f = -DotProduct(tv, n);
920 VectorMA(tv, f, n, tv);
925 void Mod_AllocSurfMesh(mempool_t *mempool, int numvertices, int numtriangles, qboolean lightmapoffsets, qboolean vertexcolors, qboolean neighbors)
928 data = (unsigned char *)Mem_Alloc(mempool, numvertices * (3 + 3 + 3 + 3 + 2 + 2 + (vertexcolors ? 4 : 0)) * sizeof(float) + numvertices * (lightmapoffsets ? 1 : 0) * sizeof(int) + numtriangles * (3 + (neighbors ? 3 : 0)) * sizeof(int) + (numvertices <= 65536 ? numtriangles * sizeof(unsigned short[3]) : 0));
929 loadmodel->surfmesh.num_vertices = numvertices;
930 loadmodel->surfmesh.num_triangles = numtriangles;
931 if (loadmodel->surfmesh.num_vertices)
933 loadmodel->surfmesh.data_vertex3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
934 loadmodel->surfmesh.data_svector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
935 loadmodel->surfmesh.data_tvector3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
936 loadmodel->surfmesh.data_normal3f = (float *)data, data += sizeof(float[3]) * loadmodel->surfmesh.num_vertices;
937 loadmodel->surfmesh.data_texcoordtexture2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
938 loadmodel->surfmesh.data_texcoordlightmap2f = (float *)data, data += sizeof(float[2]) * loadmodel->surfmesh.num_vertices;
940 loadmodel->surfmesh.data_lightmapcolor4f = (float *)data, data += sizeof(float[4]) * loadmodel->surfmesh.num_vertices;
942 loadmodel->surfmesh.data_lightmapoffsets = (int *)data, data += sizeof(int) * loadmodel->surfmesh.num_vertices;
944 if (loadmodel->surfmesh.num_triangles)
946 loadmodel->surfmesh.data_element3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
948 loadmodel->surfmesh.data_neighbor3i = (int *)data, data += sizeof(int[3]) * loadmodel->surfmesh.num_triangles;
949 if (loadmodel->surfmesh.num_vertices <= 65536)
950 loadmodel->surfmesh.data_element3s = (unsigned short *)data, data += sizeof(unsigned short[3]) * loadmodel->surfmesh.num_triangles;
954 shadowmesh_t *Mod_ShadowMesh_Alloc(mempool_t *mempool, int maxverts, int maxtriangles, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, int light, int neighbors, int expandable)
956 shadowmesh_t *newmesh;
959 size = sizeof(shadowmesh_t);
960 size += maxverts * sizeof(float[3]);
962 size += maxverts * sizeof(float[11]);
963 size += maxtriangles * sizeof(int[3]);
964 if (maxverts <= 65536)
965 size += maxtriangles * sizeof(unsigned short[3]);
967 size += maxtriangles * sizeof(int[3]);
969 size += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *) + maxverts * sizeof(shadowmeshvertexhash_t);
970 data = (unsigned char *)Mem_Alloc(mempool, size);
971 newmesh = (shadowmesh_t *)data;data += sizeof(*newmesh);
972 newmesh->map_diffuse = map_diffuse;
973 newmesh->map_specular = map_specular;
974 newmesh->map_normal = map_normal;
975 newmesh->maxverts = maxverts;
976 newmesh->maxtriangles = maxtriangles;
977 newmesh->numverts = 0;
978 newmesh->numtriangles = 0;
979 memset(newmesh->sideoffsets, 0, sizeof(newmesh->sideoffsets));
980 memset(newmesh->sidetotals, 0, sizeof(newmesh->sidetotals));
982 newmesh->vertex3f = (float *)data;data += maxverts * sizeof(float[3]);
985 newmesh->svector3f = (float *)data;data += maxverts * sizeof(float[3]);
986 newmesh->tvector3f = (float *)data;data += maxverts * sizeof(float[3]);
987 newmesh->normal3f = (float *)data;data += maxverts * sizeof(float[3]);
988 newmesh->texcoord2f = (float *)data;data += maxverts * sizeof(float[2]);
990 newmesh->element3i = (int *)data;data += maxtriangles * sizeof(int[3]);
993 newmesh->neighbor3i = (int *)data;data += maxtriangles * sizeof(int[3]);
997 newmesh->vertexhashtable = (shadowmeshvertexhash_t **)data;data += SHADOWMESHVERTEXHASH * sizeof(shadowmeshvertexhash_t *);
998 newmesh->vertexhashentries = (shadowmeshvertexhash_t *)data;data += maxverts * sizeof(shadowmeshvertexhash_t);
1000 if (maxverts <= 65536)
1001 newmesh->element3s = (unsigned short *)data;data += maxtriangles * sizeof(unsigned short[3]);
1005 shadowmesh_t *Mod_ShadowMesh_ReAlloc(mempool_t *mempool, shadowmesh_t *oldmesh, int light, int neighbors)
1007 shadowmesh_t *newmesh;
1008 newmesh = Mod_ShadowMesh_Alloc(mempool, oldmesh->numverts, oldmesh->numtriangles, oldmesh->map_diffuse, oldmesh->map_specular, oldmesh->map_normal, light, neighbors, false);
1009 newmesh->numverts = oldmesh->numverts;
1010 newmesh->numtriangles = oldmesh->numtriangles;
1011 memcpy(newmesh->sideoffsets, oldmesh->sideoffsets, sizeof(oldmesh->sideoffsets));
1012 memcpy(newmesh->sidetotals, oldmesh->sidetotals, sizeof(oldmesh->sidetotals));
1014 memcpy(newmesh->vertex3f, oldmesh->vertex3f, oldmesh->numverts * sizeof(float[3]));
1015 if (newmesh->svector3f && oldmesh->svector3f)
1017 memcpy(newmesh->svector3f, oldmesh->svector3f, oldmesh->numverts * sizeof(float[3]));
1018 memcpy(newmesh->tvector3f, oldmesh->tvector3f, oldmesh->numverts * sizeof(float[3]));
1019 memcpy(newmesh->normal3f, oldmesh->normal3f, oldmesh->numverts * sizeof(float[3]));
1020 memcpy(newmesh->texcoord2f, oldmesh->texcoord2f, oldmesh->numverts * sizeof(float[2]));
1022 memcpy(newmesh->element3i, oldmesh->element3i, oldmesh->numtriangles * sizeof(int[3]));
1023 if (newmesh->neighbor3i && oldmesh->neighbor3i)
1024 memcpy(newmesh->neighbor3i, oldmesh->neighbor3i, oldmesh->numtriangles * sizeof(int[3]));
1028 int Mod_ShadowMesh_AddVertex(shadowmesh_t *mesh, float *vertex14f)
1030 int hashindex, vnum;
1031 shadowmeshvertexhash_t *hash;
1032 // this uses prime numbers intentionally
1033 hashindex = (unsigned int) (vertex14f[0] * 2003 + vertex14f[1] * 4001 + vertex14f[2] * 7919) % SHADOWMESHVERTEXHASH;
1034 for (hash = mesh->vertexhashtable[hashindex];hash;hash = hash->next)
1036 vnum = (hash - mesh->vertexhashentries);
1037 if ((mesh->vertex3f == NULL || (mesh->vertex3f[vnum * 3 + 0] == vertex14f[0] && mesh->vertex3f[vnum * 3 + 1] == vertex14f[1] && mesh->vertex3f[vnum * 3 + 2] == vertex14f[2]))
1038 && (mesh->svector3f == NULL || (mesh->svector3f[vnum * 3 + 0] == vertex14f[3] && mesh->svector3f[vnum * 3 + 1] == vertex14f[4] && mesh->svector3f[vnum * 3 + 2] == vertex14f[5]))
1039 && (mesh->tvector3f == NULL || (mesh->tvector3f[vnum * 3 + 0] == vertex14f[6] && mesh->tvector3f[vnum * 3 + 1] == vertex14f[7] && mesh->tvector3f[vnum * 3 + 2] == vertex14f[8]))
1040 && (mesh->normal3f == NULL || (mesh->normal3f[vnum * 3 + 0] == vertex14f[9] && mesh->normal3f[vnum * 3 + 1] == vertex14f[10] && mesh->normal3f[vnum * 3 + 2] == vertex14f[11]))
1041 && (mesh->texcoord2f == NULL || (mesh->texcoord2f[vnum * 2 + 0] == vertex14f[12] && mesh->texcoord2f[vnum * 2 + 1] == vertex14f[13])))
1042 return hash - mesh->vertexhashentries;
1044 vnum = mesh->numverts++;
1045 hash = mesh->vertexhashentries + vnum;
1046 hash->next = mesh->vertexhashtable[hashindex];
1047 mesh->vertexhashtable[hashindex] = hash;
1048 if (mesh->vertex3f) {mesh->vertex3f[vnum * 3 + 0] = vertex14f[0];mesh->vertex3f[vnum * 3 + 1] = vertex14f[1];mesh->vertex3f[vnum * 3 + 2] = vertex14f[2];}
1049 if (mesh->svector3f) {mesh->svector3f[vnum * 3 + 0] = vertex14f[3];mesh->svector3f[vnum * 3 + 1] = vertex14f[4];mesh->svector3f[vnum * 3 + 2] = vertex14f[5];}
1050 if (mesh->tvector3f) {mesh->tvector3f[vnum * 3 + 0] = vertex14f[6];mesh->tvector3f[vnum * 3 + 1] = vertex14f[7];mesh->tvector3f[vnum * 3 + 2] = vertex14f[8];}
1051 if (mesh->normal3f) {mesh->normal3f[vnum * 3 + 0] = vertex14f[9];mesh->normal3f[vnum * 3 + 1] = vertex14f[10];mesh->normal3f[vnum * 3 + 2] = vertex14f[11];}
1052 if (mesh->texcoord2f) {mesh->texcoord2f[vnum * 2 + 0] = vertex14f[12];mesh->texcoord2f[vnum * 2 + 1] = vertex14f[13];}
1056 void Mod_ShadowMesh_AddTriangle(mempool_t *mempool, shadowmesh_t *mesh, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, float *vertex14f)
1058 if (mesh->numtriangles == 0)
1060 // set the properties on this empty mesh to be more favorable...
1061 // (note: this case only occurs for the first triangle added to a new mesh chain)
1062 mesh->map_diffuse = map_diffuse;
1063 mesh->map_specular = map_specular;
1064 mesh->map_normal = map_normal;
1066 while (mesh->map_diffuse != map_diffuse || mesh->map_specular != map_specular || mesh->map_normal != map_normal || mesh->numverts + 3 > mesh->maxverts || mesh->numtriangles + 1 > mesh->maxtriangles)
1068 if (mesh->next == NULL)
1069 mesh->next = Mod_ShadowMesh_Alloc(mempool, max(mesh->maxverts, 300), max(mesh->maxtriangles, 100), map_diffuse, map_specular, map_normal, mesh->svector3f != NULL, mesh->neighbor3i != NULL, true);
1072 mesh->element3i[mesh->numtriangles * 3 + 0] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 0);
1073 mesh->element3i[mesh->numtriangles * 3 + 1] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 1);
1074 mesh->element3i[mesh->numtriangles * 3 + 2] = Mod_ShadowMesh_AddVertex(mesh, vertex14f + 14 * 2);
1075 mesh->numtriangles++;
1078 void Mod_ShadowMesh_AddMesh(mempool_t *mempool, shadowmesh_t *mesh, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, const float *vertex3f, const float *svector3f, const float *tvector3f, const float *normal3f, const float *texcoord2f, int numtris, const int *element3i)
1081 float vbuf[3*14], *v;
1082 memset(vbuf, 0, sizeof(vbuf));
1083 for (i = 0;i < numtris;i++)
1085 for (j = 0, v = vbuf;j < 3;j++, v += 14)
1090 v[0] = vertex3f[e * 3 + 0];
1091 v[1] = vertex3f[e * 3 + 1];
1092 v[2] = vertex3f[e * 3 + 2];
1096 v[3] = svector3f[e * 3 + 0];
1097 v[4] = svector3f[e * 3 + 1];
1098 v[5] = svector3f[e * 3 + 2];
1102 v[6] = tvector3f[e * 3 + 0];
1103 v[7] = tvector3f[e * 3 + 1];
1104 v[8] = tvector3f[e * 3 + 2];
1108 v[9] = normal3f[e * 3 + 0];
1109 v[10] = normal3f[e * 3 + 1];
1110 v[11] = normal3f[e * 3 + 2];
1114 v[12] = texcoord2f[e * 2 + 0];
1115 v[13] = texcoord2f[e * 2 + 1];
1118 Mod_ShadowMesh_AddTriangle(mempool, mesh, map_diffuse, map_specular, map_normal, vbuf);
1121 // the triangle calculation can take a while, so let's do a keepalive here
1122 CL_KeepaliveMessage(false);
1125 shadowmesh_t *Mod_ShadowMesh_Begin(mempool_t *mempool, int maxverts, int maxtriangles, rtexture_t *map_diffuse, rtexture_t *map_specular, rtexture_t *map_normal, int light, int neighbors, int expandable)
1127 // the preparation before shadow mesh initialization can take a while, so let's do a keepalive here
1128 CL_KeepaliveMessage(false);
1130 return Mod_ShadowMesh_Alloc(mempool, maxverts, maxtriangles, map_diffuse, map_specular, map_normal, light, neighbors, expandable);
1133 static void Mod_ShadowMesh_CreateVBOs(shadowmesh_t *mesh)
1135 if (!gl_support_arb_vertex_buffer_object)
1138 // element buffer is easy because it's just one array
1139 if (mesh->numtriangles)
1141 if (mesh->element3s)
1142 mesh->ebo3s = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, mesh->element3s, mesh->numtriangles * sizeof(unsigned short[3]), "shadowmesh");
1144 mesh->ebo3i = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, mesh->element3i, mesh->numtriangles * sizeof(unsigned int[3]), "shadowmesh");
1147 // vertex buffer is several arrays and we put them in the same buffer
1149 // is this wise? the texcoordtexture2f array is used with dynamic
1150 // vertex/svector/tvector/normal when rendering animated models, on the
1151 // other hand animated models don't use a lot of vertices anyway...
1157 mesh->vbooffset_vertex3f = size;if (mesh->vertex3f ) size += mesh->numverts * sizeof(float[3]);
1158 mesh->vbooffset_svector3f = size;if (mesh->svector3f ) size += mesh->numverts * sizeof(float[3]);
1159 mesh->vbooffset_tvector3f = size;if (mesh->tvector3f ) size += mesh->numverts * sizeof(float[3]);
1160 mesh->vbooffset_normal3f = size;if (mesh->normal3f ) size += mesh->numverts * sizeof(float[3]);
1161 mesh->vbooffset_texcoord2f = size;if (mesh->texcoord2f ) size += mesh->numverts * sizeof(float[2]);
1162 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
1163 if (mesh->vertex3f ) memcpy(mem + mesh->vbooffset_vertex3f , mesh->vertex3f , mesh->numverts * sizeof(float[3]));
1164 if (mesh->svector3f ) memcpy(mem + mesh->vbooffset_svector3f , mesh->svector3f , mesh->numverts * sizeof(float[3]));
1165 if (mesh->tvector3f ) memcpy(mem + mesh->vbooffset_tvector3f , mesh->tvector3f , mesh->numverts * sizeof(float[3]));
1166 if (mesh->normal3f ) memcpy(mem + mesh->vbooffset_normal3f , mesh->normal3f , mesh->numverts * sizeof(float[3]));
1167 if (mesh->texcoord2f ) memcpy(mem + mesh->vbooffset_texcoord2f , mesh->texcoord2f , mesh->numverts * sizeof(float[2]));
1168 mesh->vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, "shadowmesh");
1173 shadowmesh_t *Mod_ShadowMesh_Finish(mempool_t *mempool, shadowmesh_t *firstmesh, qboolean light, qboolean neighbors, qboolean createvbo)
1175 shadowmesh_t *mesh, *newmesh, *nextmesh;
1176 // reallocate meshs to conserve space
1177 for (mesh = firstmesh, firstmesh = NULL;mesh;mesh = nextmesh)
1179 nextmesh = mesh->next;
1180 if (mesh->numverts >= 3 && mesh->numtriangles >= 1)
1182 newmesh = Mod_ShadowMesh_ReAlloc(mempool, mesh, light, neighbors);
1183 newmesh->next = firstmesh;
1184 firstmesh = newmesh;
1185 if (newmesh->element3s)
1188 for (i = 0;i < newmesh->numtriangles*3;i++)
1189 newmesh->element3s[i] = newmesh->element3i[i];
1192 Mod_ShadowMesh_CreateVBOs(newmesh);
1197 // this can take a while, so let's do a keepalive here
1198 CL_KeepaliveMessage(false);
1203 void Mod_ShadowMesh_CalcBBox(shadowmesh_t *firstmesh, vec3_t mins, vec3_t maxs, vec3_t center, float *radius)
1207 vec3_t nmins, nmaxs, ncenter, temp;
1208 float nradius2, dist2, *v;
1212 for (mesh = firstmesh;mesh;mesh = mesh->next)
1214 if (mesh == firstmesh)
1216 VectorCopy(mesh->vertex3f, nmins);
1217 VectorCopy(mesh->vertex3f, nmaxs);
1219 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1221 if (nmins[0] > v[0]) nmins[0] = v[0];if (nmaxs[0] < v[0]) nmaxs[0] = v[0];
1222 if (nmins[1] > v[1]) nmins[1] = v[1];if (nmaxs[1] < v[1]) nmaxs[1] = v[1];
1223 if (nmins[2] > v[2]) nmins[2] = v[2];if (nmaxs[2] < v[2]) nmaxs[2] = v[2];
1226 // calculate center and radius
1227 ncenter[0] = (nmins[0] + nmaxs[0]) * 0.5f;
1228 ncenter[1] = (nmins[1] + nmaxs[1]) * 0.5f;
1229 ncenter[2] = (nmins[2] + nmaxs[2]) * 0.5f;
1231 for (mesh = firstmesh;mesh;mesh = mesh->next)
1233 for (i = 0, v = mesh->vertex3f;i < mesh->numverts;i++, v += 3)
1235 VectorSubtract(v, ncenter, temp);
1236 dist2 = DotProduct(temp, temp);
1237 if (nradius2 < dist2)
1243 VectorCopy(nmins, mins);
1245 VectorCopy(nmaxs, maxs);
1247 VectorCopy(ncenter, center);
1249 *radius = sqrt(nradius2);
1252 void Mod_ShadowMesh_Free(shadowmesh_t *mesh)
1254 shadowmesh_t *nextmesh;
1255 for (;mesh;mesh = nextmesh)
1258 R_Mesh_DestroyBufferObject(mesh->ebo3i);
1260 R_Mesh_DestroyBufferObject(mesh->ebo3s);
1262 R_Mesh_DestroyBufferObject(mesh->vbo);
1263 nextmesh = mesh->next;
1268 void Mod_CreateCollisionMesh(dp_model_t *mod)
1271 int numcollisionmeshtriangles;
1272 const msurface_t *surface;
1273 mempool_t *mempool = mod->mempool;
1274 if (!mempool && mod->brush.parentmodel)
1275 mempool = mod->brush.parentmodel->mempool;
1276 // make a single combined collision mesh for physics engine use
1277 // TODO rewrite this to use the collision brushes as source, to fix issues with e.g. common/caulk which creates no drawsurface
1278 numcollisionmeshtriangles = 0;
1279 for (k = 0;k < mod->nummodelsurfaces;k++)
1281 surface = mod->data_surfaces + mod->firstmodelsurface + k;
1282 if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1284 numcollisionmeshtriangles += surface->num_triangles;
1286 mod->brush.collisionmesh = Mod_ShadowMesh_Begin(mempool, numcollisionmeshtriangles * 3, numcollisionmeshtriangles, NULL, NULL, NULL, false, false, true);
1287 for (k = 0;k < mod->nummodelsurfaces;k++)
1289 surface = mod->data_surfaces + mod->firstmodelsurface + k;
1290 if (!(surface->texture->supercontents & SUPERCONTENTS_SOLID))
1292 Mod_ShadowMesh_AddMesh(mempool, mod->brush.collisionmesh, NULL, NULL, NULL, mod->surfmesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (mod->surfmesh.data_element3i + 3 * surface->num_firsttriangle));
1294 mod->brush.collisionmesh = Mod_ShadowMesh_Finish(mempool, mod->brush.collisionmesh, false, true, false);
1297 void Mod_GetTerrainVertex3fTexCoord2fFromBGRA(const unsigned char *imagepixels, int imagewidth, int imageheight, int ix, int iy, float *vertex3f, float *texcoord2f, matrix4x4_t *pixelstepmatrix, matrix4x4_t *pixeltexturestepmatrix)
1302 if (ix >= 0 && iy >= 0 && ix < imagewidth && iy < imageheight)
1303 v[2] = (imagepixels[((iy*imagewidth)+ix)*4+0] + imagepixels[((iy*imagewidth)+ix)*4+1] + imagepixels[((iy*imagewidth)+ix)*4+2]) * (1.0f / 765.0f);
1306 Matrix4x4_Transform(pixelstepmatrix, v, vertex3f);
1307 Matrix4x4_Transform(pixeltexturestepmatrix, v, tc);
1308 texcoord2f[0] = tc[0];
1309 texcoord2f[1] = tc[1];
1312 void Mod_GetTerrainVertexFromBGRA(const unsigned char *imagepixels, int imagewidth, int imageheight, int ix, int iy, float *vertex3f, float *svector3f, float *tvector3f, float *normal3f, float *texcoord2f, matrix4x4_t *pixelstepmatrix, matrix4x4_t *pixeltexturestepmatrix)
1314 float vup[3], vdown[3], vleft[3], vright[3];
1315 float tcup[3], tcdown[3], tcleft[3], tcright[3];
1316 float sv[3], tv[3], nl[3];
1317 Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, pixelstepmatrix, pixeltexturestepmatrix);
1318 Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy - 1, vup, tcup, pixelstepmatrix, pixeltexturestepmatrix);
1319 Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix, iy + 1, vdown, tcdown, pixelstepmatrix, pixeltexturestepmatrix);
1320 Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix - 1, iy, vleft, tcleft, pixelstepmatrix, pixeltexturestepmatrix);
1321 Mod_GetTerrainVertex3fTexCoord2fFromBGRA(imagepixels, imagewidth, imageheight, ix + 1, iy, vright, tcright, pixelstepmatrix, pixeltexturestepmatrix);
1322 Mod_BuildBumpVectors(vertex3f, vup, vright, texcoord2f, tcup, tcright, svector3f, tvector3f, normal3f);
1323 Mod_BuildBumpVectors(vertex3f, vright, vdown, texcoord2f, tcright, tcdown, sv, tv, nl);
1324 VectorAdd(svector3f, sv, svector3f);
1325 VectorAdd(tvector3f, tv, tvector3f);
1326 VectorAdd(normal3f, nl, normal3f);
1327 Mod_BuildBumpVectors(vertex3f, vdown, vleft, texcoord2f, tcdown, tcleft, sv, tv, nl);
1328 VectorAdd(svector3f, sv, svector3f);
1329 VectorAdd(tvector3f, tv, tvector3f);
1330 VectorAdd(normal3f, nl, normal3f);
1331 Mod_BuildBumpVectors(vertex3f, vleft, vup, texcoord2f, tcleft, tcup, sv, tv, nl);
1332 VectorAdd(svector3f, sv, svector3f);
1333 VectorAdd(tvector3f, tv, tvector3f);
1334 VectorAdd(normal3f, nl, normal3f);
1337 void Mod_ConstructTerrainPatchFromBGRA(const unsigned char *imagepixels, int imagewidth, int imageheight, int x1, int y1, int width, int height, int *element3i, int *neighbor3i, float *vertex3f, float *svector3f, float *tvector3f, float *normal3f, float *texcoord2f, matrix4x4_t *pixelstepmatrix, matrix4x4_t *pixeltexturestepmatrix)
1339 int x, y, ix, iy, *e;
1341 for (y = 0;y < height;y++)
1343 for (x = 0;x < width;x++)
1345 e[0] = (y + 1) * (width + 1) + (x + 0);
1346 e[1] = (y + 0) * (width + 1) + (x + 0);
1347 e[2] = (y + 1) * (width + 1) + (x + 1);
1348 e[3] = (y + 0) * (width + 1) + (x + 0);
1349 e[4] = (y + 0) * (width + 1) + (x + 1);
1350 e[5] = (y + 1) * (width + 1) + (x + 1);
1354 Mod_BuildTriangleNeighbors(neighbor3i, element3i, width*height*2);
1355 for (y = 0, iy = y1;y < height + 1;y++, iy++)
1356 for (x = 0, ix = x1;x < width + 1;x++, ix++, vertex3f += 3, texcoord2f += 2, svector3f += 3, tvector3f += 3, normal3f += 3)
1357 Mod_GetTerrainVertexFromBGRA(imagepixels, imagewidth, imageheight, ix, iy, vertex3f, texcoord2f, svector3f, tvector3f, normal3f, pixelstepmatrix, pixeltexturestepmatrix);
1361 void Mod_Terrain_SurfaceRecurseChunk(dp_model_t *model, int stepsize, int x, int y)
1365 float chunkwidth = min(stepsize, model->terrain.width - 1 - x);
1366 float chunkheight = min(stepsize, model->terrain.height - 1 - y);
1367 float viewvector[3];
1368 unsigned int firstvertex;
1371 if (chunkwidth < 2 || chunkheight < 2)
1373 VectorSet(mins, model->terrain.mins[0] + x * stepsize * model->terrain.scale[0], model->terrain.mins[1] + y * stepsize * model->terrain.scale[1], model->terrain.mins[2]);
1374 VectorSet(maxs, model->terrain.mins[0] + (x+1) * stepsize * model->terrain.scale[0], model->terrain.mins[1] + (y+1) * stepsize * model->terrain.scale[1], model->terrain.maxs[2]);
1375 viewvector[0] = bound(mins[0], localvieworigin, maxs[0]) - model->terrain.vieworigin[0];
1376 viewvector[1] = bound(mins[1], localvieworigin, maxs[1]) - model->terrain.vieworigin[1];
1377 viewvector[2] = bound(mins[2], localvieworigin, maxs[2]) - model->terrain.vieworigin[2];
1378 if (stepsize > 1 && VectorLength(viewvector) < stepsize*model->terrain.scale[0]*r_terrain_lodscale.value)
1380 // too close for this stepsize, emit as 4 chunks instead
1382 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y);
1383 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y);
1384 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x, y+stepsize);
1385 Mod_Terrain_SurfaceRecurseChunk(model, stepsize, x+stepsize, y+stepsize);
1388 // emit the geometry at stepsize into our vertex buffer / index buffer
1389 // we add two columns and two rows for skirt
1390 outwidth = chunkwidth+2;
1391 outheight = chunkheight+2;
1392 outwidth2 = outwidth-1;
1393 outheight2 = outheight-1;
1394 outwidth3 = outwidth+1;
1395 outheight3 = outheight+1;
1396 firstvertex = numvertices;
1397 e = model->terrain.element3i + numtriangles;
1398 numtriangles += chunkwidth*chunkheight*2+chunkwidth*2*2+chunkheight*2*2;
1399 v = model->terrain.vertex3f + numvertices;
1400 numvertices += (chunkwidth+1)*(chunkheight+1)+(chunkwidth+1)*2+(chunkheight+1)*2;
1401 // emit the triangles (note: the skirt is treated as two extra rows and two extra columns)
1402 for (ty = 0;ty < outheight;ty++)
1404 for (tx = 0;tx < outwidth;tx++)
1406 *e++ = firstvertex + (ty )*outwidth3+(tx );
1407 *e++ = firstvertex + (ty )*outwidth3+(tx+1);
1408 *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1409 *e++ = firstvertex + (ty )*outwidth3+(tx );
1410 *e++ = firstvertex + (ty+1)*outwidth3+(tx+1);
1411 *e++ = firstvertex + (ty+1)*outwidth3+(tx );
1414 // TODO: emit surface vertices (x+tx*stepsize, y+ty*stepsize)
1415 for (ty = 0;ty <= outheight;ty++)
1417 skirtrow = ty == 0 || ty == outheight;
1418 ry = y+bound(1, ty, outheight)*stepsize;
1419 for (tx = 0;tx <= outwidth;tx++)
1421 skirt = skirtrow || tx == 0 || tx == outwidth;
1422 rx = x+bound(1, tx, outwidth)*stepsize;
1425 v[2] = heightmap[ry*terrainwidth+rx]*scale[2];
1429 // TODO: emit skirt vertices
1432 void Mod_Terrain_UpdateSurfacesForViewOrigin(dp_model_t *model)
1434 for (y = 0;y < model->terrain.size[1];y += model->terrain.
1435 Mod_Terrain_SurfaceRecurseChunk(model, model->terrain.maxstepsize, x, y);
1436 Mod_Terrain_BuildChunk(model,
1440 q3wavefunc_t Mod_LoadQ3Shaders_EnumerateWaveFunc(const char *s)
1442 if (!strcasecmp(s, "sin")) return Q3WAVEFUNC_SIN;
1443 if (!strcasecmp(s, "square")) return Q3WAVEFUNC_SQUARE;
1444 if (!strcasecmp(s, "triangle")) return Q3WAVEFUNC_TRIANGLE;
1445 if (!strcasecmp(s, "sawtooth")) return Q3WAVEFUNC_SAWTOOTH;
1446 if (!strcasecmp(s, "inversesawtooth")) return Q3WAVEFUNC_INVERSESAWTOOTH;
1447 if (!strcasecmp(s, "noise")) return Q3WAVEFUNC_NOISE;
1448 Con_DPrintf("Mod_LoadQ3Shaders: unknown wavefunc %s\n", s);
1449 return Q3WAVEFUNC_NONE;
1452 void Mod_FreeQ3Shaders(void)
1454 Mem_FreePool(&q3shaders_mem);
1457 static void Q3Shader_AddToHash (q3shaderinfo_t* shader)
1459 unsigned short hash = CRC_Block_CaseInsensitive ((const unsigned char *)shader->name, strlen (shader->name));
1460 q3shader_hash_entry_t* entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
1461 q3shader_hash_entry_t* lastEntry = NULL;
1462 while (entry != NULL)
1464 if (strcasecmp (entry->shader.name, shader->name) == 0)
1466 unsigned char *start, *end, *start2;
1467 start = (unsigned char *) (&shader->Q3SHADERINFO_COMPARE_START);
1468 end = ((unsigned char *) (&shader->Q3SHADERINFO_COMPARE_END)) + sizeof(shader->Q3SHADERINFO_COMPARE_END);
1469 start2 = (unsigned char *) (&entry->shader.Q3SHADERINFO_COMPARE_START);
1470 if(memcmp(start, start2, end - start))
1471 Con_Printf("Shader '%s' already defined, ignoring mismatching redeclaration\n", shader->name);
1473 Con_DPrintf("Shader '%s' already defined\n", shader->name);
1477 entry = entry->chain;
1481 if (lastEntry->shader.name[0] != 0)
1484 q3shader_hash_entry_t* newEntry = (q3shader_hash_entry_t*)
1485 Mem_ExpandableArray_AllocRecord (&q3shader_data->hash_entries);
1487 while (lastEntry->chain != NULL) lastEntry = lastEntry->chain;
1488 lastEntry->chain = newEntry;
1489 newEntry->chain = NULL;
1490 lastEntry = newEntry;
1492 /* else: head of chain, in hash entry array */
1495 memcpy (&entry->shader, shader, sizeof (q3shaderinfo_t));
1498 extern cvar_t r_picmipworld;
1499 void Mod_LoadQ3Shaders(void)
1506 q3shaderinfo_t shader;
1507 q3shaderinfo_layer_t *layer;
1509 char parameter[TEXTURE_MAXFRAMES + 4][Q3PATHLENGTH];
1511 Mod_FreeQ3Shaders();
1513 q3shaders_mem = Mem_AllocPool("q3shaders", 0, NULL);
1514 q3shader_data = (q3shader_data_t*)Mem_Alloc (q3shaders_mem,
1515 sizeof (q3shader_data_t));
1516 Mem_ExpandableArray_NewArray (&q3shader_data->hash_entries,
1517 q3shaders_mem, sizeof (q3shader_hash_entry_t), 256);
1518 Mem_ExpandableArray_NewArray (&q3shader_data->char_ptrs,
1519 q3shaders_mem, sizeof (char**), 256);
1521 search = FS_Search("scripts/*.shader", true, false);
1524 for (fileindex = 0;fileindex < search->numfilenames;fileindex++)
1526 text = f = (char *)FS_LoadFile(search->filenames[fileindex], tempmempool, false, NULL);
1529 while (COM_ParseToken_QuakeC(&text, false))
1531 memset (&shader, 0, sizeof(shader));
1532 shader.reflectmin = 0;
1533 shader.reflectmax = 1;
1534 shader.refractfactor = 1;
1535 Vector4Set(shader.refractcolor4f, 1, 1, 1, 1);
1536 shader.reflectfactor = 1;
1537 Vector4Set(shader.reflectcolor4f, 1, 1, 1, 1);
1538 shader.r_water_wateralpha = 1;
1539 shader.specularscalemod = 1;
1540 shader.specularpowermod = 1;
1542 strlcpy(shader.name, com_token, sizeof(shader.name));
1543 if (!COM_ParseToken_QuakeC(&text, false) || strcasecmp(com_token, "{"))
1545 Con_Printf("%s parsing error - expected \"{\", found \"%s\"\n", search->filenames[fileindex], com_token);
1548 while (COM_ParseToken_QuakeC(&text, false))
1550 if (!strcasecmp(com_token, "}"))
1552 if (!strcasecmp(com_token, "{"))
1554 static q3shaderinfo_layer_t dummy;
1555 if (shader.numlayers < Q3SHADER_MAXLAYERS)
1557 layer = shader.layers + shader.numlayers++;
1561 // parse and process it anyway, just don't store it (so a map $lightmap or such stuff still is found)
1562 memset(&dummy, 0, sizeof(dummy));
1565 layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1566 layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1567 layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1568 layer->blendfunc[0] = GL_ONE;
1569 layer->blendfunc[1] = GL_ZERO;
1570 while (COM_ParseToken_QuakeC(&text, false))
1572 if (!strcasecmp(com_token, "}"))
1574 if (!strcasecmp(com_token, "\n"))
1577 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1579 if (j < TEXTURE_MAXFRAMES + 4)
1581 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1582 numparameters = j + 1;
1584 if (!COM_ParseToken_QuakeC(&text, true))
1587 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1588 // parameter[j][0] = 0;
1589 if (developer.integer >= 100)
1591 Con_Printf("%s %i: ", shader.name, shader.numlayers - 1);
1592 for (j = 0;j < numparameters;j++)
1593 Con_Printf(" %s", parameter[j]);
1596 if (numparameters >= 2 && !strcasecmp(parameter[0], "blendfunc"))
1598 if (numparameters == 2)
1600 if (!strcasecmp(parameter[1], "add"))
1602 layer->blendfunc[0] = GL_ONE;
1603 layer->blendfunc[1] = GL_ONE;
1605 else if (!strcasecmp(parameter[1], "filter"))
1607 layer->blendfunc[0] = GL_DST_COLOR;
1608 layer->blendfunc[1] = GL_ZERO;
1610 else if (!strcasecmp(parameter[1], "blend"))
1612 layer->blendfunc[0] = GL_SRC_ALPHA;
1613 layer->blendfunc[1] = GL_ONE_MINUS_SRC_ALPHA;
1616 else if (numparameters == 3)
1619 for (k = 0;k < 2;k++)
1621 if (!strcasecmp(parameter[k+1], "GL_ONE"))
1622 layer->blendfunc[k] = GL_ONE;
1623 else if (!strcasecmp(parameter[k+1], "GL_ZERO"))
1624 layer->blendfunc[k] = GL_ZERO;
1625 else if (!strcasecmp(parameter[k+1], "GL_SRC_COLOR"))
1626 layer->blendfunc[k] = GL_SRC_COLOR;
1627 else if (!strcasecmp(parameter[k+1], "GL_SRC_ALPHA"))
1628 layer->blendfunc[k] = GL_SRC_ALPHA;
1629 else if (!strcasecmp(parameter[k+1], "GL_DST_COLOR"))
1630 layer->blendfunc[k] = GL_DST_COLOR;
1631 else if (!strcasecmp(parameter[k+1], "GL_DST_ALPHA"))
1632 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1633 else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_COLOR"))
1634 layer->blendfunc[k] = GL_ONE_MINUS_SRC_COLOR;
1635 else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_SRC_ALPHA"))
1636 layer->blendfunc[k] = GL_ONE_MINUS_SRC_ALPHA;
1637 else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_COLOR"))
1638 layer->blendfunc[k] = GL_ONE_MINUS_DST_COLOR;
1639 else if (!strcasecmp(parameter[k+1], "GL_ONE_MINUS_DST_ALPHA"))
1640 layer->blendfunc[k] = GL_ONE_MINUS_DST_ALPHA;
1642 layer->blendfunc[k] = GL_ONE; // default in case of parsing error
1646 if (numparameters >= 2 && !strcasecmp(parameter[0], "alphafunc"))
1647 layer->alphatest = true;
1648 if (numparameters >= 2 && (!strcasecmp(parameter[0], "map") || !strcasecmp(parameter[0], "clampmap")))
1650 if (!strcasecmp(parameter[0], "clampmap"))
1651 layer->clampmap = true;
1652 layer->numframes = 1;
1653 layer->framerate = 1;
1654 layer->texturename = (char**)Mem_ExpandableArray_AllocRecord (
1655 &q3shader_data->char_ptrs);
1656 layer->texturename[0] = Mem_strdup (q3shaders_mem, parameter[1]);
1657 if (!strcasecmp(parameter[1], "$lightmap"))
1658 shader.lighting = true;
1660 else if (numparameters >= 3 && (!strcasecmp(parameter[0], "animmap") || !strcasecmp(parameter[0], "animclampmap")))
1663 layer->numframes = min(numparameters - 2, TEXTURE_MAXFRAMES);
1664 layer->framerate = atof(parameter[1]);
1665 layer->texturename = (char **) Mem_Alloc (q3shaders_mem, sizeof (char*) * layer->numframes);
1666 for (i = 0;i < layer->numframes;i++)
1667 layer->texturename[i] = Mem_strdup (q3shaders_mem, parameter[i + 2]);
1669 else if (numparameters >= 2 && !strcasecmp(parameter[0], "rgbgen"))
1672 for (i = 0;i < numparameters - 2 && i < Q3RGBGEN_MAXPARMS;i++)
1673 layer->rgbgen.parms[i] = atof(parameter[i+2]);
1674 if (!strcasecmp(parameter[1], "identity")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITY;
1675 else if (!strcasecmp(parameter[1], "const")) layer->rgbgen.rgbgen = Q3RGBGEN_CONST;
1676 else if (!strcasecmp(parameter[1], "entity")) layer->rgbgen.rgbgen = Q3RGBGEN_ENTITY;
1677 else if (!strcasecmp(parameter[1], "exactvertex")) layer->rgbgen.rgbgen = Q3RGBGEN_EXACTVERTEX;
1678 else if (!strcasecmp(parameter[1], "identitylighting")) layer->rgbgen.rgbgen = Q3RGBGEN_IDENTITYLIGHTING;
1679 else if (!strcasecmp(parameter[1], "lightingdiffuse")) layer->rgbgen.rgbgen = Q3RGBGEN_LIGHTINGDIFFUSE;
1680 else if (!strcasecmp(parameter[1], "oneminusentity")) layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSENTITY;
1681 else if (!strcasecmp(parameter[1], "oneminusvertex")) layer->rgbgen.rgbgen = Q3RGBGEN_ONEMINUSVERTEX;
1682 else if (!strcasecmp(parameter[1], "vertex")) layer->rgbgen.rgbgen = Q3RGBGEN_VERTEX;
1683 else if (!strcasecmp(parameter[1], "wave"))
1685 layer->rgbgen.rgbgen = Q3RGBGEN_WAVE;
1686 layer->rgbgen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1687 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1688 layer->rgbgen.waveparms[i] = atof(parameter[i+3]);
1690 else Con_DPrintf("%s parsing warning: unknown rgbgen %s\n", search->filenames[fileindex], parameter[1]);
1692 else if (numparameters >= 2 && !strcasecmp(parameter[0], "alphagen"))
1695 for (i = 0;i < numparameters - 2 && i < Q3ALPHAGEN_MAXPARMS;i++)
1696 layer->alphagen.parms[i] = atof(parameter[i+2]);
1697 if (!strcasecmp(parameter[1], "identity")) layer->alphagen.alphagen = Q3ALPHAGEN_IDENTITY;
1698 else if (!strcasecmp(parameter[1], "const")) layer->alphagen.alphagen = Q3ALPHAGEN_CONST;
1699 else if (!strcasecmp(parameter[1], "entity")) layer->alphagen.alphagen = Q3ALPHAGEN_ENTITY;
1700 else if (!strcasecmp(parameter[1], "lightingspecular")) layer->alphagen.alphagen = Q3ALPHAGEN_LIGHTINGSPECULAR;
1701 else if (!strcasecmp(parameter[1], "oneminusentity")) layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSENTITY;
1702 else if (!strcasecmp(parameter[1], "oneminusvertex")) layer->alphagen.alphagen = Q3ALPHAGEN_ONEMINUSVERTEX;
1703 else if (!strcasecmp(parameter[1], "portal")) layer->alphagen.alphagen = Q3ALPHAGEN_PORTAL;
1704 else if (!strcasecmp(parameter[1], "vertex")) layer->alphagen.alphagen = Q3ALPHAGEN_VERTEX;
1705 else if (!strcasecmp(parameter[1], "wave"))
1707 layer->alphagen.alphagen = Q3ALPHAGEN_WAVE;
1708 layer->alphagen.wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1709 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1710 layer->alphagen.waveparms[i] = atof(parameter[i+3]);
1712 else Con_DPrintf("%s parsing warning: unknown alphagen %s\n", search->filenames[fileindex], parameter[1]);
1714 else if (numparameters >= 2 && (!strcasecmp(parameter[0], "texgen") || !strcasecmp(parameter[0], "tcgen")))
1717 // observed values: tcgen environment
1718 // no other values have been observed in real shaders
1719 for (i = 0;i < numparameters - 2 && i < Q3TCGEN_MAXPARMS;i++)
1720 layer->tcgen.parms[i] = atof(parameter[i+2]);
1721 if (!strcasecmp(parameter[1], "base")) layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1722 else if (!strcasecmp(parameter[1], "texture")) layer->tcgen.tcgen = Q3TCGEN_TEXTURE;
1723 else if (!strcasecmp(parameter[1], "environment")) layer->tcgen.tcgen = Q3TCGEN_ENVIRONMENT;
1724 else if (!strcasecmp(parameter[1], "lightmap")) layer->tcgen.tcgen = Q3TCGEN_LIGHTMAP;
1725 else if (!strcasecmp(parameter[1], "vector")) layer->tcgen.tcgen = Q3TCGEN_VECTOR;
1726 else Con_DPrintf("%s parsing warning: unknown tcgen mode %s\n", search->filenames[fileindex], parameter[1]);
1728 else if (numparameters >= 2 && !strcasecmp(parameter[0], "tcmod"))
1735 // tcmod stretch sin # # # #
1736 // tcmod stretch triangle # # # #
1737 // tcmod transform # # # # # #
1738 // tcmod turb # # # #
1739 // tcmod turb sin # # # # (this is bogus)
1740 // no other values have been observed in real shaders
1741 for (tcmodindex = 0;tcmodindex < Q3MAXTCMODS;tcmodindex++)
1742 if (!layer->tcmods[tcmodindex].tcmod)
1744 if (tcmodindex < Q3MAXTCMODS)
1746 for (i = 0;i < numparameters - 2 && i < Q3TCMOD_MAXPARMS;i++)
1747 layer->tcmods[tcmodindex].parms[i] = atof(parameter[i+2]);
1748 if (!strcasecmp(parameter[1], "entitytranslate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ENTITYTRANSLATE;
1749 else if (!strcasecmp(parameter[1], "rotate")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_ROTATE;
1750 else if (!strcasecmp(parameter[1], "scale")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCALE;
1751 else if (!strcasecmp(parameter[1], "scroll")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_SCROLL;
1752 else if (!strcasecmp(parameter[1], "page")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_PAGE;
1753 else if (!strcasecmp(parameter[1], "stretch"))
1755 layer->tcmods[tcmodindex].tcmod = Q3TCMOD_STRETCH;
1756 layer->tcmods[tcmodindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[2]);
1757 for (i = 0;i < numparameters - 3 && i < Q3WAVEPARMS;i++)
1758 layer->tcmods[tcmodindex].waveparms[i] = atof(parameter[i+3]);
1760 else if (!strcasecmp(parameter[1], "transform")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TRANSFORM;
1761 else if (!strcasecmp(parameter[1], "turb")) layer->tcmods[tcmodindex].tcmod = Q3TCMOD_TURBULENT;
1762 else Con_DPrintf("%s parsing warning: unknown tcmod mode %s\n", search->filenames[fileindex], parameter[1]);
1765 Con_DPrintf("%s parsing warning: too many tcmods on one layer\n", search->filenames[fileindex]);
1767 // break out a level if it was a closing brace (not using the character here to not confuse vim)
1768 if (!strcasecmp(com_token, "}"))
1771 if (layer->rgbgen.rgbgen == Q3RGBGEN_LIGHTINGDIFFUSE || layer->rgbgen.rgbgen == Q3RGBGEN_VERTEX)
1772 shader.lighting = true;
1773 if (layer->alphagen.alphagen == Q3ALPHAGEN_VERTEX)
1775 if (layer == shader.layers + 0)
1777 // vertex controlled transparency
1778 shader.vertexalpha = true;
1782 // multilayer terrain shader or similar
1783 shader.textureblendalpha = true;
1786 layer->texflags = TEXF_ALPHA | TEXF_PRECACHE;
1787 if (!(shader.surfaceparms & Q3SURFACEPARM_NOMIPMAPS))
1788 layer->texflags |= TEXF_MIPMAP;
1789 if (!(shader.textureflags & Q3TEXTUREFLAG_NOPICMIP))
1790 layer->texflags |= TEXF_PICMIP | TEXF_COMPRESS;
1791 if (layer->clampmap)
1792 layer->texflags |= TEXF_CLAMP;
1796 for (j = 0;strcasecmp(com_token, "\n") && strcasecmp(com_token, "}");j++)
1798 if (j < TEXTURE_MAXFRAMES + 4)
1800 strlcpy(parameter[j], com_token, sizeof(parameter[j]));
1801 numparameters = j + 1;
1803 if (!COM_ParseToken_QuakeC(&text, true))
1806 //for (j = numparameters;j < TEXTURE_MAXFRAMES + 4;j++)
1807 // parameter[j][0] = 0;
1808 if (fileindex == 0 && !strcasecmp(com_token, "}"))
1810 if (developer.integer >= 100)
1812 Con_Printf("%s: ", shader.name);
1813 for (j = 0;j < numparameters;j++)
1814 Con_Printf(" %s", parameter[j]);
1817 if (numparameters < 1)
1819 if (!strcasecmp(parameter[0], "surfaceparm") && numparameters >= 2)
1821 if (!strcasecmp(parameter[1], "alphashadow"))
1822 shader.surfaceparms |= Q3SURFACEPARM_ALPHASHADOW;
1823 else if (!strcasecmp(parameter[1], "areaportal"))
1824 shader.surfaceparms |= Q3SURFACEPARM_AREAPORTAL;
1825 else if (!strcasecmp(parameter[1], "botclip"))
1826 shader.surfaceparms |= Q3SURFACEPARM_BOTCLIP;
1827 else if (!strcasecmp(parameter[1], "clusterportal"))
1828 shader.surfaceparms |= Q3SURFACEPARM_CLUSTERPORTAL;
1829 else if (!strcasecmp(parameter[1], "detail"))
1830 shader.surfaceparms |= Q3SURFACEPARM_DETAIL;
1831 else if (!strcasecmp(parameter[1], "donotenter"))
1832 shader.surfaceparms |= Q3SURFACEPARM_DONOTENTER;
1833 else if (!strcasecmp(parameter[1], "dust"))
1834 shader.surfaceparms |= Q3SURFACEPARM_DUST;
1835 else if (!strcasecmp(parameter[1], "hint"))
1836 shader.surfaceparms |= Q3SURFACEPARM_HINT;
1837 else if (!strcasecmp(parameter[1], "fog"))
1838 shader.surfaceparms |= Q3SURFACEPARM_FOG;
1839 else if (!strcasecmp(parameter[1], "lava"))
1840 shader.surfaceparms |= Q3SURFACEPARM_LAVA;
1841 else if (!strcasecmp(parameter[1], "lightfilter"))
1842 shader.surfaceparms |= Q3SURFACEPARM_LIGHTFILTER;
1843 else if (!strcasecmp(parameter[1], "lightgrid"))
1844 shader.surfaceparms |= Q3SURFACEPARM_LIGHTGRID;
1845 else if (!strcasecmp(parameter[1], "metalsteps"))
1846 shader.surfaceparms |= Q3SURFACEPARM_METALSTEPS;
1847 else if (!strcasecmp(parameter[1], "nodamage"))
1848 shader.surfaceparms |= Q3SURFACEPARM_NODAMAGE;
1849 else if (!strcasecmp(parameter[1], "nodlight"))
1850 shader.surfaceparms |= Q3SURFACEPARM_NODLIGHT;
1851 else if (!strcasecmp(parameter[1], "nodraw"))
1852 shader.surfaceparms |= Q3SURFACEPARM_NODRAW;
1853 else if (!strcasecmp(parameter[1], "nodrop"))
1854 shader.surfaceparms |= Q3SURFACEPARM_NODROP;
1855 else if (!strcasecmp(parameter[1], "noimpact"))
1856 shader.surfaceparms |= Q3SURFACEPARM_NOIMPACT;
1857 else if (!strcasecmp(parameter[1], "nolightmap"))
1858 shader.surfaceparms |= Q3SURFACEPARM_NOLIGHTMAP;
1859 else if (!strcasecmp(parameter[1], "nomarks"))
1860 shader.surfaceparms |= Q3SURFACEPARM_NOMARKS;
1861 else if (!strcasecmp(parameter[1], "nomipmaps"))
1862 shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1863 else if (!strcasecmp(parameter[1], "nonsolid"))
1864 shader.surfaceparms |= Q3SURFACEPARM_NONSOLID;
1865 else if (!strcasecmp(parameter[1], "origin"))
1866 shader.surfaceparms |= Q3SURFACEPARM_ORIGIN;
1867 else if (!strcasecmp(parameter[1], "playerclip"))
1868 shader.surfaceparms |= Q3SURFACEPARM_PLAYERCLIP;
1869 else if (!strcasecmp(parameter[1], "sky"))
1870 shader.surfaceparms |= Q3SURFACEPARM_SKY;
1871 else if (!strcasecmp(parameter[1], "slick"))
1872 shader.surfaceparms |= Q3SURFACEPARM_SLICK;
1873 else if (!strcasecmp(parameter[1], "slime"))
1874 shader.surfaceparms |= Q3SURFACEPARM_SLIME;
1875 else if (!strcasecmp(parameter[1], "structural"))
1876 shader.surfaceparms |= Q3SURFACEPARM_STRUCTURAL;
1877 else if (!strcasecmp(parameter[1], "trans"))
1878 shader.surfaceparms |= Q3SURFACEPARM_TRANS;
1879 else if (!strcasecmp(parameter[1], "water"))
1880 shader.surfaceparms |= Q3SURFACEPARM_WATER;
1881 else if (!strcasecmp(parameter[1], "pointlight"))
1882 shader.surfaceparms |= Q3SURFACEPARM_POINTLIGHT;
1883 else if (!strcasecmp(parameter[1], "antiportal"))
1884 shader.surfaceparms |= Q3SURFACEPARM_ANTIPORTAL;
1886 Con_DPrintf("%s parsing warning: unknown surfaceparm \"%s\"\n", search->filenames[fileindex], parameter[1]);
1888 else if (!strcasecmp(parameter[0], "dpshadow"))
1889 shader.dpshadow = true;
1890 else if (!strcasecmp(parameter[0], "dpnoshadow"))
1891 shader.dpnoshadow = true;
1892 else if (!strcasecmp(parameter[0], "sky") && numparameters >= 2)
1894 // some q3 skies don't have the sky parm set
1895 shader.surfaceparms |= Q3SURFACEPARM_SKY;
1896 strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
1898 else if (!strcasecmp(parameter[0], "skyparms") && numparameters >= 2)
1900 // some q3 skies don't have the sky parm set
1901 shader.surfaceparms |= Q3SURFACEPARM_SKY;
1902 if (!atoi(parameter[1]) && strcasecmp(parameter[1], "-"))
1903 strlcpy(shader.skyboxname, parameter[1], sizeof(shader.skyboxname));
1905 else if (!strcasecmp(parameter[0], "cull") && numparameters >= 2)
1907 if (!strcasecmp(parameter[1], "disable") || !strcasecmp(parameter[1], "none") || !strcasecmp(parameter[1], "twosided"))
1908 shader.textureflags |= Q3TEXTUREFLAG_TWOSIDED;
1910 else if (!strcasecmp(parameter[0], "nomipmaps"))
1911 shader.surfaceparms |= Q3SURFACEPARM_NOMIPMAPS;
1912 else if (!strcasecmp(parameter[0], "nopicmip"))
1913 shader.textureflags |= Q3TEXTUREFLAG_NOPICMIP;
1914 else if (!strcasecmp(parameter[0], "polygonoffset"))
1915 shader.textureflags |= Q3TEXTUREFLAG_POLYGONOFFSET;
1916 else if (!strcasecmp(parameter[0], "dp_refract") && numparameters >= 5)
1918 shader.textureflags |= Q3TEXTUREFLAG_REFRACTION;
1919 shader.refractfactor = atof(parameter[1]);
1920 Vector4Set(shader.refractcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), 1);
1922 else if (!strcasecmp(parameter[0], "dp_reflect") && numparameters >= 6)
1924 shader.textureflags |= Q3TEXTUREFLAG_REFLECTION;
1925 shader.reflectfactor = atof(parameter[1]);
1926 Vector4Set(shader.reflectcolor4f, atof(parameter[2]), atof(parameter[3]), atof(parameter[4]), atof(parameter[5]));
1928 else if (!strcasecmp(parameter[0], "dp_water") && numparameters >= 12)
1930 shader.textureflags |= Q3TEXTUREFLAG_WATERSHADER;
1931 shader.reflectmin = atof(parameter[1]);
1932 shader.reflectmax = atof(parameter[2]);
1933 shader.refractfactor = atof(parameter[3]);
1934 shader.reflectfactor = atof(parameter[4]);
1935 Vector4Set(shader.refractcolor4f, atof(parameter[5]), atof(parameter[6]), atof(parameter[7]), 1);
1936 Vector4Set(shader.reflectcolor4f, atof(parameter[8]), atof(parameter[9]), atof(parameter[10]), 1);
1937 shader.r_water_wateralpha = atof(parameter[11]);
1939 else if (!strcasecmp(parameter[0], "dp_glossintensitymod") && numparameters >= 2)
1941 shader.specularscalemod = atof(parameter[1]);
1943 else if (!strcasecmp(parameter[0], "dp_glossexponentmod") && numparameters >= 2)
1945 shader.specularpowermod = atof(parameter[1]);
1947 else if (!strcasecmp(parameter[0], "deformvertexes") && numparameters >= 2)
1950 for (deformindex = 0;deformindex < Q3MAXDEFORMS;deformindex++)
1951 if (!shader.deforms[deformindex].deform)
1953 if (deformindex < Q3MAXDEFORMS)
1955 for (i = 0;i < numparameters - 2 && i < Q3DEFORM_MAXPARMS;i++)
1956 shader.deforms[deformindex].parms[i] = atof(parameter[i+2]);
1957 if (!strcasecmp(parameter[1], "projectionshadow")) shader.deforms[deformindex].deform = Q3DEFORM_PROJECTIONSHADOW;
1958 else if (!strcasecmp(parameter[1], "autosprite" )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE;
1959 else if (!strcasecmp(parameter[1], "autosprite2" )) shader.deforms[deformindex].deform = Q3DEFORM_AUTOSPRITE2;
1960 else if (!strcasecmp(parameter[1], "text0" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT0;
1961 else if (!strcasecmp(parameter[1], "text1" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT1;
1962 else if (!strcasecmp(parameter[1], "text2" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT2;
1963 else if (!strcasecmp(parameter[1], "text3" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT3;
1964 else if (!strcasecmp(parameter[1], "text4" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT4;
1965 else if (!strcasecmp(parameter[1], "text5" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT5;
1966 else if (!strcasecmp(parameter[1], "text6" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT6;
1967 else if (!strcasecmp(parameter[1], "text7" )) shader.deforms[deformindex].deform = Q3DEFORM_TEXT7;
1968 else if (!strcasecmp(parameter[1], "bulge" )) shader.deforms[deformindex].deform = Q3DEFORM_BULGE;
1969 else if (!strcasecmp(parameter[1], "normal" )) shader.deforms[deformindex].deform = Q3DEFORM_NORMAL;
1970 else if (!strcasecmp(parameter[1], "wave" ))
1972 shader.deforms[deformindex].deform = Q3DEFORM_WAVE;
1973 shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[3]);
1974 for (i = 0;i < numparameters - 4 && i < Q3WAVEPARMS;i++)
1975 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+4]);
1977 else if (!strcasecmp(parameter[1], "move" ))
1979 shader.deforms[deformindex].deform = Q3DEFORM_MOVE;
1980 shader.deforms[deformindex].wavefunc = Mod_LoadQ3Shaders_EnumerateWaveFunc(parameter[5]);
1981 for (i = 0;i < numparameters - 6 && i < Q3WAVEPARMS;i++)
1982 shader.deforms[deformindex].waveparms[i] = atof(parameter[i+6]);
1987 // pick the primary layer to render with
1988 if (shader.numlayers)
1990 shader.backgroundlayer = -1;
1991 shader.primarylayer = 0;
1992 // if lightmap comes first this is definitely an ordinary texture
1993 // if the first two layers have the correct blendfuncs and use vertex alpha, it is a blended terrain shader
1994 if ((shader.layers[shader.primarylayer].texturename != NULL)
1995 && !strcasecmp(shader.layers[shader.primarylayer].texturename[0], "$lightmap"))
1997 shader.backgroundlayer = -1;
1998 shader.primarylayer = 1;
2000 else if (shader.numlayers >= 2
2001 && shader.layers[1].alphagen.alphagen == Q3ALPHAGEN_VERTEX
2002 && (shader.layers[0].blendfunc[0] == GL_ONE && shader.layers[0].blendfunc[1] == GL_ZERO && !shader.layers[0].alphatest)
2003 && ((shader.layers[1].blendfunc[0] == GL_SRC_ALPHA && shader.layers[1].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2004 || (shader.layers[1].blendfunc[0] == GL_ONE && shader.layers[1].blendfunc[1] == GL_ZERO && shader.layers[1].alphatest)))
2006 // terrain blending or other effects
2007 shader.backgroundlayer = 0;
2008 shader.primarylayer = 1;
2011 // fix up multiple reflection types
2012 if(shader.textureflags & Q3TEXTUREFLAG_WATERSHADER)
2013 shader.textureflags &= ~(Q3TEXTUREFLAG_REFRACTION | Q3TEXTUREFLAG_REFLECTION);
2015 Q3Shader_AddToHash (&shader);
2019 FS_FreeSearch(search);
2022 q3shaderinfo_t *Mod_LookupQ3Shader(const char *name)
2024 unsigned short hash;
2025 q3shader_hash_entry_t* entry;
2027 Mod_LoadQ3Shaders();
2028 hash = CRC_Block_CaseInsensitive ((const unsigned char *)name, strlen (name));
2029 entry = q3shader_data->hash + (hash % Q3SHADER_HASH_SIZE);
2030 while (entry != NULL)
2032 if (strcasecmp (entry->shader.name, name) == 0)
2033 return &entry->shader;
2034 entry = entry->chain;
2039 qboolean Mod_LoadTextureFromQ3Shader(texture_t *texture, const char *name, qboolean warnmissing, qboolean fallback, int defaulttexflags)
2043 qboolean success = true;
2044 q3shaderinfo_t *shader;
2047 strlcpy(texture->name, name, sizeof(texture->name));
2048 shader = name[0] ? Mod_LookupQ3Shader(name) : NULL;
2051 if(!(defaulttexflags & TEXF_PICMIP))
2052 texflagsmask &= ~TEXF_PICMIP;
2053 if(!(defaulttexflags & TEXF_COMPRESS))
2054 texflagsmask &= ~TEXF_COMPRESS;
2055 texture->specularscalemod = 1; // unless later loaded from the shader
2056 texture->specularpowermod = 1; // unless later loaded from the shader
2060 if (developer_loading.integer)
2061 Con_Printf("%s: loaded shader for %s\n", loadmodel->name, name);
2062 texture->surfaceparms = shader->surfaceparms;
2064 // allow disabling of picmip or compression by defaulttexflags
2065 texture->textureflags = shader->textureflags & texflagsmask;
2067 if (shader->surfaceparms & Q3SURFACEPARM_SKY)
2069 texture->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2070 if (shader->skyboxname[0])
2072 // quake3 seems to append a _ to the skybox name, so this must do so as well
2073 dpsnprintf(loadmodel->brush.skybox, sizeof(loadmodel->brush.skybox), "%s_", shader->skyboxname);
2076 else if ((texture->surfaceflags & Q3SURFACEFLAG_NODRAW) || shader->numlayers == 0)
2077 texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2079 texture->basematerialflags = MATERIALFLAG_WALL;
2081 if (shader->layers[0].alphatest)
2082 texture->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
2083 if (shader->textureflags & Q3TEXTUREFLAG_TWOSIDED)
2084 texture->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_NOCULLFACE;
2085 if (shader->textureflags & Q3TEXTUREFLAG_POLYGONOFFSET)
2086 texture->biaspolygonoffset -= 2;
2087 if (shader->textureflags & Q3TEXTUREFLAG_REFRACTION)
2088 texture->basematerialflags |= MATERIALFLAG_REFRACTION;
2089 if (shader->textureflags & Q3TEXTUREFLAG_REFLECTION)
2090 texture->basematerialflags |= MATERIALFLAG_REFLECTION;
2091 if (shader->textureflags & Q3TEXTUREFLAG_WATERSHADER)
2092 texture->basematerialflags |= MATERIALFLAG_WATERSHADER;
2093 texture->customblendfunc[0] = GL_ONE;
2094 texture->customblendfunc[1] = GL_ZERO;
2095 if (shader->numlayers > 0)
2097 texture->customblendfunc[0] = shader->layers[0].blendfunc[0];
2098 texture->customblendfunc[1] = shader->layers[0].blendfunc[1];
2100 Q3 shader blendfuncs actually used in the game (* = supported by DP)
2101 * additive GL_ONE GL_ONE
2102 additive weird GL_ONE GL_SRC_ALPHA
2103 additive weird 2 GL_ONE GL_ONE_MINUS_SRC_ALPHA
2104 * alpha GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
2105 alpha inverse GL_ONE_MINUS_SRC_ALPHA GL_SRC_ALPHA
2106 brighten GL_DST_COLOR GL_ONE
2107 brighten GL_ONE GL_SRC_COLOR
2108 brighten weird GL_DST_COLOR GL_ONE_MINUS_DST_ALPHA
2109 brighten weird 2 GL_DST_COLOR GL_SRC_ALPHA
2110 * modulate GL_DST_COLOR GL_ZERO
2111 * modulate GL_ZERO GL_SRC_COLOR
2112 modulate inverse GL_ZERO GL_ONE_MINUS_SRC_COLOR
2113 modulate inverse alpha GL_ZERO GL_SRC_ALPHA
2114 modulate weird inverse GL_ONE_MINUS_DST_COLOR GL_ZERO
2115 * modulate x2 GL_DST_COLOR GL_SRC_COLOR
2116 * no blend GL_ONE GL_ZERO
2117 nothing GL_ZERO GL_ONE
2119 // if not opaque, figure out what blendfunc to use
2120 if (shader->layers[0].blendfunc[0] != GL_ONE || shader->layers[0].blendfunc[1] != GL_ZERO)
2122 if (shader->layers[0].blendfunc[0] == GL_ONE && shader->layers[0].blendfunc[1] == GL_ONE)
2123 texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2124 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE)
2125 texture->basematerialflags |= MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2126 else if (shader->layers[0].blendfunc[0] == GL_SRC_ALPHA && shader->layers[0].blendfunc[1] == GL_ONE_MINUS_SRC_ALPHA)
2127 texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2129 texture->basematerialflags |= MATERIALFLAG_CUSTOMBLEND | MATERIALFLAG_FULLBRIGHT | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2132 if (!shader->lighting)
2133 texture->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
2134 if (shader->primarylayer >= 0)
2136 q3shaderinfo_layer_t* primarylayer = shader->layers + shader->primarylayer;
2137 // copy over many primarylayer parameters
2138 texture->rgbgen = primarylayer->rgbgen;
2139 texture->alphagen = primarylayer->alphagen;
2140 texture->tcgen = primarylayer->tcgen;
2141 memcpy(texture->tcmods, primarylayer->tcmods, sizeof(texture->tcmods));
2142 // load the textures
2143 texture->numskinframes = primarylayer->numframes;
2144 texture->skinframerate = primarylayer->framerate;
2145 for (j = 0;j < primarylayer->numframes;j++)
2147 if(cls.state == ca_dedicated)
2149 texture->skinframes[j] = NULL;
2151 else if (!(texture->skinframes[j] = R_SkinFrame_LoadExternal(primarylayer->texturename[j], primarylayer->texflags & texflagsmask, false)))
2153 Con_Printf("^1%s:^7 could not load texture ^3\"%s\"^7 (frame %i) for shader ^2\"%s\"\n", loadmodel->name, primarylayer->texturename[j], j, texture->name);
2154 texture->skinframes[j] = R_SkinFrame_LoadMissing();
2158 if (shader->backgroundlayer >= 0)
2160 q3shaderinfo_layer_t* backgroundlayer = shader->layers + shader->backgroundlayer;
2161 // copy over one secondarylayer parameter
2162 memcpy(texture->backgroundtcmods, backgroundlayer->tcmods, sizeof(texture->backgroundtcmods));
2163 // load the textures
2164 texture->backgroundnumskinframes = backgroundlayer->numframes;
2165 texture->backgroundskinframerate = backgroundlayer->framerate;
2166 for (j = 0;j < backgroundlayer->numframes;j++)
2168 if(cls.state == ca_dedicated)
2170 texture->skinframes[j] = NULL;
2172 else if (!(texture->backgroundskinframes[j] = R_SkinFrame_LoadExternal(backgroundlayer->texturename[j], backgroundlayer->texflags & texflagsmask, false)))
2174 Con_Printf("^1%s:^7 could not load texture ^3\"%s\"^7 (background frame %i) for shader ^2\"%s\"\n", loadmodel->name, backgroundlayer->texturename[j], j, texture->name);
2175 texture->backgroundskinframes[j] = R_SkinFrame_LoadMissing();
2179 if (shader->dpshadow)
2180 texture->basematerialflags &= ~MATERIALFLAG_NOSHADOW;
2181 if (shader->dpnoshadow)
2182 texture->basematerialflags |= MATERIALFLAG_NOSHADOW;
2183 memcpy(texture->deforms, shader->deforms, sizeof(texture->deforms));
2184 texture->reflectmin = shader->reflectmin;
2185 texture->reflectmax = shader->reflectmax;
2186 texture->refractfactor = shader->refractfactor;
2187 Vector4Copy(shader->refractcolor4f, texture->refractcolor4f);
2188 texture->reflectfactor = shader->reflectfactor;
2189 Vector4Copy(shader->reflectcolor4f, texture->reflectcolor4f);
2190 texture->r_water_wateralpha = shader->r_water_wateralpha;
2191 texture->specularscalemod = shader->specularscalemod;
2192 texture->specularpowermod = shader->specularpowermod;
2194 else if (!strcmp(texture->name, "noshader") || !texture->name[0])
2196 if (developer.integer >= 100)
2197 Con_Printf("^1%s:^7 using fallback noshader material for ^3\"%s\"\n", loadmodel->name, name);
2198 texture->surfaceparms = 0;
2200 else if (!strcmp(texture->name, "common/nodraw") || !strcmp(texture->name, "textures/common/nodraw"))
2202 if (developer.integer >= 100)
2203 Con_Printf("^1%s:^7 using fallback nodraw material for ^3\"%s\"\n", loadmodel->name, name);
2204 texture->surfaceparms = 0;
2205 texture->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2209 if (developer.integer >= 100)
2210 Con_Printf("^1%s:^7 No shader found for texture ^3\"%s\"\n", loadmodel->name, texture->name);
2211 texture->surfaceparms = 0;
2212 if (texture->surfaceflags & Q3SURFACEFLAG_NODRAW)
2213 texture->basematerialflags |= MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
2214 else if (texture->surfaceflags & Q3SURFACEFLAG_SKY)
2215 texture->basematerialflags |= MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
2217 texture->basematerialflags |= MATERIALFLAG_WALL;
2218 texture->numskinframes = 1;
2219 if(cls.state == ca_dedicated)
2221 texture->skinframes[0] = NULL;
2228 if ((texture->skinframes[0] = R_SkinFrame_LoadExternal_CheckAlpha(texture->name, defaulttexflags, false, &has_alpha)))
2230 if(has_alpha && (defaulttexflags & TEXF_ALPHA))
2231 texture->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
2238 if (!success && warnmissing)
2239 Con_Printf("^1%s:^7 could not load texture ^3\"%s\"\n", loadmodel->name, texture->name);
2242 // init the animation variables
2243 texture->currentframe = texture;
2244 if (texture->numskinframes < 1)
2245 texture->numskinframes = 1;
2246 if (!texture->skinframes[0])
2247 texture->skinframes[0] = R_SkinFrame_LoadMissing();
2248 texture->currentskinframe = texture->skinframes[0];
2249 texture->backgroundcurrentskinframe = texture->backgroundskinframes[0];
2253 skinfile_t *Mod_LoadSkinFiles(void)
2255 int i, words, line, wordsoverflow;
2258 skinfile_t *skinfile = NULL, *first = NULL;
2259 skinfileitem_t *skinfileitem;
2260 char word[10][MAX_QPATH];
2264 U_bodyBox,models/players/Legoman/BikerA2.tga
2265 U_RArm,models/players/Legoman/BikerA1.tga
2266 U_LArm,models/players/Legoman/BikerA1.tga
2267 U_armor,common/nodraw
2268 U_sword,common/nodraw
2269 U_shield,common/nodraw
2270 U_homb,common/nodraw
2271 U_backpack,common/nodraw
2272 U_colcha,common/nodraw
2277 memset(word, 0, sizeof(word));
2278 for (i = 0;i < 256 && (data = text = (char *)FS_LoadFile(va("%s_%i.skin", loadmodel->name, i), tempmempool, true, NULL));i++)
2280 // If it's the first file we parse
2281 if (skinfile == NULL)
2283 skinfile = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2288 skinfile->next = (skinfile_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfile_t));
2289 skinfile = skinfile->next;
2291 skinfile->next = NULL;
2293 for(line = 0;;line++)
2296 if (!COM_ParseToken_QuakeC(&data, true))
2298 if (!strcmp(com_token, "\n"))
2301 wordsoverflow = false;
2305 strlcpy(word[words++], com_token, sizeof (word[0]));
2307 wordsoverflow = true;
2309 while (COM_ParseToken_QuakeC(&data, true) && strcmp(com_token, "\n"));
2312 Con_Printf("Mod_LoadSkinFiles: parsing error in file \"%s_%i.skin\" on line #%i: line with too many statements, skipping\n", loadmodel->name, i, line);
2315 // words is always >= 1
2316 if (!strcmp(word[0], "replace"))
2320 if (developer_loading.integer)
2321 Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[1], word[2]);
2322 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2323 skinfileitem->next = skinfile->items;
2324 skinfile->items = skinfileitem;
2325 strlcpy (skinfileitem->name, word[1], sizeof (skinfileitem->name));
2326 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2329 Con_Printf("Mod_LoadSkinFiles: parsing error in file \"%s_%i.skin\" on line #%i: wrong number of parameters to command \"%s\", see documentation in DP_GFX_SKINFILES extension in dpextensions.qc\n", loadmodel->name, i, line, word[0]);
2331 else if (words >= 2 && !strncmp(word[0], "tag_", 4))
2333 // tag name, like "tag_weapon,"
2334 // not used for anything (not even in Quake3)
2336 else if (words >= 2 && !strcmp(word[1], ","))
2338 // mesh shader name, like "U_RArm,models/players/Legoman/BikerA1.tga"
2339 if (developer_loading.integer)
2340 Con_Printf("Mod_LoadSkinFiles: parsed mesh \"%s\" shader replacement \"%s\"\n", word[0], word[2]);
2341 skinfileitem = (skinfileitem_t *)Mem_Alloc(loadmodel->mempool, sizeof(skinfileitem_t));
2342 skinfileitem->next = skinfile->items;
2343 skinfile->items = skinfileitem;
2344 strlcpy (skinfileitem->name, word[0], sizeof (skinfileitem->name));
2345 strlcpy (skinfileitem->replacement, word[2], sizeof (skinfileitem->replacement));
2348 Con_Printf("Mod_LoadSkinFiles: parsing error in file \"%s_%i.skin\" on line #%i: does not look like tag or mesh specification, or replace command, see documentation in DP_GFX_SKINFILES extension in dpextensions.qc\n", loadmodel->name, i, line);
2353 loadmodel->numskins = i;
2357 void Mod_FreeSkinFiles(skinfile_t *skinfile)
2360 skinfileitem_t *skinfileitem, *nextitem;
2361 for (;skinfile;skinfile = next)
2363 next = skinfile->next;
2364 for (skinfileitem = skinfile->items;skinfileitem;skinfileitem = nextitem)
2366 nextitem = skinfileitem->next;
2367 Mem_Free(skinfileitem);
2373 int Mod_CountSkinFiles(skinfile_t *skinfile)
2376 for (i = 0;skinfile;skinfile = skinfile->next, i++);
2380 void Mod_SnapVertices(int numcomponents, int numvertices, float *vertices, float snap)
2383 double isnap = 1.0 / snap;
2384 for (i = 0;i < numvertices*numcomponents;i++)
2385 vertices[i] = floor(vertices[i]*isnap)*snap;
2388 int Mod_RemoveDegenerateTriangles(int numtriangles, const int *inelement3i, int *outelement3i, const float *vertex3f)
2390 int i, outtriangles;
2391 float edgedir1[3], edgedir2[3], temp[3];
2392 // a degenerate triangle is one with no width (thickness, surface area)
2393 // these are characterized by having all 3 points colinear (along a line)
2394 // or having two points identical
2395 // the simplest check is to calculate the triangle's area
2396 for (i = 0, outtriangles = 0;i < numtriangles;i++, inelement3i += 3)
2398 // calculate first edge
2399 VectorSubtract(vertex3f + inelement3i[1] * 3, vertex3f + inelement3i[0] * 3, edgedir1);
2400 VectorSubtract(vertex3f + inelement3i[2] * 3, vertex3f + inelement3i[0] * 3, edgedir2);
2401 CrossProduct(edgedir1, edgedir2, temp);
2402 if (VectorLength2(temp) < 0.001f)
2403 continue; // degenerate triangle (no area)
2404 // valid triangle (has area)
2405 VectorCopy(inelement3i, outelement3i);
2409 return outtriangles;
2412 void Mod_VertexRangeFromElements(int numelements, const int *elements, int *firstvertexpointer, int *lastvertexpointer)
2415 int firstvertex, lastvertex;
2416 if (numelements > 0 && elements)
2418 firstvertex = lastvertex = elements[0];
2419 for (i = 1;i < numelements;i++)
2422 firstvertex = min(firstvertex, e);
2423 lastvertex = max(lastvertex, e);
2427 firstvertex = lastvertex = 0;
2428 if (firstvertexpointer)
2429 *firstvertexpointer = firstvertex;
2430 if (lastvertexpointer)
2431 *lastvertexpointer = lastvertex;
2434 void Mod_MakeSortedSurfaces(dp_model_t *mod)
2436 // make an optimal set of texture-sorted batches to draw...
2438 int *firstsurfacefortexture;
2439 int *numsurfacesfortexture;
2440 if (!mod->sortedmodelsurfaces)
2441 mod->sortedmodelsurfaces = (int *) Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
2442 firstsurfacefortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*firstsurfacefortexture));
2443 numsurfacesfortexture = (int *) Mem_Alloc(tempmempool, mod->num_textures * sizeof(*numsurfacesfortexture));
2444 memset(numsurfacesfortexture, 0, mod->num_textures * sizeof(*numsurfacesfortexture));
2445 for (j = 0;j < mod->nummodelsurfaces;j++)
2447 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2448 int t = (int)(surface->texture - mod->data_textures);
2449 numsurfacesfortexture[t]++;
2452 for (t = 0;t < mod->num_textures;t++)
2454 firstsurfacefortexture[t] = j;
2455 j += numsurfacesfortexture[t];
2457 for (j = 0;j < mod->nummodelsurfaces;j++)
2459 const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
2460 int t = (int)(surface->texture - mod->data_textures);
2461 mod->sortedmodelsurfaces[firstsurfacefortexture[t]++] = j + mod->firstmodelsurface;
2463 Mem_Free(firstsurfacefortexture);
2464 Mem_Free(numsurfacesfortexture);
2467 static void Mod_BuildVBOs(void)
2469 if (developer.integer && loadmodel->surfmesh.data_element3s && loadmodel->surfmesh.data_element3i)
2472 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2474 if (loadmodel->surfmesh.data_element3s[i] != loadmodel->surfmesh.data_element3i[i])
2476 Con_Printf("Mod_BuildVBOs: element %u is incorrect (%u should be %u)\n", i, loadmodel->surfmesh.data_element3s[i], loadmodel->surfmesh.data_element3i[i]);
2477 loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2482 if (!gl_support_arb_vertex_buffer_object)
2485 // element buffer is easy because it's just one array
2486 if (loadmodel->surfmesh.num_triangles)
2488 if (loadmodel->surfmesh.data_element3s)
2489 loadmodel->surfmesh.ebo3s = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]), loadmodel->name);
2491 loadmodel->surfmesh.ebo3i = R_Mesh_CreateStaticBufferObject(GL_ELEMENT_ARRAY_BUFFER_ARB, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles * sizeof(unsigned int[3]), loadmodel->name);
2494 // vertex buffer is several arrays and we put them in the same buffer
2496 // is this wise? the texcoordtexture2f array is used with dynamic
2497 // vertex/svector/tvector/normal when rendering animated models, on the
2498 // other hand animated models don't use a lot of vertices anyway...
2499 if (loadmodel->surfmesh.num_vertices)
2504 loadmodel->surfmesh.vbooffset_vertex3f = size;if (loadmodel->surfmesh.data_vertex3f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2505 loadmodel->surfmesh.vbooffset_svector3f = size;if (loadmodel->surfmesh.data_svector3f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2506 loadmodel->surfmesh.vbooffset_tvector3f = size;if (loadmodel->surfmesh.data_tvector3f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2507 loadmodel->surfmesh.vbooffset_normal3f = size;if (loadmodel->surfmesh.data_normal3f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[3]);
2508 loadmodel->surfmesh.vbooffset_texcoordtexture2f = size;if (loadmodel->surfmesh.data_texcoordtexture2f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2509 loadmodel->surfmesh.vbooffset_texcoordlightmap2f = size;if (loadmodel->surfmesh.data_texcoordlightmap2f) size += loadmodel->surfmesh.num_vertices * sizeof(float[2]);
2510 loadmodel->surfmesh.vbooffset_lightmapcolor4f = size;if (loadmodel->surfmesh.data_lightmapcolor4f ) size += loadmodel->surfmesh.num_vertices * sizeof(float[4]);
2511 mem = (unsigned char *)Mem_Alloc(tempmempool, size);
2512 if (loadmodel->surfmesh.data_vertex3f ) memcpy(mem + loadmodel->surfmesh.vbooffset_vertex3f , loadmodel->surfmesh.data_vertex3f , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2513 if (loadmodel->surfmesh.data_svector3f ) memcpy(mem + loadmodel->surfmesh.vbooffset_svector3f , loadmodel->surfmesh.data_svector3f , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2514 if (loadmodel->surfmesh.data_tvector3f ) memcpy(mem + loadmodel->surfmesh.vbooffset_tvector3f , loadmodel->surfmesh.data_tvector3f , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2515 if (loadmodel->surfmesh.data_normal3f ) memcpy(mem + loadmodel->surfmesh.vbooffset_normal3f , loadmodel->surfmesh.data_normal3f , loadmodel->surfmesh.num_vertices * sizeof(float[3]));
2516 if (loadmodel->surfmesh.data_texcoordtexture2f ) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordtexture2f , loadmodel->surfmesh.data_texcoordtexture2f , loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2517 if (loadmodel->surfmesh.data_texcoordlightmap2f) memcpy(mem + loadmodel->surfmesh.vbooffset_texcoordlightmap2f, loadmodel->surfmesh.data_texcoordlightmap2f, loadmodel->surfmesh.num_vertices * sizeof(float[2]));
2518 if (loadmodel->surfmesh.data_lightmapcolor4f ) memcpy(mem + loadmodel->surfmesh.vbooffset_lightmapcolor4f , loadmodel->surfmesh.data_lightmapcolor4f , loadmodel->surfmesh.num_vertices * sizeof(float[4]));
2519 loadmodel->surfmesh.vbo = R_Mesh_CreateStaticBufferObject(GL_ARRAY_BUFFER_ARB, mem, size, loadmodel->name);
2524 static void Mod_Decompile_OBJ(dp_model_t *model, const char *filename, const char *mtlfilename, const char *originalfilename)
2526 int vertexindex, surfaceindex, triangleindex, textureindex, countvertices = 0, countsurfaces = 0, countfaces = 0, counttextures = 0;
2528 const char *texname;
2530 const float *v, *vn, *vt;
2532 size_t outbufferpos = 0;
2533 size_t outbuffermax = 0x100000;
2534 char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
2535 const msurface_t *surface;
2536 const int maxtextures = 256;
2537 char *texturenames = (char *) Z_Malloc(maxtextures * MAX_QPATH);
2539 // construct the mtllib file
2540 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "# mtllib for %s exported by darkplaces engine\n", originalfilename);
2543 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2546 countvertices += surface->num_vertices;
2547 countfaces += surface->num_triangles;
2548 texname = (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default";
2549 for (textureindex = 0;textureindex < counttextures;textureindex++)
2550 if (!strcmp(texturenames + textureindex * MAX_QPATH, texname))
2552 if (textureindex < counttextures)
2553 continue; // already wrote this material entry
2554 if (textureindex >= maxtextures)
2555 continue; // just a precaution
2556 textureindex = counttextures++;
2557 strlcpy(texturenames + textureindex * MAX_QPATH, texname, MAX_QPATH);
2558 if (outbufferpos >= outbuffermax >> 1)
2561 oldbuffer = outbuffer;
2562 outbuffer = (char *) Z_Malloc(outbuffermax);
2563 memcpy(outbuffer, oldbuffer, outbufferpos);
2566 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "newmtl %s\nNs 96.078431\nKa 0 0 0\nKd 0.64 0.64 0.64\nKs 0.5 0.5 0.5\nNi 1\nd 1\nillum 2\nmap_Kd %s%s\n\n", texname, texname, strstr(texname, ".tga") ? "" : ".tga");
2571 // write the mtllib file
2572 FS_WriteFile(mtlfilename, outbuffer, outbufferpos);
2575 // construct the obj file
2576 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "# model exported from %s by darkplaces engine\n# %i vertices, %i faces, %i surfaces\nmtllib %s\n", originalfilename, countvertices, countfaces, countsurfaces, mtlfilename);
2579 for (vertexindex = 0, v = model->surfmesh.data_vertex3f, vn = model->surfmesh.data_normal3f, vt = model->surfmesh.data_texcoordtexture2f;vertexindex < model->surfmesh.num_vertices;vertexindex++, v += 3, vn += 3, vt += 2)
2581 if (outbufferpos >= outbuffermax >> 1)
2584 oldbuffer = outbuffer;
2585 outbuffer = (char *) Z_Malloc(outbuffermax);
2586 memcpy(outbuffer, oldbuffer, outbufferpos);
2589 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "v %f %f %f\nvn %f %f %f\nvt %f %f\n", v[0], v[2], -v[1], vn[0], vn[2], -vn[1], vt[0], 1-vt[1]);
2593 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2595 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "usemtl %s\n", (surface->texture && surface->texture->name[0]) ? surface->texture->name : "default");
2598 for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
2600 if (outbufferpos >= outbuffermax >> 1)
2603 oldbuffer = outbuffer;
2604 outbuffer = (char *) Z_Malloc(outbuffermax);
2605 memcpy(outbuffer, oldbuffer, outbufferpos);
2611 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "f %i/%i/%i %i/%i/%i %i/%i/%i\n", a,a,a,b,b,b,c,c,c);
2617 // write the obj file
2618 FS_WriteFile(filename, outbuffer, outbufferpos);
2622 Z_Free(texturenames);
2625 Con_Printf("Wrote %s (%i bytes, %i vertices, %i faces, %i surfaces with %i distinct textures)\n", filename, (int)outbufferpos, countvertices, countfaces, countsurfaces, counttextures);
2628 static void Mod_Decompile_SMD(dp_model_t *model, const char *filename, int firstpose, int numposes, qboolean writetriangles)
2630 int countnodes = 0, counttriangles = 0, countframes = 0;
2640 size_t outbufferpos = 0;
2641 size_t outbuffermax = 0x100000;
2642 char *outbuffer = (char *) Z_Malloc(outbuffermax), *oldbuffer;
2643 const msurface_t *surface;
2644 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "version 1\nnodes\n");
2648 if(model->num_poses >= 0)
2649 modelscale = sqrt(model->data_poses[0] * model->data_poses[0] + model->data_poses[1] * model->data_poses[1] + model->data_poses[2] * model->data_poses[2]);
2650 if(fabs(modelscale - 1) > 1e-4)
2652 if(firstpose == 0) // only print the when writing the reference pose
2653 Con_Printf("The model has an old-style model scale of %f\n", modelscale);
2657 for (transformindex = 0;transformindex < model->num_bones;transformindex++)
2659 if (outbufferpos >= outbuffermax >> 1)
2662 oldbuffer = outbuffer;
2663 outbuffer = (char *) Z_Malloc(outbuffermax);
2664 memcpy(outbuffer, oldbuffer, outbufferpos);
2668 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i \"%s\" %3i\n", transformindex, model->data_bones[transformindex].name, model->data_bones[transformindex].parent);
2672 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\nskeleton\n");
2675 for (poseindex = 0, pose = model->data_poses + model->num_bones * 12 * firstpose;poseindex < numposes;poseindex++)
2678 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "time %i\n", poseindex);
2681 for (transformindex = 0;transformindex < model->num_bones;transformindex++, pose += 12)
2686 if (outbufferpos >= outbuffermax >> 1)
2689 oldbuffer = outbuffer;
2690 outbuffer = (char *) Z_Malloc(outbuffermax);
2691 memcpy(outbuffer, oldbuffer, outbufferpos);
2695 // strangely the smd angles are for a transposed matrix, so we
2696 // have to generate a transposed matrix, then convert that...
2697 mtest[0][0] = pose[ 0];
2698 mtest[0][1] = pose[ 4];
2699 mtest[0][2] = pose[ 8];
2700 mtest[0][3] = pose[ 3];
2701 mtest[1][0] = pose[ 1];
2702 mtest[1][1] = pose[ 5];
2703 mtest[1][2] = pose[ 9];
2704 mtest[1][3] = pose[ 7];
2705 mtest[2][0] = pose[ 2];
2706 mtest[2][1] = pose[ 6];
2707 mtest[2][2] = pose[10];
2708 mtest[2][3] = pose[11];
2709 AnglesFromVectors(angles, mtest[0], mtest[2], false);
2710 if (angles[0] >= 180) angles[0] -= 360;
2711 if (angles[1] >= 180) angles[1] -= 360;
2712 if (angles[2] >= 180) angles[2] -= 360;
2714 a = DEG2RAD(angles[ROLL]);
2715 b = DEG2RAD(angles[PITCH]);
2716 c = DEG2RAD(angles[YAW]);
2720 float cy, sy, cp, sp, cr, sr;
2722 // smd matrix construction, for comparing to non-transposed m
2733 test[0][1] = sr*sp*cy+cr*-sy;
2734 test[1][1] = sr*sp*sy+cr*cy;
2736 test[0][2] = (cr*sp*cy+-sr*-sy);
2737 test[1][2] = (cr*sp*sy+-sr*cy);
2739 test[0][3] = pose[3];
2740 test[1][3] = pose[7];
2741 test[2][3] = pose[11];
2744 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f\n", transformindex, pose[3] * modelscale, pose[7] * modelscale, pose[11] * modelscale, DEG2RAD(angles[ROLL]), DEG2RAD(angles[PITCH]), DEG2RAD(angles[YAW]));
2749 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
2754 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "triangles\n");
2757 for (surfaceindex = 0, surface = model->data_surfaces;surfaceindex < model->num_surfaces;surfaceindex++, surface++)
2759 for (triangleindex = 0, e = model->surfmesh.data_element3i + surface->num_firsttriangle * 3;triangleindex < surface->num_triangles;triangleindex++, e += 3)
2762 if (outbufferpos >= outbuffermax >> 1)
2765 oldbuffer = outbuffer;
2766 outbuffer = (char *) Z_Malloc(outbuffermax);
2767 memcpy(outbuffer, oldbuffer, outbufferpos);
2770 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%s\n", surface->texture && surface->texture->name[0] ? surface->texture->name : "default.bmp");
2773 for (cornerindex = 0;cornerindex < 3;cornerindex++)
2775 const int index = e[2-cornerindex];
2776 const float *v = model->surfmesh.data_vertex3f + index * 3;
2777 const float *vn = model->surfmesh.data_normal3f + index * 3;
2778 const float *vt = model->surfmesh.data_texcoordtexture2f + index * 2;
2779 const int *wi = model->surfmesh.data_vertexweightindex4i + index * 4;
2780 const float *wf = model->surfmesh.data_vertexweightinfluence4f + index * 4;
2781 if (wf[3]) l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f 4 %i %f %i %f %i %f %i %f\n", wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1], wi[0], wf[0], wi[1], wf[1], wi[2], wf[2], wi[3], wf[3]);
2782 else if (wf[2]) l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f 3 %i %f %i %f %i %f\n" , wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1], wi[0], wf[0], wi[1], wf[1], wi[2], wf[2]);
2783 else if (wf[1]) l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f 2 %i %f %i %f\n" , wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1], wi[0], wf[0], wi[1], wf[1]);
2784 else l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "%3i %f %f %f %f %f %f %f %f\n" , wi[0], v[0], v[1], v[2], vn[0], vn[1], vn[2], vt[0], 1 - vt[1]);
2790 l = dpsnprintf(outbuffer + outbufferpos, outbuffermax - outbufferpos, "end\n");
2795 FS_WriteFile(filename, outbuffer, outbufferpos);
2798 Con_Printf("Wrote %s (%i bytes, %i nodes, %i frames, %i triangles)\n", filename, (int)outbufferpos, countnodes, countframes, counttriangles);
2805 decompiles a model to editable files
2808 static void Mod_Decompile_f(void)
2810 int i, j, k, l, first, count;
2812 char inname[MAX_QPATH];
2813 char outname[MAX_QPATH];
2814 char mtlname[MAX_QPATH];
2815 char basename[MAX_QPATH];
2816 char animname[MAX_QPATH];
2817 char animname2[MAX_QPATH];
2818 char zymtextbuffer[16384];
2819 char dpmtextbuffer[16384];
2820 int zymtextsize = 0;
2821 int dpmtextsize = 0;
2823 if (Cmd_Argc() != 2)
2825 Con_Print("usage: modeldecompile <filename>\n");
2829 strlcpy(inname, Cmd_Argv(1), sizeof(inname));
2830 FS_StripExtension(inname, basename, sizeof(basename));
2832 mod = Mod_ForName(inname, false, true, inname[0] == '*' ? cl.model_name[1] : NULL);
2833 if (mod->brush.submodel)
2835 // if we're decompiling a submodel, be sure to give it a proper name based on its parent
2836 FS_StripExtension(cl.model_name[1], outname, sizeof(outname));
2837 dpsnprintf(basename, sizeof(basename), "%s/%s", outname, mod->name);
2842 Con_Print("No such model\n");
2845 if (!mod->surfmesh.num_triangles)
2847 Con_Print("Empty model (or sprite)\n");
2851 // export OBJ if possible (not on sprites)
2852 if (mod->surfmesh.num_triangles)
2854 dpsnprintf(outname, sizeof(outname), "%s_decompiled.obj", basename);
2855 dpsnprintf(mtlname, sizeof(mtlname), "%s_decompiled.mtl", basename);
2856 Mod_Decompile_OBJ(mod, outname, mtlname, inname);
2859 // export SMD if possible (only for skeletal models)
2860 if (mod->surfmesh.num_triangles && mod->num_bones)
2862 dpsnprintf(outname, sizeof(outname), "%s_decompiled/ref1.smd", basename);
2863 Mod_Decompile_SMD(mod, outname, 0, 1, true);
2864 l = dpsnprintf(zymtextbuffer + zymtextsize, sizeof(zymtextbuffer) - zymtextsize, "output out.zym\nscale 1\norigin 0 0 0\nmesh ref1.smd\n");
2865 if (l > 0) zymtextsize += l;
2866 l = dpsnprintf(dpmtextbuffer + dpmtextsize, sizeof(dpmtextbuffer) - dpmtextsize, "outputdir .\nmodel out\nscale 1\norigin 0 0 0\nscene ref1.smd\n");
2867 if (l > 0) dpmtextsize += l;
2868 for (i = 0;i < mod->numframes;i = j)
2870 strlcpy(animname, mod->animscenes[i].name, sizeof(animname));
2871 first = mod->animscenes[i].firstframe;
2872 if (mod->animscenes[i].framecount > 1)
2875 count = mod->animscenes[i].framecount;
2881 // check for additional frames with same name
2882 for (l = 0, k = strlen(animname);animname[l];l++)
2883 if ((animname[l] < '0' || animname[l] > '9') && animname[l] != '_')
2886 count = mod->num_poses - first;
2887 for (j = i + 1;j < mod->numframes;j++)
2889 strlcpy(animname2, mod->animscenes[j].name, sizeof(animname2));
2890 for (l = 0, k = strlen(animname2);animname2[l];l++)
2891 if ((animname2[l] < '0' || animname2[l] > '9') && animname2[l] != '_')
2894 if (strcmp(animname2, animname) || mod->animscenes[j].framecount > 1)
2896 count = mod->animscenes[j].firstframe - first;
2900 // if it's only one frame, use the original frame name
2902 strlcpy(animname, mod->animscenes[i].name, sizeof(animname));
2905 dpsnprintf(outname, sizeof(outname), "%s_decompiled/%s.smd", basename, animname);
2906 Mod_Decompile_SMD(mod, outname, first, count, false);
2907 if (zymtextsize < (int)sizeof(zymtextbuffer) - 100)
2909 l = dpsnprintf(zymtextbuffer + zymtextsize, sizeof(zymtextbuffer) - zymtextsize, "scene %s.smd fps %g\n", animname, mod->animscenes[i].framerate);
2910 if (l > 0) zymtextsize += l;
2912 if (dpmtextsize < (int)sizeof(dpmtextbuffer) - 100)
2914 l = dpsnprintf(dpmtextbuffer + dpmtextsize, sizeof(dpmtextbuffer) - dpmtextsize, "scene %s.smd\n", animname);
2915 if (l > 0) dpmtextsize += l;
2919 FS_WriteFile(va("%s_decompiled/out_zym.txt", basename), zymtextbuffer, (fs_offset_t)zymtextsize);
2921 FS_WriteFile(va("%s_decompiled/out_dpm.txt", basename), dpmtextbuffer, (fs_offset_t)dpmtextsize);
2925 void Mod_AllocLightmap_Init(mod_alloclightmap_state_t *state, int width, int height)
2928 memset(state, 0, sizeof(*state));
2929 state->width = width;
2930 state->height = height;
2931 state->currentY = 0;
2932 state->rows = Mem_Alloc(tempmempool, state->height * sizeof(*state->rows));
2933 for (y = 0;y < state->height;y++)
2935 state->rows[y].currentX = 0;
2936 state->rows[y].rowY = -1;
2940 void Mod_AllocLightmap_Reset(mod_alloclightmap_state_t *state)
2943 state->currentY = 0;
2944 for (y = 0;y < state->height;y++)
2946 state->rows[y].currentX = 0;
2947 state->rows[y].rowY = -1;
2951 void Mod_AllocLightmap_Free(mod_alloclightmap_state_t *state)
2954 Mem_Free(state->rows);
2955 memset(state, 0, sizeof(*state));
2958 qboolean Mod_AllocLightmap_Block(mod_alloclightmap_state_t *state, int blockwidth, int blockheight, int *outx, int *outy)
2960 mod_alloclightmap_row_t *row;
2963 row = state->rows + blockheight;
2964 if ((row->rowY < 0) || (row->currentX + blockwidth > state->width))
2966 if (state->currentY + blockheight <= state->height)
2968 // use the current allocation position
2969 row->rowY = state->currentY;
2971 state->currentY += blockheight;
2975 // find another position
2976 for (y = blockheight;y < state->height;y++)
2978 if ((state->rows[y].rowY >= 0) && (state->rows[y].currentX + blockwidth <= state->width))
2980 row = state->rows + y;
2984 if (y == state->height)
2989 *outx = row->currentX;
2990 row->currentX += blockwidth;
2995 typedef struct lightmapsample_s
2999 float *vertex_color;
3000 unsigned char *lm_bgr;
3001 unsigned char *lm_dir;
3005 typedef struct lightmapvertex_s
3010 float texcoordbase[2];
3011 float texcoordlightmap[2];
3012 float lightcolor[4];
3016 typedef struct lightmaptriangle_s
3024 // 2D modelspace coordinates of min corner
3025 // snapped to lightmap grid but not in grid coordinates
3027 // 2D modelspace to lightmap coordinate scale
3033 lightmaptriangle_t *mod_generatelightmaps_lightmaptriangles;
3035 extern void R_SampleRTLights(const float *pos, float *sh1);
3037 static void Mod_GenerateLightmaps_SamplePoint(const float *pos, float *sh1)
3040 for (i = 0;i < 4*3;i++)
3042 R_SampleRTLights(pos, sh1);
3045 static void Mod_GenerateLightmaps_LightmapSample(const float *pos, const float *normal, unsigned char *lm_bgr, unsigned char *lm_dir)
3050 Mod_GenerateLightmaps_SamplePoint(pos, sh1);
3051 VectorSet(dir, VectorLength(sh1 + 3), VectorLength(sh1 + 6), VectorLength(sh1 + 9));
3052 VectorNormalize(dir);
3053 VectorScale(sh1, 127.5f, color);
3054 VectorSet(dir, (dir[0]+1.0f)*127.5f, (dir[1]+1.0f)*127.5f, (dir[2]+1.0f)*127.5f);
3055 lm_bgr[0] = (unsigned char)bound(0.0f, color[2], 255.0f);
3056 lm_bgr[1] = (unsigned char)bound(0.0f, color[1], 255.0f);
3057 lm_bgr[2] = (unsigned char)bound(0.0f, color[0], 255.0f);
3059 lm_dir[0] = (unsigned char)dir[0];
3060 lm_dir[1] = (unsigned char)dir[1];
3061 lm_dir[2] = (unsigned char)dir[2];
3065 static void Mod_GenerateLightmaps_VertexSample(const float *pos, const float *normal, float *vertex_color)
3068 Mod_GenerateLightmaps_SamplePoint(pos, sh1);
3069 VectorCopy(sh1, vertex_color);
3072 static void Mod_GenerateLightmaps_GridSample(const float *pos, q3dlightgrid_t *s)
3078 Mod_GenerateLightmaps_SamplePoint(pos, sh1);
3079 // calculate the direction we'll use to reduce the sh1 to a directional light source
3080 VectorSet(dir, VectorLength(sh1 + 3), VectorLength(sh1 + 6), VectorLength(sh1 + 9));
3081 VectorNormalize(dir);
3082 // scale the ambient from 0-2 to 0-255
3083 VectorScale(sh1, 127.5f, ambient);
3084 // extract the diffuse color along the chosen direction and scale it
3085 diffuse[0] = (dir[0]*sh1[3] + dir[1]*sh1[6] + dir[2]*sh1[ 9] + sh1[0]) * 127.5f;
3086 diffuse[1] = (dir[0]*sh1[4] + dir[1]*sh1[7] + dir[2]*sh1[10] + sh1[1]) * 127.5f;
3087 diffuse[2] = (dir[0]*sh1[5] + dir[1]*sh1[8] + dir[2]*sh1[11] + sh1[2]) * 127.5f;
3088 // encode to the grid format
3089 s->ambientrgb[0] = (unsigned char)bound(0.0f, ambient[0], 255.0f);
3090 s->ambientrgb[1] = (unsigned char)bound(0.0f, ambient[1], 255.0f);
3091 s->ambientrgb[2] = (unsigned char)bound(0.0f, ambient[2], 255.0f);
3092 s->diffusergb[0] = (unsigned char)bound(0.0f, diffuse[0], 255.0f);
3093 s->diffusergb[1] = (unsigned char)bound(0.0f, diffuse[1], 255.0f);
3094 s->diffusergb[2] = (unsigned char)bound(0.0f, diffuse[2], 255.0f);
3095 if (dir[2] >= 0.99f) {s->diffuseyaw = 0;s->diffusepitch = 0;}
3096 else if (dir[2] <= -0.99f) {s->diffuseyaw = 0;s->diffusepitch = 128;}
3097 else {s->diffuseyaw = (unsigned char)(acos(dir[2]) * (127.5f/M_PI));s->diffusepitch = (unsigned char)(atan2(dir[1], dir[0]) * (127.5f/M_PI));}
3100 static void Mod_GenerateLightmaps_DestroyLightmaps(dp_model_t *model)
3102 msurface_t *surface;
3105 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3107 surface = model->data_surfaces + surfaceindex;
3108 surface->lightmaptexture = NULL;
3109 surface->deluxemaptexture = NULL;
3111 if (model->brushq3.data_lightmaps)
3113 for (i = 0;i < model->brushq3.num_mergedlightmaps;i++)
3114 R_FreeTexture(model->brushq3.data_lightmaps[i]);
3115 Mem_Free(model->brushq3.data_lightmaps);
3116 model->brushq3.data_lightmaps = NULL;
3118 if (model->brushq3.data_deluxemaps)
3120 for (i = 0;i < model->brushq3.num_mergedlightmaps;i++)
3121 R_FreeTexture(model->brushq3.data_deluxemaps[i]);
3122 Mem_Free(model->brushq3.data_deluxemaps);
3123 model->brushq3.data_deluxemaps = NULL;
3127 static void Mod_GenerateLightmaps_UnweldTriangles(dp_model_t *model)
3129 msurface_t *surface;
3135 surfmesh_t oldsurfmesh;
3137 unsigned char *data;
3138 oldsurfmesh = model->surfmesh;
3139 model->surfmesh.num_triangles = oldsurfmesh.num_triangles;
3140 model->surfmesh.num_vertices = oldsurfmesh.num_triangles * 3;
3142 size += model->surfmesh.num_vertices * sizeof(float[3]);
3143 size += model->surfmesh.num_vertices * sizeof(float[3]);
3144 size += model->surfmesh.num_vertices * sizeof(float[3]);
3145 size += model->surfmesh.num_vertices * sizeof(float[3]);
3146 size += model->surfmesh.num_vertices * sizeof(float[2]);
3147 size += model->surfmesh.num_vertices * sizeof(float[2]);
3148 size += model->surfmesh.num_vertices * sizeof(float[4]);
3149 data = (unsigned char *)Mem_Alloc(model->mempool, size);
3150 model->surfmesh.data_vertex3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3151 model->surfmesh.data_normal3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3152 model->surfmesh.data_svector3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3153 model->surfmesh.data_tvector3f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[3]);
3154 model->surfmesh.data_texcoordtexture2f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[2]);
3155 model->surfmesh.data_texcoordlightmap2f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[2]);
3156 model->surfmesh.data_lightmapcolor4f = (float *)data;data += model->surfmesh.num_vertices * sizeof(float[4]);
3157 if (model->surfmesh.num_vertices > 65536)
3158 model->surfmesh.data_element3s = NULL;
3160 if (model->surfmesh.vbo)
3161 R_Mesh_DestroyBufferObject(model->surfmesh.vbo);
3162 model->surfmesh.vbo = 0;
3163 if (model->surfmesh.ebo3i)
3164 R_Mesh_DestroyBufferObject(model->surfmesh.ebo3i);
3165 model->surfmesh.ebo3i = 0;
3166 if (model->surfmesh.ebo3s)
3167 R_Mesh_DestroyBufferObject(model->surfmesh.ebo3s);
3168 model->surfmesh.ebo3s = 0;
3170 // convert all triangles to unique vertex data
3172 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3174 surface = model->data_surfaces + surfaceindex;
3175 surface->num_firstvertex = outvertexindex;
3176 surface->num_vertices = surface->num_triangles*3;
3177 e = oldsurfmesh.data_element3i + surface->num_firsttriangle*3;
3178 for (i = 0;i < surface->num_triangles*3;i++)
3181 model->surfmesh.data_vertex3f[outvertexindex*3+0] = oldsurfmesh.data_vertex3f[vertexindex*3+0];
3182 model->surfmesh.data_vertex3f[outvertexindex*3+1] = oldsurfmesh.data_vertex3f[vertexindex*3+1];
3183 model->surfmesh.data_vertex3f[outvertexindex*3+2] = oldsurfmesh.data_vertex3f[vertexindex*3+2];
3184 model->surfmesh.data_normal3f[outvertexindex*3+0] = oldsurfmesh.data_normal3f[vertexindex*3+0];
3185 model->surfmesh.data_normal3f[outvertexindex*3+1] = oldsurfmesh.data_normal3f[vertexindex*3+1];
3186 model->surfmesh.data_normal3f[outvertexindex*3+2] = oldsurfmesh.data_normal3f[vertexindex*3+2];
3187 model->surfmesh.data_svector3f[outvertexindex*3+0] = oldsurfmesh.data_svector3f[vertexindex*3+0];
3188 model->surfmesh.data_svector3f[outvertexindex*3+1] = oldsurfmesh.data_svector3f[vertexindex*3+1];
3189 model->surfmesh.data_svector3f[outvertexindex*3+2] = oldsurfmesh.data_svector3f[vertexindex*3+2];
3190 model->surfmesh.data_tvector3f[outvertexindex*3+0] = oldsurfmesh.data_tvector3f[vertexindex*3+0];
3191 model->surfmesh.data_tvector3f[outvertexindex*3+1] = oldsurfmesh.data_tvector3f[vertexindex*3+1];
3192 model->surfmesh.data_tvector3f[outvertexindex*3+2] = oldsurfmesh.data_tvector3f[vertexindex*3+2];
3193 model->surfmesh.data_texcoordtexture2f[outvertexindex*2+0] = oldsurfmesh.data_texcoordtexture2f[vertexindex*2+0];
3194 model->surfmesh.data_texcoordtexture2f[outvertexindex*2+1] = oldsurfmesh.data_texcoordtexture2f[vertexindex*2+1];
3195 model->surfmesh.data_texcoordlightmap2f[outvertexindex*2+0] = oldsurfmesh.data_texcoordlightmap2f[vertexindex*2+0];
3196 model->surfmesh.data_texcoordlightmap2f[outvertexindex*2+1] = oldsurfmesh.data_texcoordlightmap2f[vertexindex*2+1];
3197 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+0] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+0];
3198 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+1] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+1];
3199 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+2] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+2];
3200 model->surfmesh.data_lightmapcolor4f[outvertexindex*4+3] = oldsurfmesh.data_lightmapcolor4f[vertexindex*4+3];
3201 model->surfmesh.data_element3i[surface->num_firsttriangle*3+i] = outvertexindex;
3205 if (model->surfmesh.data_element3s)
3206 for (i = 0;i < model->surfmesh.num_triangles*3;i++)
3207 model->surfmesh.data_element3s[i] = model->surfmesh.data_element3i[i];
3209 // find and update all submodels to use this new surfmesh data
3210 for (i = 0;i < model->brush.numsubmodels;i++)
3211 model->brush.submodels[i]->surfmesh = model->surfmesh;
3214 static void Mod_GenerateLightmaps_CreateTriangleInformation(dp_model_t *model)
3216 msurface_t *surface;
3220 lightmaptriangle_t *triangle;
3221 // generate lightmap triangle structs
3222 mod_generatelightmaps_lightmaptriangles = Mem_Alloc(model->mempool, model->surfmesh.num_triangles * sizeof(lightmaptriangle_t));
3223 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3225 surface = model->data_surfaces + surfaceindex;
3226 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
3227 for (i = 0;i < surface->num_triangles;i++)
3229 triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
3230 triangle->triangleindex = surface->num_firsttriangle+i;
3231 triangle->surfaceindex = surfaceindex;
3232 VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+0], triangle->vertex[0]);
3233 VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+1], triangle->vertex[1]);
3234 VectorCopy(model->surfmesh.data_vertex3f + 3*e[i*3+2], triangle->vertex[2]);
3240 float lmprojection[3][3][3] =
3242 {{0, 1, 0}, {0, 0, 1}, {1, 0, 0}},
3243 {{1, 0, 0}, {0, 0, 1}, {0, 1, 0}},
3244 {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}},
3248 static void Mod_GenerateLightmaps_ClassifyTriangles(dp_model_t *model)
3250 msurface_t *surface;
3258 lightmaptriangle_t *triangle;
3260 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3262 surface = model->data_surfaces + surfaceindex;
3263 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
3264 for (i = 0;i < surface->num_triangles;i++)
3266 triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
3267 // calculate bounds of triangle
3268 mins[0] = min(triangle->vertex[0][0], min(triangle->vertex[1][0], triangle->vertex[2][0]));
3269 mins[1] = min(triangle->vertex[0][1], min(triangle->vertex[1][1], triangle->vertex[2][1]));
3270 mins[2] = min(triangle->vertex[0][2], min(triangle->vertex[1][2], triangle->vertex[2][2]));
3271 maxs[0] = max(triangle->vertex[0][0], max(triangle->vertex[1][0], triangle->vertex[2][0]));
3272 maxs[1] = max(triangle->vertex[0][1], max(triangle->vertex[1][1], triangle->vertex[2][1]));
3273 maxs[2] = max(triangle->vertex[0][2], max(triangle->vertex[1][2], triangle->vertex[2][2]));
3274 // pick an axial projection based on the shortest dimension of the
3275 // axially aligned bounding box, this is almost equivalent to
3276 // calculating a triangle normal and classifying its primary axis.
3278 // one difference is that this method can pick a workable
3279 // projection axis even for a degenerate triangle whose only shape
3280 // is a line (where the chosen projection will always map the line
3281 // to non-zero coordinates in texture space)
3282 VectorSubtract(maxs, mins, aabbsize);
3284 if (aabbsize[1] < aabbsize[axis])
3286 if (aabbsize[2] < aabbsize[axis])
3288 triangle->axis = axis;
3293 static void Mod_GenerateLightmaps_CreateLightmaps(dp_model_t *model)
3295 msurface_t *surface;
3307 int column_numpoints;
3310 float column_plane[3];
3311 float trianglenormal[3];
3312 float clipbuf[5][8][3];
3313 float samplecenter[3];
3314 float samplenormal[3];
3316 float lmscalepixels;
3319 float lm_basescalepixels;
3320 int lm_borderpixels;
3324 lightmaptriangle_t *triangle;
3325 unsigned char *lightmappixels;
3326 unsigned char *deluxemappixels;
3327 mod_alloclightmap_state_t lmstate;
3329 // generate lightmap projection information for all triangles
3330 if (model->texturepool == NULL)
3331 model->texturepool = R_AllocTexturePool();
3332 lm_basescalepixels = 1.0f / max(0.0001f, mod_generatelightmaps_unitspersample.value);
3333 lm_borderpixels = mod_generatelightmaps_borderpixels.integer;
3334 lm_texturesize = bound(lm_borderpixels*2+1, 64, gl_max_texture_size);
3335 lm_maxpixels = lm_texturesize-(lm_borderpixels*2+1);
3336 Mod_AllocLightmap_Init(&lmstate, lm_texturesize, lm_texturesize);
3338 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3340 surface = model->data_surfaces + surfaceindex;
3341 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
3342 lmscalepixels = lm_basescalepixels;
3343 for (retry = 0;retry < 30;retry++)
3345 // after a couple failed attempts, degrade quality to make it fit
3347 lmscalepixels *= 0.5f;
3348 for (i = 0;i < surface->num_triangles;i++)
3350 triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
3351 triangle->lightmapindex = lightmapnumber;
3352 // calculate lightmap bounds in 3D pixel coordinates, limit size,
3353 // pick two planar axes for projection
3354 // lightmap coordinates here are in pixels
3355 // lightmap projections are snapped to pixel grid explicitly, such
3356 // that two neighboring triangles sharing an edge and projection
3357 // axis will have identical sampl espacing along their shared edge
3359 for (j = 0;j < 3;j++)
3361 if (j == triangle->axis)
3363 lmmins = floor(mins[j]*lmscalepixels)-lm_borderpixels;
3364 lmmaxs = floor(mins[j]*lmscalepixels)+lm_borderpixels;
3365 triangle->lmsize[k] = (int)(lmmaxs-lmmins);
3366 triangle->lmbase[k] = lmmins/lmscalepixels;
3367 triangle->lmscale[k] = lmscalepixels;
3370 if (!Mod_AllocLightmap_Block(&lmstate, triangle->lmsize[0], triangle->lmsize[1], &triangle->lmoffset[0], &triangle->lmoffset[1]))
3373 // if all fit in this texture, we're done with this surface
3374 if (i == surface->num_triangles)
3376 // if we haven't maxed out the lightmap size yet, we retry the
3377 // entire surface batch...
3378 if (lm_texturesize * 2 <= min(mod_generatelightmaps_texturesize.integer, gl_max_texture_size))
3380 lm_texturesize *= 2;
3383 Mod_AllocLightmap_Free(&lmstate);
3384 Mod_AllocLightmap_Init(&lmstate, lm_texturesize, lm_texturesize);
3387 // if we have maxed out the lightmap size, and this triangle does
3388 // not fit in the same texture as the rest of the surface, we have
3389 // to retry the entire surface in a new texture (can only use one)
3390 // with multiple retries, the lightmap quality degrades until it
3391 // fits (or gives up)
3392 if (surfaceindex > 0)
3394 Mod_AllocLightmap_Reset(&lmstate);
3398 Mod_AllocLightmap_Free(&lmstate);
3400 // now together lightmap textures
3401 model->brushq3.num_mergedlightmaps = lightmapnumber;
3402 model->brushq3.data_lightmaps = Mem_Alloc(model->mempool, model->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
3403 model->brushq3.data_deluxemaps = Mem_Alloc(model->mempool, model->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
3404 lightmappixels = Mem_Alloc(tempmempool, model->brushq3.num_mergedlightmaps * lm_texturesize * lm_texturesize * 4);
3405 deluxemappixels = Mem_Alloc(tempmempool, model->brushq3.num_mergedlightmaps * lm_texturesize * lm_texturesize * 4);
3406 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3408 surface = model->data_surfaces + surfaceindex;
3409 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
3410 for (i = 0;i < surface->num_triangles;i++)
3412 triangle = &mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle+i];
3413 VectorClear(row_plane);
3414 VectorClear(column_plane);
3415 row_plane[triangle->axis] = 1.0f;
3416 column_plane[!triangle->axis] = 1.0f;
3423 forward[1] = 1.0f / triangle->lmscale[0];
3427 left[2] = 1.0f / triangle->lmscale[1];
3432 origin[1] = triangle->lmbase[0];
3433 origin[2] = triangle->lmbase[1];
3436 forward[0] = 1.0f / triangle->lmscale[0];
3441 left[2] = 1.0f / triangle->lmscale[1];
3445 origin[0] = triangle->lmbase[0];
3447 origin[2] = triangle->lmbase[1];
3450 forward[0] = 1.0f / triangle->lmscale[0];
3454 left[1] = 1.0f / triangle->lmscale[1];
3459 origin[0] = triangle->lmbase[0];
3460 origin[1] = triangle->lmbase[1];
3464 Matrix4x4_FromVectors(&backmatrix, forward, left, up, origin);
3466 #define LM_DIST_EPSILON (1.0f / 32.0f)
3467 TriangleNormal(triangle->vertex[0], triangle->vertex[1], triangle->vertex[2], trianglenormal);
3468 VectorNormalize(trianglenormal);
3469 PolygonF_QuadForPlane(clipbuf[0][0], trianglenormal[0], trianglenormal[1], trianglenormal[2], DotProduct(trianglenormal, triangle->vertex[0]), model->radius * 2);
3470 VectorCopy(trianglenormal, samplenormal); // FIXME!
3471 for (y = 0;y < triangle->lmsize[1];y++)
3473 row_numpoints = PolygonF_Clip(4 , clipbuf[0][0], row_plane[0], row_plane[1], row_plane[2], triangle->lmbase[1] + y / triangle->lmscale[1] , LM_DIST_EPSILON, 8, clipbuf[1][0]);
3476 row_numpoints = PolygonF_Clip(row_numpoints, clipbuf[1][0], -row_plane[0], -row_plane[1], -row_plane[2], -(triangle->lmbase[1] + (y+1) / triangle->lmscale[1]), LM_DIST_EPSILON, 8, clipbuf[2][0]);
3479 pixeloffset = triangle->lightmapindex * lm_texturesize * lm_texturesize * 4 + (y+triangle->lmoffset[1]) * lm_texturesize * 4 + triangle->lmoffset[0] * 4;
3480 for (x = 0;x < triangle->lmsize[0];x++, pixeloffset += 4)
3482 column_numpoints = PolygonF_Clip(row_numpoints , clipbuf[2][0], column_plane[0], column_plane[1], column_plane[2], triangle->lmbase[0] + x / triangle->lmscale[0] , LM_DIST_EPSILON, 8, clipbuf[3][0]);
3483 if (!column_numpoints)
3485 column_numpoints = PolygonF_Clip(column_numpoints, clipbuf[3][0], -column_plane[0], -column_plane[1], -column_plane[2], -(triangle->lmbase[0] + (x+1) / triangle->lmscale[0]), LM_DIST_EPSILON, 8, clipbuf[4][0]);
3486 if (!column_numpoints)
3488 // we now have a polygon fragment in clipbuf[4], we can
3489 // sample its center or subdivide it further for
3491 VectorClear(samplecenter);
3492 for (j = 0;j < column_numpoints;j++)
3493 VectorAdd(samplecenter, clipbuf[4][j], samplecenter);
3494 f = 1.0f / column_numpoints;
3495 VectorScale(samplecenter, f, samplecenter);
3496 VectorMA(samplecenter, 0.125f, trianglenormal, samplecenter);
3497 Mod_GenerateLightmaps_LightmapSample(samplecenter, samplenormal, lightmappixels + pixeloffset, deluxemappixels + pixeloffset);
3503 for (lightmapindex = 0;lightmapindex < model->brushq3.num_mergedlightmaps;lightmapindex++)
3505 model->brushq3.data_lightmaps[lightmapindex] = R_LoadTexture2D(model->texturepool, va("lightmap%i", lightmapindex), lm_texturesize, lm_texturesize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_PRECACHE, NULL);
3506 model->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(model->texturepool, va("deluxemap%i", lightmapindex), lm_texturesize, lm_texturesize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_PRECACHE, NULL);
3510 Mem_Free(lightmappixels);
3511 if (deluxemappixels)
3512 Mem_Free(deluxemappixels);
3514 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3516 surface = model->data_surfaces + surfaceindex;
3517 e = model->surfmesh.data_element3i + surface->num_firsttriangle*3;
3518 if (!surface->num_triangles)
3520 lightmapindex = mod_generatelightmaps_lightmaptriangles[surface->num_firsttriangle].lightmapindex;
3521 surface->lightmaptexture = model->brushq3.data_lightmaps[lightmapindex];
3522 surface->deluxemaptexture = model->brushq3.data_deluxemaps[lightmapindex];
3526 static void Mod_GenerateLightmaps_UpdateVertexColors(dp_model_t *model)
3529 for (i = 0;i < model->surfmesh.num_vertices;i++)
3530 Mod_GenerateLightmaps_VertexSample(model->surfmesh.data_vertex3f + 3*i, model->surfmesh.data_normal3f + 3*i, model->surfmesh.data_lightmapcolor4f + 4*i);
3533 static void Mod_GenerateLightmaps_UpdateLightGrid(dp_model_t *model)
3540 for (z = 0;z < model->brushq3.num_lightgrid_isize[2];z++)
3542 pos[2] = (model->brushq3.num_lightgrid_imins[2] + z + 0.5f) * model->brushq3.num_lightgrid_cellsize[2];
3543 for (y = 0;y < model->brushq3.num_lightgrid_isize[1];y++)
3545 pos[1] = (model->brushq3.num_lightgrid_imins[1] + y + 0.5f) * model->brushq3.num_lightgrid_cellsize[1];
3546 for (x = 0;x < model->brushq3.num_lightgrid_isize[0];x++, index++)
3548 pos[0] = (model->brushq3.num_lightgrid_imins[0] + x + 0.5f) * model->brushq3.num_lightgrid_cellsize[0];
3549 Mod_GenerateLightmaps_GridSample(pos, model->brushq3.data_lightgrid + index);
3555 extern cvar_t mod_q3bsp_nolightmaps;
3556 static void Mod_GenerateLightmaps(dp_model_t *model)
3558 //lightmaptriangle_t *lightmaptriangles = Mem_Alloc(model->mempool, model->surfmesh.num_triangles * sizeof(lightmaptriangle_t));
3559 dp_model_t *oldloadmodel = loadmodel;
3562 Mod_GenerateLightmaps_DestroyLightmaps(model);
3563 Mod_GenerateLightmaps_UnweldTriangles(model);
3564 Mod_GenerateLightmaps_CreateTriangleInformation(model);
3565 Mod_GenerateLightmaps_ClassifyTriangles(model);
3566 if(!mod_q3bsp_nolightmaps.integer)
3567 Mod_GenerateLightmaps_CreateLightmaps(model);
3568 Mod_GenerateLightmaps_UpdateVertexColors(model);
3569 Mod_GenerateLightmaps_UpdateLightGrid(model);
3572 // first step is deleting the lightmaps
3573 for (surfaceindex = 0;surfaceindex < model->num_surfaces;surfaceindex++)
3575 surface = model->data_surfaces + surfaceindex;
3576 surface->lightmap = NULL;
3577 surface->deluxemap = NULL;
3578 // add a sample for each vertex of surface
3579 for (i = 0, vertexindex = surface->num_firstvertex;i < surface->num_vertices;i++, vertexindex++)
3580 Mod_GenerateLightmaps_AddSample(model->surfmesh.data_vertex3f + 3*vertexindex, model->surfmesh.data_normal3f + 3*vertexindex, model->surfmesh.data_lightmapcolor4f + 4*vertexindex, NULL, NULL);
3581 // generate lightmaptriangle_t for each triangle of surface
3582 for (i = 0, triangleindex = surface->num_firstvertex;i < surface->num_triangles;i++, triangleindex++)
3587 if (mod_generatelightmaps_lightmaptriangles)
3588 Mem_Free(mod_generatelightmaps_lightmaptriangles);
3589 mod_generatelightmaps_lightmaptriangles = NULL;
3591 loadmodel = oldloadmodel;
3594 static void Mod_GenerateLightmaps_f(void)
3596 if (Cmd_Argc() != 1)
3598 Con_Printf("usage: mod_generatelightmaps\n");
3603 Con_Printf("no worldmodel loaded\n");
3606 Mod_GenerateLightmaps(cl.worldmodel);