]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - model_brush.c
fix C++ compile error
[xonotic/darkplaces.git] / model_brush.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20
21 #include "quakedef.h"
22 #include "image.h"
23 #include "r_shadow.h"
24 #include "polygon.h"
25 #include "curves.h"
26 #include "wad.h"
27
28
29 //cvar_t r_subdivide_size = {CVAR_SAVE, "r_subdivide_size", "128", "how large water polygons should be (smaller values produce more polygons which give better warping effects)"};
30 cvar_t mod_bsp_portalize = {0, "mod_bsp_portalize", "1", "enables portal generation from BSP tree (may take several seconds per map), used by r_drawportals, r_useportalculling, r_shadow_realtime_world_compileportalculling, sv_cullentities_portal"};
31 cvar_t r_novis = {0, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
32 cvar_t r_nosurftextures = {0, "r_nosurftextures", "0", "pretends there was no texture lump found in the q1bsp/hlbsp loading (useful for debugging this rare case)"};
33 cvar_t r_subdivisions_tolerance = {0, "r_subdivisions_tolerance", "4", "maximum error tolerance on curve subdivision for rendering purposes (in other words, the curves will be given as many polygons as necessary to represent curves at this quality)"};
34 cvar_t r_subdivisions_mintess = {0, "r_subdivisions_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
35 cvar_t r_subdivisions_maxtess = {0, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
36 cvar_t r_subdivisions_maxvertices = {0, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
37 cvar_t r_subdivisions_collision_tolerance = {0, "r_subdivisions_collision_tolerance", "15", "maximum error tolerance on curve subdivision for collision purposes (usually a larger error tolerance than for rendering)"};
38 cvar_t r_subdivisions_collision_mintess = {0, "r_subdivisions_collision_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
39 cvar_t r_subdivisions_collision_maxtess = {0, "r_subdivisions_collision_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
40 cvar_t r_subdivisions_collision_maxvertices = {0, "r_subdivisions_collision_maxvertices", "4225", "maximum vertices allowed per subdivided curve"};
41 cvar_t r_trippy = {0, "r_trippy", "0", "easter egg"};
42 cvar_t mod_noshader_default_offsetmapping = {CVAR_SAVE, "mod_noshader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are not using q3 shader files"};
43 cvar_t mod_obj_orientation = {0, "mod_obj_orientation", "1", "fix orientation of OBJ models to the usual conventions (if zero, use coordinates as is)"};
44 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
45 cvar_t mod_q3bsp_curves_collisions_stride = {0, "mod_q3bsp_curves_collisions_stride", "16", "collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
46 cvar_t mod_q3bsp_curves_stride = {0, "mod_q3bsp_curves_stride", "16", "particle effect collisions against curves: optimize performance by doing a combined collision check for this triangle amount first (-1 avoids any box tests)"};
47 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
48 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
49 cvar_t mod_q3bsp_lightmapmergepower = {CVAR_SAVE, "mod_q3bsp_lightmapmergepower", "4", "merges the quake3 128x128 lightmap textures into larger lightmap group textures to speed up rendering, 1 = 256x256, 2 = 512x512, 3 = 1024x1024, 4 = 2048x2048, 5 = 4096x4096, ..."};
50 cvar_t mod_q3bsp_nolightmaps = {CVAR_SAVE, "mod_q3bsp_nolightmaps", "0", "do not load lightmaps in Q3BSP maps (to save video RAM, but be warned: it looks ugly)"};
51 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
52 cvar_t mod_q3bsp_sRGBlightmaps = {0, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
53 cvar_t mod_q3shader_default_offsetmapping = {CVAR_SAVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are using q3 shader files"};
54 cvar_t mod_q3shader_default_offsetmapping_scale = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
55 cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
56 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
57 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
58 cvar_t mod_q3shader_force_addalpha = {0, "mod_q3shader_force_addalpha", "0", "treat GL_ONE GL_ONE (or add) blendfunc as GL_SRC_ALPHA GL_ONE for compatibility with older DarkPlaces releases"};
59 cvar_t mod_q3shader_force_terrain_alphaflag = {0, "mod_q3shader_force_terrain_alphaflag", "0", "for multilayered terrain shaders force TEXF_ALPHA flag on both layers"};
60
61 cvar_t mod_q1bsp_polygoncollisions = {0, "mod_q1bsp_polygoncollisions", "0", "disables use of precomputed cliphulls and instead collides with polygons (uses Bounding Interval Hierarchy optimizations)"};
62 cvar_t mod_collision_bih = {0, "mod_collision_bih", "1", "enables use of generated Bounding Interval Hierarchy tree instead of compiled bsp tree in collision code"};
63 cvar_t mod_recalculatenodeboxes = {0, "mod_recalculatenodeboxes", "1", "enables use of generated node bounding boxes based on BSP tree portal reconstruction, rather than the node boxes supplied by the map compiler"};
64
65 static texture_t mod_q1bsp_texture_solid;
66 static texture_t mod_q1bsp_texture_sky;
67 static texture_t mod_q1bsp_texture_lava;
68 static texture_t mod_q1bsp_texture_slime;
69 static texture_t mod_q1bsp_texture_water;
70
71 void Mod_BrushInit(void)
72 {
73 //      Cvar_RegisterVariable(&r_subdivide_size);
74         Cvar_RegisterVariable(&mod_bsp_portalize);
75         Cvar_RegisterVariable(&r_novis);
76         Cvar_RegisterVariable(&r_nosurftextures);
77         Cvar_RegisterVariable(&r_subdivisions_tolerance);
78         Cvar_RegisterVariable(&r_subdivisions_mintess);
79         Cvar_RegisterVariable(&r_subdivisions_maxtess);
80         Cvar_RegisterVariable(&r_subdivisions_maxvertices);
81         Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
82         Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
83         Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
84         Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
85         Cvar_RegisterVariable(&r_trippy);
86         Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
87         Cvar_RegisterVariable(&mod_obj_orientation);
88         Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
89         Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
90         Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
91         Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
92         Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
93         Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
94         Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
95         Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
96         Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
97         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
98         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
99         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
100         Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
101         Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
102         Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
103         Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
104         Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
105         Cvar_RegisterVariable(&mod_collision_bih);
106         Cvar_RegisterVariable(&mod_recalculatenodeboxes);
107
108         // these games were made for older DP engines and are no longer
109         // maintained; use this hack to show their textures properly
110         if(gamemode == GAME_NEXUIZ)
111                 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
112
113         memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
114         strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
115         mod_q1bsp_texture_solid.surfaceflags = 0;
116         mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
117
118         mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
119         strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
120         mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
121         mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
122
123         mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
124         strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
125         mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
126         mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
127
128         mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
129         strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
130         mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
131         mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
132
133         mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
134         strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
135         mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
136         mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
137 }
138
139 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
140 {
141         mnode_t *node;
142
143         if (model == NULL)
144                 return NULL;
145
146         // LordHavoc: modified to start at first clip node,
147         // in other words: first node of the (sub)model
148         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
149         while (node->plane)
150                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
151
152         return (mleaf_t *)node;
153 }
154
155 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
156 {
157         int i;
158         mleaf_t *leaf;
159         leaf = Mod_Q1BSP_PointInLeaf(model, p);
160         if (leaf)
161         {
162                 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
163                 if (i)
164                 {
165                         memcpy(out, leaf->ambient_sound_level, i);
166                         out += i;
167                         outsize -= i;
168                 }
169         }
170         if (outsize)
171                 memset(out, 0, outsize);
172 }
173
174 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
175 {
176         int numclusters = 0;
177         int nodestackindex = 0;
178         mnode_t *node, *nodestack[1024];
179         if (!model->brush.num_pvsclusters)
180                 return -1;
181         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
182         for (;;)
183         {
184 #if 1
185                 if (node->plane)
186                 {
187                         // node - recurse down the BSP tree
188                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
189                         if (sides < 3)
190                         {
191                                 if (sides == 0)
192                                         return -1; // ERROR: NAN bounding box!
193                                 // box is on one side of plane, take that path
194                                 node = node->children[sides-1];
195                         }
196                         else
197                         {
198                                 // box crosses plane, take one path and remember the other
199                                 if (nodestackindex < 1024)
200                                         nodestack[nodestackindex++] = node->children[0];
201                                 node = node->children[1];
202                         }
203                         continue;
204                 }
205                 else
206                 {
207                         // leaf - add clusterindex to list
208                         if (numclusters < maxclusters)
209                                 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
210                         numclusters++;
211                 }
212 #else
213                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
214                 {
215                         if (node->plane)
216                         {
217                                 if (nodestackindex < 1024)
218                                         nodestack[nodestackindex++] = node->children[0];
219                                 node = node->children[1];
220                                 continue;
221                         }
222                         else
223                         {
224                                 // leaf - add clusterindex to list
225                                 if (numclusters < maxclusters)
226                                         clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
227                                 numclusters++;
228                         }
229                 }
230 #endif
231                 // try another path we didn't take earlier
232                 if (nodestackindex == 0)
233                         break;
234                 node = nodestack[--nodestackindex];
235         }
236         // return number of clusters found (even if more than the maxclusters)
237         return numclusters;
238 }
239
240 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
241 {
242         int nodestackindex = 0;
243         mnode_t *node, *nodestack[1024];
244         if (!model->brush.num_pvsclusters)
245                 return true;
246         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
247         for (;;)
248         {
249 #if 1
250                 if (node->plane)
251                 {
252                         // node - recurse down the BSP tree
253                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
254                         if (sides < 3)
255                         {
256                                 if (sides == 0)
257                                         return -1; // ERROR: NAN bounding box!
258                                 // box is on one side of plane, take that path
259                                 node = node->children[sides-1];
260                         }
261                         else
262                         {
263                                 // box crosses plane, take one path and remember the other
264                                 if (nodestackindex < 1024)
265                                         nodestack[nodestackindex++] = node->children[0];
266                                 node = node->children[1];
267                         }
268                         continue;
269                 }
270                 else
271                 {
272                         // leaf - check cluster bit
273                         int clusterindex = ((mleaf_t *)node)->clusterindex;
274                         if (CHECKPVSBIT(pvs, clusterindex))
275                         {
276                                 // it is visible, return immediately with the news
277                                 return true;
278                         }
279                 }
280 #else
281                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
282                 {
283                         if (node->plane)
284                         {
285                                 if (nodestackindex < 1024)
286                                         nodestack[nodestackindex++] = node->children[0];
287                                 node = node->children[1];
288                                 continue;
289                         }
290                         else
291                         {
292                                 // leaf - check cluster bit
293                                 int clusterindex = ((mleaf_t *)node)->clusterindex;
294                                 if (CHECKPVSBIT(pvs, clusterindex))
295                                 {
296                                         // it is visible, return immediately with the news
297                                         return true;
298                                 }
299                         }
300                 }
301 #endif
302                 // nothing to see here, try another path we didn't take earlier
303                 if (nodestackindex == 0)
304                         break;
305                 node = nodestack[--nodestackindex];
306         }
307         // it is not visible
308         return false;
309 }
310
311 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
312 {
313         int nodestackindex = 0;
314         mnode_t *node, *nodestack[1024];
315         if (!model->brush.num_leafs)
316                 return true;
317         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
318         for (;;)
319         {
320 #if 1
321                 if (node->plane)
322                 {
323                         // node - recurse down the BSP tree
324                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
325                         if (sides < 3)
326                         {
327                                 if (sides == 0)
328                                         return -1; // ERROR: NAN bounding box!
329                                 // box is on one side of plane, take that path
330                                 node = node->children[sides-1];
331                         }
332                         else
333                         {
334                                 // box crosses plane, take one path and remember the other
335                                 if (nodestackindex < 1024)
336                                         nodestack[nodestackindex++] = node->children[0];
337                                 node = node->children[1];
338                         }
339                         continue;
340                 }
341                 else
342                 {
343                         // leaf - check cluster bit
344                         int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
345                         if (CHECKPVSBIT(pvs, clusterindex))
346                         {
347                                 // it is visible, return immediately with the news
348                                 return true;
349                         }
350                 }
351 #else
352                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
353                 {
354                         if (node->plane)
355                         {
356                                 if (nodestackindex < 1024)
357                                         nodestack[nodestackindex++] = node->children[0];
358                                 node = node->children[1];
359                                 continue;
360                         }
361                         else
362                         {
363                                 // leaf - check cluster bit
364                                 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
365                                 if (CHECKPVSBIT(pvs, clusterindex))
366                                 {
367                                         // it is visible, return immediately with the news
368                                         return true;
369                                 }
370                         }
371                 }
372 #endif
373                 // nothing to see here, try another path we didn't take earlier
374                 if (nodestackindex == 0)
375                         break;
376                 node = nodestack[--nodestackindex];
377         }
378         // it is not visible
379         return false;
380 }
381
382 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
383 {
384         int nodestackindex = 0;
385         mnode_t *node, *nodestack[1024];
386         if (!model->brush.num_leafs)
387                 return true;
388         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
389         for (;;)
390         {
391 #if 1
392                 if (node->plane)
393                 {
394                         // node - recurse down the BSP tree
395                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
396                         if (sides < 3)
397                         {
398                                 if (sides == 0)
399                                         return -1; // ERROR: NAN bounding box!
400                                 // box is on one side of plane, take that path
401                                 node = node->children[sides-1];
402                         }
403                         else
404                         {
405                                 // box crosses plane, take one path and remember the other
406                                 if (nodestackindex < 1024)
407                                         nodestack[nodestackindex++] = node->children[0];
408                                 node = node->children[1];
409                         }
410                         continue;
411                 }
412                 else
413                 {
414                         // leaf - check if it is visible
415                         if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
416                         {
417                                 // it is visible, return immediately with the news
418                                 return true;
419                         }
420                 }
421 #else
422                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
423                 {
424                         if (node->plane)
425                         {
426                                 if (nodestackindex < 1024)
427                                         nodestack[nodestackindex++] = node->children[0];
428                                 node = node->children[1];
429                                 continue;
430                         }
431                         else
432                         {
433                                 // leaf - check if it is visible
434                                 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
435                                 {
436                                         // it is visible, return immediately with the news
437                                         return true;
438                                 }
439                         }
440                 }
441 #endif
442                 // nothing to see here, try another path we didn't take earlier
443                 if (nodestackindex == 0)
444                         break;
445                 node = nodestack[--nodestackindex];
446         }
447         // it is not visible
448         return false;
449 }
450
451 typedef struct findnonsolidlocationinfo_s
452 {
453         vec3_t center;
454         vec3_t absmin, absmax;
455         vec_t radius;
456         vec3_t nudge;
457         vec_t bestdist;
458         dp_model_t *model;
459 }
460 findnonsolidlocationinfo_t;
461
462 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
463 {
464         int i, *tri;
465         float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
466
467         tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
468         VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
469         VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
470         VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
471         VectorSubtract(vert[1], vert[0], edge[0]);
472         VectorSubtract(vert[2], vert[1], edge[1]);
473         CrossProduct(edge[1], edge[0], facenormal);
474         if (facenormal[0] || facenormal[1] || facenormal[2])
475         {
476                 VectorNormalize(facenormal);
477                 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
478                 if (f <= info->bestdist && f >= -info->bestdist)
479                 {
480                         VectorSubtract(vert[0], vert[2], edge[2]);
481                         VectorNormalize(edge[0]);
482                         VectorNormalize(edge[1]);
483                         VectorNormalize(edge[2]);
484                         CrossProduct(facenormal, edge[0], edgenormal[0]);
485                         CrossProduct(facenormal, edge[1], edgenormal[1]);
486                         CrossProduct(facenormal, edge[2], edgenormal[2]);
487                         // face distance
488                         if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
489                                         && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
490                                         && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
491                         {
492                                 // we got lucky, the center is within the face
493                                 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
494                                 if (dist < 0)
495                                 {
496                                         dist = -dist;
497                                         if (info->bestdist > dist)
498                                         {
499                                                 info->bestdist = dist;
500                                                 VectorScale(facenormal, (info->radius - -dist), info->nudge);
501                                         }
502                                 }
503                                 else
504                                 {
505                                         if (info->bestdist > dist)
506                                         {
507                                                 info->bestdist = dist;
508                                                 VectorScale(facenormal, (info->radius - dist), info->nudge);
509                                         }
510                                 }
511                         }
512                         else
513                         {
514                                 // check which edge or vertex the center is nearest
515                                 for (i = 0;i < 3;i++)
516                                 {
517                                         f = DotProduct(info->center, edge[i]);
518                                         if (f >= DotProduct(vert[0], edge[i])
519                                                         && f <= DotProduct(vert[1], edge[i]))
520                                         {
521                                                 // on edge
522                                                 VectorMA(info->center, -f, edge[i], point);
523                                                 dist = sqrt(DotProduct(point, point));
524                                                 if (info->bestdist > dist)
525                                                 {
526                                                         info->bestdist = dist;
527                                                         VectorScale(point, (info->radius / dist), info->nudge);
528                                                 }
529                                                 // skip both vertex checks
530                                                 // (both are further away than this edge)
531                                                 i++;
532                                         }
533                                         else
534                                         {
535                                                 // not on edge, check first vertex of edge
536                                                 VectorSubtract(info->center, vert[i], point);
537                                                 dist = sqrt(DotProduct(point, point));
538                                                 if (info->bestdist > dist)
539                                                 {
540                                                         info->bestdist = dist;
541                                                         VectorScale(point, (info->radius / dist), info->nudge);
542                                                 }
543                                         }
544                                 }
545                         }
546                 }
547         }
548 }
549
550 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
551 {
552         int surfacenum, k, *mark;
553         msurface_t *surface;
554         for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
555         {
556                 surface = info->model->data_surfaces + *mark;
557                 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
558                 {
559                         if(surface->deprecatedq3num_bboxstride > 0)
560                         {
561                                 int i, cnt, tri;
562                                 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
563                                 for(i = 0; i < cnt; ++i)
564                                 {
565                                         if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
566                                         {
567                                                 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
568                                                 {
569                                                         tri = i * surface->deprecatedq3num_bboxstride + k;
570                                                         if(tri >= surface->num_triangles)
571                                                                 break;
572                                                         Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
573                                                 }
574                                         }
575                                 }
576                         }
577                         else
578                         {
579                                 for (k = 0;k < surface->num_triangles;k++)
580                                 {
581                                         Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
582                                 }
583                         }
584                 }
585         }
586 }
587
588 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
589 {
590         if (node->plane)
591         {
592                 float f = PlaneDiff(info->center, node->plane);
593                 if (f >= -info->bestdist)
594                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
595                 if (f <= info->bestdist)
596                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
597         }
598         else
599         {
600                 if (((mleaf_t *)node)->numleafsurfaces)
601                         Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
602         }
603 }
604
605 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
606 {
607         int i;
608         findnonsolidlocationinfo_t info;
609         if (model == NULL)
610         {
611                 VectorCopy(in, out);
612                 return;
613         }
614         VectorCopy(in, info.center);
615         info.radius = radius;
616         info.model = model;
617         i = 0;
618         do
619         {
620                 VectorClear(info.nudge);
621                 info.bestdist = radius;
622                 VectorCopy(info.center, info.absmin);
623                 VectorCopy(info.center, info.absmax);
624                 info.absmin[0] -= info.radius + 1;
625                 info.absmin[1] -= info.radius + 1;
626                 info.absmin[2] -= info.radius + 1;
627                 info.absmax[0] += info.radius + 1;
628                 info.absmax[1] += info.radius + 1;
629                 info.absmax[2] += info.radius + 1;
630                 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
631                 VectorAdd(info.center, info.nudge, info.center);
632         }
633         while (info.bestdist < radius && ++i < 10);
634         VectorCopy(info.center, out);
635 }
636
637 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
638 {
639         switch(nativecontents)
640         {
641                 case CONTENTS_EMPTY:
642                         return 0;
643                 case CONTENTS_SOLID:
644                         return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
645                 case CONTENTS_WATER:
646                         return SUPERCONTENTS_WATER;
647                 case CONTENTS_SLIME:
648                         return SUPERCONTENTS_SLIME;
649                 case CONTENTS_LAVA:
650                         return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
651                 case CONTENTS_SKY:
652                         return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
653         }
654         return 0;
655 }
656
657 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
658 {
659         if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
660                 return CONTENTS_SOLID;
661         if (supercontents & SUPERCONTENTS_SKY)
662                 return CONTENTS_SKY;
663         if (supercontents & SUPERCONTENTS_LAVA)
664                 return CONTENTS_LAVA;
665         if (supercontents & SUPERCONTENTS_SLIME)
666                 return CONTENTS_SLIME;
667         if (supercontents & SUPERCONTENTS_WATER)
668                 return CONTENTS_WATER;
669         return CONTENTS_EMPTY;
670 }
671
672 typedef struct RecursiveHullCheckTraceInfo_s
673 {
674         // the hull we're tracing through
675         const hull_t *hull;
676
677         // the trace structure to fill in
678         trace_t *trace;
679
680         // start, end, and end - start (in model space)
681         double start[3];
682         double end[3];
683         double dist[3];
684 }
685 RecursiveHullCheckTraceInfo_t;
686
687 // 1/32 epsilon to keep floating point happy
688 #define DIST_EPSILON (0.03125)
689
690 #define HULLCHECKSTATE_EMPTY 0
691 #define HULLCHECKSTATE_SOLID 1
692 #define HULLCHECKSTATE_DONE 2
693
694 extern cvar_t collision_prefernudgedfraction;
695 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
696 {
697         // status variables, these don't need to be saved on the stack when
698         // recursing...  but are because this should be thread-safe
699         // (note: tracing against a bbox is not thread-safe, yet)
700         int ret;
701         mplane_t *plane;
702         double t1, t2;
703
704         // variables that need to be stored on the stack when recursing
705         mclipnode_t *node;
706         int side;
707         double midf, mid[3];
708
709         // LordHavoc: a goto!  everyone flee in terror... :)
710 loc0:
711         // check for empty
712         if (num < 0)
713         {
714                 num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
715                 if (!t->trace->startfound)
716                 {
717                         t->trace->startfound = true;
718                         t->trace->startsupercontents |= num;
719                 }
720                 if (num & SUPERCONTENTS_LIQUIDSMASK)
721                         t->trace->inwater = true;
722                 if (num == 0)
723                         t->trace->inopen = true;
724                 if (num & SUPERCONTENTS_SOLID)
725                         t->trace->hittexture = &mod_q1bsp_texture_solid;
726                 else if (num & SUPERCONTENTS_SKY)
727                         t->trace->hittexture = &mod_q1bsp_texture_sky;
728                 else if (num & SUPERCONTENTS_LAVA)
729                         t->trace->hittexture = &mod_q1bsp_texture_lava;
730                 else if (num & SUPERCONTENTS_SLIME)
731                         t->trace->hittexture = &mod_q1bsp_texture_slime;
732                 else
733                         t->trace->hittexture = &mod_q1bsp_texture_water;
734                 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
735                 t->trace->hitsupercontents = num;
736                 if (num & t->trace->hitsupercontentsmask)
737                 {
738                         // if the first leaf is solid, set startsolid
739                         if (t->trace->allsolid)
740                                 t->trace->startsolid = true;
741 #if COLLISIONPARANOID >= 3
742                         Con_Print("S");
743 #endif
744                         return HULLCHECKSTATE_SOLID;
745                 }
746                 else
747                 {
748                         t->trace->allsolid = false;
749 #if COLLISIONPARANOID >= 3
750                         Con_Print("E");
751 #endif
752                         return HULLCHECKSTATE_EMPTY;
753                 }
754         }
755
756         // find the point distances
757         node = t->hull->clipnodes + num;
758
759         plane = t->hull->planes + node->planenum;
760         if (plane->type < 3)
761         {
762                 t1 = p1[plane->type] - plane->dist;
763                 t2 = p2[plane->type] - plane->dist;
764         }
765         else
766         {
767                 t1 = DotProduct (plane->normal, p1) - plane->dist;
768                 t2 = DotProduct (plane->normal, p2) - plane->dist;
769         }
770
771         if (t1 < 0)
772         {
773                 if (t2 < 0)
774                 {
775 #if COLLISIONPARANOID >= 3
776                         Con_Print("<");
777 #endif
778                         num = node->children[1];
779                         goto loc0;
780                 }
781                 side = 1;
782         }
783         else
784         {
785                 if (t2 >= 0)
786                 {
787 #if COLLISIONPARANOID >= 3
788                         Con_Print(">");
789 #endif
790                         num = node->children[0];
791                         goto loc0;
792                 }
793                 side = 0;
794         }
795
796         // the line intersects, find intersection point
797         // LordHavoc: this uses the original trace for maximum accuracy
798 #if COLLISIONPARANOID >= 3
799         Con_Print("M");
800 #endif
801         if (plane->type < 3)
802         {
803                 t1 = t->start[plane->type] - plane->dist;
804                 t2 = t->end[plane->type] - plane->dist;
805         }
806         else
807         {
808                 t1 = DotProduct (plane->normal, t->start) - plane->dist;
809                 t2 = DotProduct (plane->normal, t->end) - plane->dist;
810         }
811
812         midf = t1 / (t1 - t2);
813         midf = bound(p1f, midf, p2f);
814         VectorMA(t->start, midf, t->dist, mid);
815
816         // recurse both sides, front side first
817         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side], p1f, midf, p1, mid);
818         // if this side is not empty, return what it is (solid or done)
819         if (ret != HULLCHECKSTATE_EMPTY)
820                 return ret;
821
822         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[side ^ 1], midf, p2f, mid, p2);
823         // if other side is not solid, return what it is (empty or done)
824         if (ret != HULLCHECKSTATE_SOLID)
825                 return ret;
826
827         // front is air and back is solid, this is the impact point...
828         if (side)
829         {
830                 t->trace->plane.dist = -plane->dist;
831                 VectorNegate (plane->normal, t->trace->plane.normal);
832         }
833         else
834         {
835                 t->trace->plane.dist = plane->dist;
836                 VectorCopy (plane->normal, t->trace->plane.normal);
837         }
838
839         // calculate the true fraction
840         t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
841         t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
842         midf = t1 / (t1 - t2);
843         t->trace->realfraction = bound(0, midf, 1);
844
845         // calculate the return fraction which is nudged off the surface a bit
846         midf = (t1 - DIST_EPSILON) / (t1 - t2);
847         t->trace->fraction = bound(0, midf, 1);
848
849         if (collision_prefernudgedfraction.integer)
850                 t->trace->realfraction = t->trace->fraction;
851
852 #if COLLISIONPARANOID >= 3
853         Con_Print("D");
854 #endif
855         return HULLCHECKSTATE_DONE;
856 }
857
858 //#if COLLISIONPARANOID < 2
859 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
860 {
861         mplane_t *plane;
862         mclipnode_t *nodes = t->hull->clipnodes;
863         mplane_t *planes = t->hull->planes;
864         vec3_t point;
865         VectorCopy(t->start, point);
866         while (num >= 0)
867         {
868                 plane = planes + nodes[num].planenum;
869                 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
870         }
871         num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
872         t->trace->startsupercontents |= num;
873         if (num & SUPERCONTENTS_LIQUIDSMASK)
874                 t->trace->inwater = true;
875         if (num == 0)
876                 t->trace->inopen = true;
877         if (num & t->trace->hitsupercontentsmask)
878         {
879                 t->trace->allsolid = t->trace->startsolid = true;
880                 return HULLCHECKSTATE_SOLID;
881         }
882         else
883         {
884                 t->trace->allsolid = t->trace->startsolid = false;
885                 return HULLCHECKSTATE_EMPTY;
886         }
887 }
888 //#endif
889
890 static void Mod_Q1BSP_TracePoint(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask)
891 {
892         RecursiveHullCheckTraceInfo_t rhc;
893
894         memset(&rhc, 0, sizeof(rhc));
895         memset(trace, 0, sizeof(trace_t));
896         rhc.trace = trace;
897         rhc.trace->fraction = 1;
898         rhc.trace->realfraction = 1;
899         rhc.trace->allsolid = true;
900         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
901         VectorCopy(start, rhc.start);
902         VectorCopy(start, rhc.end);
903         Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
904 }
905
906 static void Mod_Q1BSP_TraceLineAgainstSurfaces(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask);
907
908 static void Mod_Q1BSP_TraceLine(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
909 {
910         RecursiveHullCheckTraceInfo_t rhc;
911
912         if (VectorCompare(start, end))
913         {
914                 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
915                 return;
916         }
917
918         // sometimes we want to traceline against polygons so we can report the texture that was hit rather than merely a contents, but using this method breaks one of negke's maps so it must be a cvar check...
919         if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
920         {
921                 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
922                 return;
923         }
924
925         memset(&rhc, 0, sizeof(rhc));
926         memset(trace, 0, sizeof(trace_t));
927         rhc.trace = trace;
928         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
929         rhc.trace->fraction = 1;
930         rhc.trace->realfraction = 1;
931         rhc.trace->allsolid = true;
932         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
933         VectorCopy(start, rhc.start);
934         VectorCopy(end, rhc.end);
935         VectorSubtract(rhc.end, rhc.start, rhc.dist);
936 #if COLLISIONPARANOID >= 2
937         Con_Printf("t(%f %f %f,%f %f %f)", rhc.start[0], rhc.start[1], rhc.start[2], rhc.end[0], rhc.end[1], rhc.end[2]);
938         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
939         {
940
941                 double test[3];
942                 trace_t testtrace;
943                 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
944                 memset(&testtrace, 0, sizeof(trace_t));
945                 rhc.trace = &testtrace;
946                 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
947                 rhc.trace->fraction = 1;
948                 rhc.trace->realfraction = 1;
949                 rhc.trace->allsolid = true;
950                 VectorCopy(test, rhc.start);
951                 VectorCopy(test, rhc.end);
952                 VectorClear(rhc.dist);
953                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
954                 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
955                 if (!trace->startsolid && testtrace.startsolid)
956                         Con_Printf(" - ended in solid!\n");
957         }
958         Con_Print("\n");
959 #else
960         if (VectorLength2(rhc.dist))
961                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
962         else
963                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
964 #endif
965 }
966
967 static void Mod_Q1BSP_TraceBox(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask)
968 {
969         // this function currently only supports same size start and end
970         double boxsize[3];
971         RecursiveHullCheckTraceInfo_t rhc;
972
973         if (VectorCompare(boxmins, boxmaxs))
974         {
975                 if (VectorCompare(start, end))
976                         Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
977                 else
978                         Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
979                 return;
980         }
981
982         memset(&rhc, 0, sizeof(rhc));
983         memset(trace, 0, sizeof(trace_t));
984         rhc.trace = trace;
985         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
986         rhc.trace->fraction = 1;
987         rhc.trace->realfraction = 1;
988         rhc.trace->allsolid = true;
989         VectorSubtract(boxmaxs, boxmins, boxsize);
990         if (boxsize[0] < 3)
991                 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
992         else if (model->brush.ishlbsp)
993         {
994                 // LordHavoc: this has to have a minor tolerance (the .1) because of
995                 // minor float precision errors from the box being transformed around
996                 if (boxsize[0] < 32.1)
997                 {
998                         if (boxsize[2] < 54) // pick the nearest of 36 or 72
999                                 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
1000                         else
1001                                 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
1002                 }
1003                 else
1004                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
1005         }
1006         else
1007         {
1008                 // LordHavoc: this has to have a minor tolerance (the .1) because of
1009                 // minor float precision errors from the box being transformed around
1010                 if (boxsize[0] < 32.1)
1011                         rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1012                 else
1013                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1014         }
1015         VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1016         VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1017         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1018 #if COLLISIONPARANOID >= 2
1019         Con_Printf("t(%f %f %f,%f %f %f,%i %f %f %f)", rhc.start[0], rhc.start[1], rhc.start[2], rhc.end[0], rhc.end[1], rhc.end[2], rhc.hull - model->brushq1.hulls, rhc.hull->clip_mins[0], rhc.hull->clip_mins[1], rhc.hull->clip_mins[2]);
1020         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1021         {
1022
1023                 double test[3];
1024                 trace_t testtrace;
1025                 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1026                 memset(&testtrace, 0, sizeof(trace_t));
1027                 rhc.trace = &testtrace;
1028                 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1029                 rhc.trace->fraction = 1;
1030                 rhc.trace->realfraction = 1;
1031                 rhc.trace->allsolid = true;
1032                 VectorCopy(test, rhc.start);
1033                 VectorCopy(test, rhc.end);
1034                 VectorClear(rhc.dist);
1035                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1036                 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1037                 if (!trace->startsolid && testtrace.startsolid)
1038                         Con_Printf(" - ended in solid!\n");
1039         }
1040         Con_Print("\n");
1041 #else
1042         if (VectorLength2(rhc.dist))
1043                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1044         else
1045                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1046 #endif
1047 }
1048
1049 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1050 {
1051         int num = model->brushq1.hulls[0].firstclipnode;
1052         mplane_t *plane;
1053         mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1054         mplane_t *planes = model->brushq1.hulls[0].planes;
1055         while (num >= 0)
1056         {
1057                 plane = planes + nodes[num].planenum;
1058                 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1059         }
1060         return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1061 }
1062
1063 void Collision_ClipTrace_Box(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, const vec3_t mins, const vec3_t maxs, const vec3_t end, int hitsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1064 {
1065 #if 1
1066         colbrushf_t cbox;
1067         colplanef_t cbox_planes[6];
1068         cbox.isaabb = true;
1069         cbox.hasaabbplanes = true;
1070         cbox.supercontents = boxsupercontents;
1071         cbox.numplanes = 6;
1072         cbox.numpoints = 0;
1073         cbox.numtriangles = 0;
1074         cbox.planes = cbox_planes;
1075         cbox.points = NULL;
1076         cbox.elements = NULL;
1077         cbox.markframe = 0;
1078         cbox.mins[0] = 0;
1079         cbox.mins[1] = 0;
1080         cbox.mins[2] = 0;
1081         cbox.maxs[0] = 0;
1082         cbox.maxs[1] = 0;
1083         cbox.maxs[2] = 0;
1084         cbox_planes[0].normal[0] =  1;cbox_planes[0].normal[1] =  0;cbox_planes[0].normal[2] =  0;cbox_planes[0].dist = cmaxs[0] - mins[0];
1085         cbox_planes[1].normal[0] = -1;cbox_planes[1].normal[1] =  0;cbox_planes[1].normal[2] =  0;cbox_planes[1].dist = maxs[0] - cmins[0];
1086         cbox_planes[2].normal[0] =  0;cbox_planes[2].normal[1] =  1;cbox_planes[2].normal[2] =  0;cbox_planes[2].dist = cmaxs[1] - mins[1];
1087         cbox_planes[3].normal[0] =  0;cbox_planes[3].normal[1] = -1;cbox_planes[3].normal[2] =  0;cbox_planes[3].dist = maxs[1] - cmins[1];
1088         cbox_planes[4].normal[0] =  0;cbox_planes[4].normal[1] =  0;cbox_planes[4].normal[2] =  1;cbox_planes[4].dist = cmaxs[2] - mins[2];
1089         cbox_planes[5].normal[0] =  0;cbox_planes[5].normal[1] =  0;cbox_planes[5].normal[2] = -1;cbox_planes[5].dist = maxs[2] - cmins[2];
1090         cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1091         cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1092         cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1093         cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1094         cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1095         cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1096         memset(trace, 0, sizeof(trace_t));
1097         trace->hitsupercontentsmask = hitsupercontentsmask;
1098         trace->fraction = 1;
1099         trace->realfraction = 1;
1100         Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1101 #else
1102         RecursiveHullCheckTraceInfo_t rhc;
1103         static hull_t box_hull;
1104         static mclipnode_t box_clipnodes[6];
1105         static mplane_t box_planes[6];
1106         // fill in a default trace
1107         memset(&rhc, 0, sizeof(rhc));
1108         memset(trace, 0, sizeof(trace_t));
1109         //To keep everything totally uniform, bounding boxes are turned into small
1110         //BSP trees instead of being compared directly.
1111         // create a temp hull from bounding box sizes
1112         box_planes[0].dist = cmaxs[0] - mins[0];
1113         box_planes[1].dist = cmins[0] - maxs[0];
1114         box_planes[2].dist = cmaxs[1] - mins[1];
1115         box_planes[3].dist = cmins[1] - maxs[1];
1116         box_planes[4].dist = cmaxs[2] - mins[2];
1117         box_planes[5].dist = cmins[2] - maxs[2];
1118 #if COLLISIONPARANOID >= 3
1119         Con_Printf("box_planes %f:%f %f:%f %f:%f\ncbox %f %f %f:%f %f %f\nbox %f %f %f:%f %f %f\n", box_planes[0].dist, box_planes[1].dist, box_planes[2].dist, box_planes[3].dist, box_planes[4].dist, box_planes[5].dist, cmins[0], cmins[1], cmins[2], cmaxs[0], cmaxs[1], cmaxs[2], mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]);
1120 #endif
1121
1122         if (box_hull.clipnodes == NULL)
1123         {
1124                 int i, side;
1125
1126                 //Set up the planes and clipnodes so that the six floats of a bounding box
1127                 //can just be stored out and get a proper hull_t structure.
1128
1129                 box_hull.clipnodes = box_clipnodes;
1130                 box_hull.planes = box_planes;
1131                 box_hull.firstclipnode = 0;
1132                 box_hull.lastclipnode = 5;
1133
1134                 for (i = 0;i < 6;i++)
1135                 {
1136                         box_clipnodes[i].planenum = i;
1137
1138                         side = i&1;
1139
1140                         box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1141                         if (i != 5)
1142                                 box_clipnodes[i].children[side^1] = i + 1;
1143                         else
1144                                 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1145
1146                         box_planes[i].type = i>>1;
1147                         box_planes[i].normal[i>>1] = 1;
1148                 }
1149         }
1150
1151         // trace a line through the generated clipping hull
1152         //rhc.boxsupercontents = boxsupercontents;
1153         rhc.hull = &box_hull;
1154         rhc.trace = trace;
1155         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1156         rhc.trace->fraction = 1;
1157         rhc.trace->realfraction = 1;
1158         rhc.trace->allsolid = true;
1159         VectorCopy(start, rhc.start);
1160         VectorCopy(end, rhc.end);
1161         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1162         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1163         //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1164         if (rhc.trace->startsupercontents)
1165                 rhc.trace->startsupercontents = boxsupercontents;
1166 #endif
1167 }
1168
1169 void Collision_ClipTrace_Point(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, int hitsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1170 {
1171         memset(trace, 0, sizeof(trace_t));
1172         trace->fraction = 1;
1173         trace->realfraction = 1;
1174         if (BoxesOverlap(start, start, cmins, cmaxs))
1175         {
1176                 trace->startsupercontents |= boxsupercontents;
1177                 if (hitsupercontentsmask & boxsupercontents)
1178                 {
1179                         trace->startsolid = true;
1180                         trace->allsolid = true;
1181                 }
1182         }
1183 }
1184
1185 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1186 {
1187         trace_t trace;
1188         Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
1189         return trace.fraction == 1;
1190 }
1191
1192 static int Mod_Q1BSP_LightPoint_RecursiveBSPNode(dp_model_t *model, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const mnode_t *node, float x, float y, float startz, float endz)
1193 {
1194         int side;
1195         float front, back;
1196         float mid, distz = endz - startz;
1197
1198 loc0:
1199         if (!node->plane)
1200                 return false;           // didn't hit anything
1201
1202         switch (node->plane->type)
1203         {
1204         case PLANE_X:
1205                 node = node->children[x < node->plane->dist];
1206                 goto loc0;
1207         case PLANE_Y:
1208                 node = node->children[y < node->plane->dist];
1209                 goto loc0;
1210         case PLANE_Z:
1211                 side = startz < node->plane->dist;
1212                 if ((endz < node->plane->dist) == side)
1213                 {
1214                         node = node->children[side];
1215                         goto loc0;
1216                 }
1217                 // found an intersection
1218                 mid = node->plane->dist;
1219                 break;
1220         default:
1221                 back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1222                 front += startz * node->plane->normal[2];
1223                 back += endz * node->plane->normal[2];
1224                 side = front < node->plane->dist;
1225                 if ((back < node->plane->dist) == side)
1226                 {
1227                         node = node->children[side];
1228                         goto loc0;
1229                 }
1230                 // found an intersection
1231                 mid = startz + distz * (front - node->plane->dist) / (front - back);
1232                 break;
1233         }
1234
1235         // go down front side
1236         if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1237                 return true;    // hit something
1238         else
1239         {
1240                 // check for impact on this node
1241                 if (node->numsurfaces)
1242                 {
1243                         unsigned int i;
1244                         int dsi, dti, lmwidth, lmheight;
1245                         float ds, dt;
1246                         msurface_t *surface;
1247                         unsigned char *lightmap;
1248                         int maps, line3, size3;
1249                         float dsfrac;
1250                         float dtfrac;
1251                         float scale, w, w00, w01, w10, w11;
1252
1253                         surface = model->data_surfaces + node->firstsurface;
1254                         for (i = 0;i < node->numsurfaces;i++, surface++)
1255                         {
1256                                 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1257                                         continue;       // no lightmaps
1258
1259                                 // location we want to sample in the lightmap
1260                                 ds = ((x * surface->lightmapinfo->texinfo->vecs[0][0] + y * surface->lightmapinfo->texinfo->vecs[0][1] + mid * surface->lightmapinfo->texinfo->vecs[0][2] + surface->lightmapinfo->texinfo->vecs[0][3]) - surface->lightmapinfo->texturemins[0]) * 0.0625f;
1261                                 dt = ((x * surface->lightmapinfo->texinfo->vecs[1][0] + y * surface->lightmapinfo->texinfo->vecs[1][1] + mid * surface->lightmapinfo->texinfo->vecs[1][2] + surface->lightmapinfo->texinfo->vecs[1][3]) - surface->lightmapinfo->texturemins[1]) * 0.0625f;
1262
1263                                 // check the bounds
1264                                 dsi = (int)ds;
1265                                 dti = (int)dt;
1266                                 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1267                                 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1268
1269                                 // is it in bounds?
1270                                 if (dsi >= 0 && dsi < lmwidth-1 && dti >= 0 && dti < lmheight-1)
1271                                 {
1272                                         // calculate bilinear interpolation factors
1273                                         // and also multiply by fixedpoint conversion factors
1274                                         dsfrac = ds - dsi;
1275                                         dtfrac = dt - dti;
1276                                         w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1277                                         w01 = (    dsfrac) * (1 - dtfrac) * (1.0f / 32768.0f);
1278                                         w10 = (1 - dsfrac) * (    dtfrac) * (1.0f / 32768.0f);
1279                                         w11 = (    dsfrac) * (    dtfrac) * (1.0f / 32768.0f);
1280
1281                                         // values for pointer math
1282                                         line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1283                                         size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1284
1285                                         // look up the pixel
1286                                         lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1287
1288                                         // bilinear filter each lightmap style, and sum them
1289                                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1290                                         {
1291                                                 scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]];
1292                                                 w = w00 * scale;VectorMA(ambientcolor, w, lightmap            , ambientcolor);
1293                                                 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3        , ambientcolor);
1294                                                 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3    , ambientcolor);
1295                                                 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1296                                                 lightmap += size3;
1297                                         }
1298
1299                                         return true; // success
1300                                 }
1301                         }
1302                 }
1303
1304                 // go down back side
1305                 node = node->children[side ^ 1];
1306                 startz = mid;
1307                 distz = endz - startz;
1308                 goto loc0;
1309         }
1310 }
1311
1312 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1313 {
1314         // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1315         VectorSet(diffusenormal, 0, 0, 1);
1316
1317         if (!model->brushq1.lightdata)
1318         {
1319                 VectorSet(ambientcolor, 1, 1, 1);
1320                 VectorSet(diffusecolor, 0, 0, 0);
1321                 return;
1322         }
1323
1324         Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, p[0], p[1], p[2] + 0.125, p[2] - 65536);
1325 }
1326
1327 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1328 {
1329         unsigned int i;
1330         int j;
1331         int k;
1332         const msurface_t *surface;
1333         float normal[3];
1334         float v0[3];
1335         float v1[3];
1336         float edgedir[3];
1337         float edgenormal[3];
1338         float p[4];
1339         float midf;
1340         float t1;
1341         float t2;
1342         VectorCopy(mid, p);
1343         p[3] = 1;
1344         surface = model->data_surfaces + node->firstsurface;
1345         for (i = 0;i < node->numsurfaces;i++, surface++)
1346         {
1347                 // skip surfaces whose bounding box does not include the point
1348 //              if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1349 //                      continue;
1350                 // skip faces with contents we don't care about
1351                 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1352                         continue;
1353                 // get the surface normal - since it is flat we know any vertex normal will suffice
1354                 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1355                 // skip backfaces
1356                 if (DotProduct(t->dist, normal) > 0)
1357                         continue;
1358                 // iterate edges and see if the point is outside one of them
1359                 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1360                 {
1361                         VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1362                         VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1363                         VectorSubtract(v0, v1, edgedir);
1364                         CrossProduct(edgedir, normal, edgenormal);
1365                         if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1366                                 break;
1367                 }
1368                 // if the point is outside one of the edges, it is not within the surface
1369                 if (j < surface->num_vertices)
1370                         continue;
1371
1372                 // we hit a surface, this is the impact point...
1373                 VectorCopy(normal, t->trace->plane.normal);
1374                 t->trace->plane.dist = DotProduct(normal, p);
1375
1376                 // calculate the true fraction
1377                 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1378                 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1379                 midf = t1 / (t1 - t2);
1380                 t->trace->realfraction = midf;
1381
1382                 // calculate the return fraction which is nudged off the surface a bit
1383                 midf = (t1 - DIST_EPSILON) / (t1 - t2);
1384                 t->trace->fraction = bound(0, midf, 1);
1385
1386                 if (collision_prefernudgedfraction.integer)
1387                         t->trace->realfraction = t->trace->fraction;
1388
1389                 t->trace->hittexture = surface->texture->currentframe;
1390                 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1391                 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1392                 return surface->texture->currentframe;
1393         }
1394         return NULL;
1395 }
1396
1397 static int Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, const double p1[3], const double p2[3])
1398 {
1399         const mplane_t *plane;
1400         double t1, t2;
1401         int side;
1402         double midf, mid[3];
1403         const mleaf_t *leaf;
1404
1405         while (node->plane)
1406         {
1407                 plane = node->plane;
1408                 if (plane->type < 3)
1409                 {
1410                         t1 = p1[plane->type] - plane->dist;
1411                         t2 = p2[plane->type] - plane->dist;
1412                 }
1413                 else
1414                 {
1415                         t1 = DotProduct (plane->normal, p1) - plane->dist;
1416                         t2 = DotProduct (plane->normal, p2) - plane->dist;
1417                 }
1418                 if (t1 < 0)
1419                 {
1420                         if (t2 < 0)
1421                         {
1422                                 node = node->children[1];
1423                                 continue;
1424                         }
1425                         side = 1;
1426                 }
1427                 else
1428                 {
1429                         if (t2 >= 0)
1430                         {
1431                                 node = node->children[0];
1432                                 continue;
1433                         }
1434                         side = 0;
1435                 }
1436
1437                 // the line intersects, find intersection point
1438                 // LordHavoc: this uses the original trace for maximum accuracy
1439                 if (plane->type < 3)
1440                 {
1441                         t1 = t->start[plane->type] - plane->dist;
1442                         t2 = t->end[plane->type] - plane->dist;
1443                 }
1444                 else
1445                 {
1446                         t1 = DotProduct (plane->normal, t->start) - plane->dist;
1447                         t2 = DotProduct (plane->normal, t->end) - plane->dist;
1448                 }
1449         
1450                 midf = t1 / (t1 - t2);
1451                 VectorMA(t->start, midf, t->dist, mid);
1452
1453                 // recurse both sides, front side first, return if we hit a surface
1454                 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1455                         return HULLCHECKSTATE_DONE;
1456
1457                 // test each surface on the node
1458                 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1459                 if (t->trace->hittexture)
1460                         return HULLCHECKSTATE_DONE;
1461
1462                 // recurse back side
1463                 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1464         }
1465         leaf = (const mleaf_t *)node;
1466         side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1467         if (!t->trace->startfound)
1468         {
1469                 t->trace->startfound = true;
1470                 t->trace->startsupercontents |= side;
1471         }
1472         if (side & SUPERCONTENTS_LIQUIDSMASK)
1473                 t->trace->inwater = true;
1474         if (side == 0)
1475                 t->trace->inopen = true;
1476         if (side & t->trace->hitsupercontentsmask)
1477         {
1478                 // if the first leaf is solid, set startsolid
1479                 if (t->trace->allsolid)
1480                         t->trace->startsolid = true;
1481                 return HULLCHECKSTATE_SOLID;
1482         }
1483         else
1484         {
1485                 t->trace->allsolid = false;
1486                 return HULLCHECKSTATE_EMPTY;
1487         }
1488 }
1489
1490 static void Mod_Q1BSP_TraceLineAgainstSurfaces(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
1491 {
1492         RecursiveHullCheckTraceInfo_t rhc;
1493
1494         memset(&rhc, 0, sizeof(rhc));
1495         memset(trace, 0, sizeof(trace_t));
1496         rhc.trace = trace;
1497         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1498         rhc.trace->fraction = 1;
1499         rhc.trace->realfraction = 1;
1500         rhc.trace->allsolid = true;
1501         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1502         VectorCopy(start, rhc.start);
1503         VectorCopy(end, rhc.end);
1504         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1505         Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1506         VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1507 }
1508
1509 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1510 {
1511         int c;
1512         unsigned char *outstart = out;
1513         while (out < outend)
1514         {
1515                 if (in == inend)
1516                 {
1517                         Con_Printf("Mod_Q1BSP_DecompressVis: input underrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
1518                         return;
1519                 }
1520                 c = *in++;
1521                 if (c)
1522                         *out++ = c;
1523                 else
1524                 {
1525                         if (in == inend)
1526                         {
1527                                 Con_Printf("Mod_Q1BSP_DecompressVis: input underrun (during zero-run) on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
1528                                 return;
1529                         }
1530                         for (c = *in++;c > 0;c--)
1531                         {
1532                                 if (out == outend)
1533                                 {
1534                                         Con_Printf("Mod_Q1BSP_DecompressVis: output overrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
1535                                         return;
1536                                 }
1537                                 *out++ = 0;
1538                         }
1539                 }
1540         }
1541 }
1542
1543 /*
1544 =============
1545 R_Q1BSP_LoadSplitSky
1546
1547 A sky texture is 256*128, with the right side being a masked overlay
1548 ==============
1549 */
1550 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1551 {
1552         int x, y;
1553         int w = width/2;
1554         int h = height;
1555         unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1556         unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1557
1558         // allocate a texture pool if we need it
1559         if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1560                 loadmodel->texturepool = R_AllocTexturePool();
1561
1562         if (bytesperpixel == 4)
1563         {
1564                 for (y = 0;y < h;y++)
1565                 {
1566                         for (x = 0;x < w;x++)
1567                         {
1568                                 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1569                                 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1570                         }
1571                 }
1572         }
1573         else
1574         {
1575                 // make an average value for the back to avoid
1576                 // a fringe on the top level
1577                 int p, r, g, b;
1578                 union
1579                 {
1580                         unsigned int i;
1581                         unsigned char b[4];
1582                 }
1583                 bgra;
1584                 r = g = b = 0;
1585                 for (y = 0;y < h;y++)
1586                 {
1587                         for (x = 0;x < w;x++)
1588                         {
1589                                 p = src[x*width+y+w];
1590                                 r += palette_rgb[p][0];
1591                                 g += palette_rgb[p][1];
1592                                 b += palette_rgb[p][2];
1593                         }
1594                 }
1595                 bgra.b[2] = r/(w*h);
1596                 bgra.b[1] = g/(w*h);
1597                 bgra.b[0] = b/(w*h);
1598                 bgra.b[3] = 0;
1599                 for (y = 0;y < h;y++)
1600                 {
1601                         for (x = 0;x < w;x++)
1602                         {
1603                                 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1604                                 p = src[y*width+x];
1605                                 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1606                         }
1607                 }
1608         }
1609
1610         loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0         , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1611         loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1612         Mem_Free(solidpixels);
1613         Mem_Free(alphapixels);
1614 }
1615
1616 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1617 {
1618         int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0;
1619         skinframe_t *skinframe;
1620         texture_t *tx, *tx2, *anims[10], *altanims[10];
1621         texture_t backuptex;
1622         unsigned char *data, *mtdata;
1623         const char *s;
1624         char mapname[MAX_QPATH], name[MAX_QPATH];
1625         unsigned char zeroopaque[4], zerotrans[4];
1626         sizebuf_t miptexsb;
1627         char vabuf[1024];
1628         Vector4Set(zeroopaque, 0, 0, 0, 255);
1629         Vector4Set(zerotrans, 0, 0, 0, 128);
1630
1631         loadmodel->data_textures = NULL;
1632
1633         // add two slots for notexture walls and notexture liquids
1634         if (sb->cursize)
1635         {
1636                 nummiptex = MSG_ReadLittleLong(sb);
1637                 loadmodel->num_textures = nummiptex + 2;
1638                 loadmodel->num_texturesperskin = loadmodel->num_textures;
1639         }
1640         else
1641         {
1642                 loadmodel->num_textures = 2;
1643                 loadmodel->num_texturesperskin = loadmodel->num_textures;
1644         }
1645
1646         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1647
1648         // fill out all slots with notexture
1649         if (cls.state != ca_dedicated)
1650                 skinframe = R_SkinFrame_LoadMissing();
1651         else
1652                 skinframe = NULL;
1653         for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1654         {
1655                 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1656                 tx->width = 16;
1657                 tx->height = 16;
1658                 if (cls.state != ca_dedicated)
1659                 {
1660                         tx->numskinframes = 1;
1661                         tx->skinframerate = 1;
1662                         tx->skinframes[0] = skinframe;
1663                         tx->currentskinframe = tx->skinframes[0];
1664                 }
1665                 tx->basematerialflags = MATERIALFLAG_WALL;
1666                 if (i == loadmodel->num_textures - 1)
1667                 {
1668                         tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1669                         tx->supercontents = mod_q1bsp_texture_water.supercontents;
1670                         tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1671                 }
1672                 else
1673                 {
1674                         tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1675                         tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1676                 }
1677                 tx->currentframe = tx;
1678
1679                 // clear water settings
1680                 tx->reflectmin = 0;
1681                 tx->reflectmax = 1;
1682                 tx->refractfactor = 1;
1683                 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1684                 tx->reflectfactor = 1;
1685                 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1686                 tx->r_water_wateralpha = 1;
1687                 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1688                 tx->offsetscale = 1;
1689                 tx->offsetbias = 0;
1690                 tx->specularscalemod = 1;
1691                 tx->specularpowermod = 1;
1692                 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1693                 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1694                 // JUST GREP FOR "specularscalemod = 1".
1695         }
1696
1697         if (!sb->cursize)
1698         {
1699                 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1700                 return;
1701         }
1702
1703         s = loadmodel->name;
1704         if (!strncasecmp(s, "maps/", 5))
1705                 s += 5;
1706         FS_StripExtension(s, mapname, sizeof(mapname));
1707
1708         // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1709         // LordHavoc: mostly rewritten map texture loader
1710         for (i = 0;i < nummiptex;i++)
1711         {
1712                 doffset = MSG_ReadLittleLong(sb);
1713                 if (r_nosurftextures.integer)
1714                         continue;
1715                 if (doffset == -1)
1716                 {
1717                         Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1718                         continue;
1719                 }
1720
1721                 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1722
1723                 // copy name, but only up to 16 characters
1724                 // (the output buffer can hold more than this, but the input buffer is
1725                 //  only 16)
1726                 for (j = 0;j < 16;j++)
1727                         name[j] = MSG_ReadByte(&miptexsb);
1728                 name[j] = 0;
1729                 // pretty up the buffer (replacing any trailing garbage with 0)
1730                 for (j = strlen(name);j < 16;j++)
1731                         name[j] = 0;
1732
1733                 if (!name[0])
1734                 {
1735                         dpsnprintf(name, sizeof(name), "unnamed%i", i);
1736                         Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1737                 }
1738
1739                 mtwidth = MSG_ReadLittleLong(&miptexsb);
1740                 mtheight = MSG_ReadLittleLong(&miptexsb);
1741                 mtdata = NULL;
1742                 j = MSG_ReadLittleLong(&miptexsb);
1743                 if (j)
1744                 {
1745                         // texture included
1746                         if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1747                         {
1748                                 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1749                                 continue;
1750                         }
1751                         mtdata = miptexsb.data + j;
1752                 }
1753
1754                 if ((mtwidth & 15) || (mtheight & 15))
1755                         Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1756
1757                 // LordHavoc: force all names to lowercase
1758                 for (j = 0;name[j];j++)
1759                         if (name[j] >= 'A' && name[j] <= 'Z')
1760                                 name[j] += 'a' - 'A';
1761
1762                 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1763                 backuptex = loadmodel->data_textures[i];
1764                 if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1765                         continue;
1766                 loadmodel->data_textures[i] = backuptex;
1767
1768                 tx = loadmodel->data_textures + i;
1769                 strlcpy(tx->name, name, sizeof(tx->name));
1770                 tx->width = mtwidth;
1771                 tx->height = mtheight;
1772
1773                 if (tx->name[0] == '*')
1774                 {
1775                         if (!strncmp(tx->name, "*lava", 5))
1776                         {
1777                                 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1778                                 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1779                         }
1780                         else if (!strncmp(tx->name, "*slime", 6))
1781                         {
1782                                 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1783                                 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1784                         }
1785                         else
1786                         {
1787                                 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1788                                 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1789                         }
1790                 }
1791                 else if (!strncmp(tx->name, "sky", 3))
1792                 {
1793                         tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1794                         tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1795                         // for the surface traceline we need to hit this surface as a solid...
1796                         tx->supercontents |= SUPERCONTENTS_SOLID;
1797                 }
1798                 else
1799                 {
1800                         tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1801                         tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1802                 }
1803
1804                 if (cls.state != ca_dedicated)
1805                 {
1806                         // LordHavoc: HL sky textures are entirely different than quake
1807                         if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1808                         {
1809                                 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1810                                 if (!data)
1811                                         data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1812                                 if (data && image_width == image_height * 2)
1813                                 {
1814                                         R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1815                                         Mem_Free(data);
1816                                 }
1817                                 else if (mtdata != NULL)
1818                                         R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1819                         }
1820                         else
1821                         {
1822                                 skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
1823                                 if (!skinframe)
1824                                         skinframe = R_SkinFrame_LoadExternal(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, false);
1825                                 if (skinframe)
1826                                         tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1827                                 if (!skinframe)
1828                                 {
1829                                         // did not find external texture, load it from the bsp or wad3
1830                                         if (loadmodel->brush.ishlbsp)
1831                                         {
1832                                                 // internal texture overrides wad
1833                                                 unsigned char *pixels, *freepixels;
1834                                                 pixels = freepixels = NULL;
1835                                                 if (mtdata)
1836                                                         pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1837                                                 if (pixels == NULL)
1838                                                         pixels = freepixels = W_GetTextureBGRA(tx->name);
1839                                                 if (pixels != NULL)
1840                                                 {
1841                                                         tx->width = image_width;
1842                                                         tx->height = image_height;
1843                                                         skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1844                                                 }
1845                                                 if (freepixels)
1846                                                         Mem_Free(freepixels);
1847                                         }
1848                                         else if (mtdata) // texture included
1849                                                 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1850                                 }
1851                                 // if skinframe is still NULL the "missing" texture will be used
1852                                 if (skinframe)
1853                                         tx->skinframes[0] = skinframe;
1854                         }
1855                         // LordHavoc: some Tenebrae textures get replaced by black
1856                         if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1857                                 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1858                         else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1859                                 tx->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1860                 }
1861
1862                 tx->basematerialflags = MATERIALFLAG_WALL;
1863                 if (tx->name[0] == '*')
1864                 {
1865                         // LordHavoc: some turbulent textures should not be affected by wateralpha
1866                         if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1867                                 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1868                         else if (!strncmp(tx->name,"*lava",5)
1869                          || !strncmp(tx->name,"*teleport",9)
1870                          || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1871                                 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1872                         else
1873                                 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1874                         if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1875                                 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1876                 }
1877                 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1878                 {
1879                         // replace the texture with black
1880                         tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1881                 }
1882                 else if (!strncmp(tx->name, "sky", 3))
1883                         tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1884                 else if (!strcmp(tx->name, "caulk"))
1885                         tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1886                 else if (tx->skinframes[0] && tx->skinframes[0]->hasalpha)
1887                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1888
1889                 // start out with no animation
1890                 tx->currentframe = tx;
1891                 tx->currentskinframe = tx->skinframes[0];
1892                 tx->currentmaterialflags = tx->basematerialflags;
1893         }
1894
1895         // sequence the animations
1896         for (i = 0;i < nummiptex;i++)
1897         {
1898                 tx = loadmodel->data_textures + i;
1899                 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1900                         continue;
1901                 if (tx->anim_total[0] || tx->anim_total[1])
1902                         continue;       // already sequenced
1903
1904                 // find the number of frames in the animation
1905                 memset(anims, 0, sizeof(anims));
1906                 memset(altanims, 0, sizeof(altanims));
1907
1908                 for (j = i;j < nummiptex;j++)
1909                 {
1910                         tx2 = loadmodel->data_textures + j;
1911                         if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1912                                 continue;
1913
1914                         num = tx2->name[1];
1915                         if (num >= '0' && num <= '9')
1916                                 anims[num - '0'] = tx2;
1917                         else if (num >= 'a' && num <= 'j')
1918                                 altanims[num - 'a'] = tx2;
1919                         else
1920                                 Con_Printf("Bad animating texture %s\n", tx->name);
1921                 }
1922
1923                 max = altmax = 0;
1924                 for (j = 0;j < 10;j++)
1925                 {
1926                         if (anims[j])
1927                                 max = j + 1;
1928                         if (altanims[j])
1929                                 altmax = j + 1;
1930                 }
1931                 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1932
1933                 incomplete = false;
1934                 for (j = 0;j < max;j++)
1935                 {
1936                         if (!anims[j])
1937                         {
1938                                 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1939                                 incomplete = true;
1940                         }
1941                 }
1942                 for (j = 0;j < altmax;j++)
1943                 {
1944                         if (!altanims[j])
1945                         {
1946                                 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1947                                 incomplete = true;
1948                         }
1949                 }
1950                 if (incomplete)
1951                         continue;
1952
1953                 if (altmax < 1)
1954                 {
1955                         // if there is no alternate animation, duplicate the primary
1956                         // animation into the alternate
1957                         altmax = max;
1958                         for (k = 0;k < 10;k++)
1959                                 altanims[k] = anims[k];
1960                 }
1961
1962                 // link together the primary animation
1963                 for (j = 0;j < max;j++)
1964                 {
1965                         tx2 = anims[j];
1966                         tx2->animated = true;
1967                         tx2->anim_total[0] = max;
1968                         tx2->anim_total[1] = altmax;
1969                         for (k = 0;k < 10;k++)
1970                         {
1971                                 tx2->anim_frames[0][k] = anims[k];
1972                                 tx2->anim_frames[1][k] = altanims[k];
1973                         }
1974                 }
1975
1976                 // if there really is an alternate anim...
1977                 if (anims[0] != altanims[0])
1978                 {
1979                         // link together the alternate animation
1980                         for (j = 0;j < altmax;j++)
1981                         {
1982                                 tx2 = altanims[j];
1983                                 tx2->animated = true;
1984                                 // the primary/alternate are reversed here
1985                                 tx2->anim_total[0] = altmax;
1986                                 tx2->anim_total[1] = max;
1987                                 for (k = 0;k < 10;k++)
1988                                 {
1989                                         tx2->anim_frames[0][k] = altanims[k];
1990                                         tx2->anim_frames[1][k] = anims[k];
1991                                 }
1992                         }
1993                 }
1994         }
1995 }
1996
1997 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
1998 {
1999         int i;
2000         unsigned char *in, *out, *data, d;
2001         char litfilename[MAX_QPATH];
2002         char dlitfilename[MAX_QPATH];
2003         fs_offset_t filesize;
2004         if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
2005         {
2006                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2007                 for (i = 0;i < sb->cursize;i++)
2008                         loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2009         }
2010         else // LordHavoc: bsp version 29 (normal white lighting)
2011         {
2012                 // LordHavoc: hope is not lost yet, check for a .lit file to load
2013                 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2014                 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2015                 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2016                 strlcat (litfilename, ".lit", sizeof (litfilename));
2017                 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2018                 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2019                 if (data)
2020                 {
2021                         if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2022                         {
2023                                 i = LittleLong(((int *)data)[1]);
2024                                 if (i == 1)
2025                                 {
2026                                         if (developer_loading.integer)
2027                                                 Con_Printf("loaded %s\n", litfilename);
2028                                         loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2029                                         memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2030                                         Mem_Free(data);
2031                                         data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2032                                         if (data)
2033                                         {
2034                                                 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2035                                                 {
2036                                                         i = LittleLong(((int *)data)[1]);
2037                                                         if (i == 1)
2038                                                         {
2039                                                                 if (developer_loading.integer)
2040                                                                         Con_Printf("loaded %s\n", dlitfilename);
2041                                                                 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2042                                                                 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2043                                                                 loadmodel->brushq3.deluxemapping_modelspace = false;
2044                                                                 loadmodel->brushq3.deluxemapping = true;
2045                                                         }
2046                                                 }
2047                                                 Mem_Free(data);
2048                                                 data = NULL;
2049                                         }
2050                                         return;
2051                                 }
2052                                 else
2053                                         Con_Printf("Unknown .lit file version (%d)\n", i);
2054                         }
2055                         else if (filesize == 8)
2056                                 Con_Print("Empty .lit file, ignoring\n");
2057                         else
2058                                 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2059                         if (data)
2060                         {
2061                                 Mem_Free(data);
2062                                 data = NULL;
2063                         }
2064                 }
2065                 // LordHavoc: oh well, expand the white lighting data
2066                 if (!sb->cursize)
2067                         return;
2068                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2069                 in = sb->data;
2070                 out = loadmodel->brushq1.lightdata;
2071                 for (i = 0;i < sb->cursize;i++)
2072                 {
2073                         d = *in++;
2074                         *out++ = d;
2075                         *out++ = d;
2076                         *out++ = d;
2077                 }
2078         }
2079 }
2080
2081 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2082 {
2083         loadmodel->brushq1.num_compressedpvs = 0;
2084         loadmodel->brushq1.data_compressedpvs = NULL;
2085         if (!sb->cursize)
2086                 return;
2087         loadmodel->brushq1.num_compressedpvs = sb->cursize;
2088         loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2089         MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2090 }
2091
2092 // used only for HalfLife maps
2093 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2094 {
2095         char key[128], value[4096];
2096         int i, j, k;
2097         if (!data)
2098                 return;
2099         if (!COM_ParseToken_Simple(&data, false, false, true))
2100                 return; // error
2101         if (com_token[0] != '{')
2102                 return; // error
2103         while (1)
2104         {
2105                 if (!COM_ParseToken_Simple(&data, false, false, true))
2106                         return; // error
2107                 if (com_token[0] == '}')
2108                         break; // end of worldspawn
2109                 if (com_token[0] == '_')
2110                         strlcpy(key, com_token + 1, sizeof(key));
2111                 else
2112                         strlcpy(key, com_token, sizeof(key));
2113                 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2114                         key[strlen(key)-1] = 0;
2115                 if (!COM_ParseToken_Simple(&data, false, false, true))
2116                         return; // error
2117                 dpsnprintf(value, sizeof(value), "%s", com_token);
2118                 if (!strcmp("wad", key)) // for HalfLife maps
2119                 {
2120                         if (loadmodel->brush.ishlbsp)
2121                         {
2122                                 j = 0;
2123                                 for (i = 0;i < (int)sizeof(value);i++)
2124                                         if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2125                                                 break;
2126                                 if (value[i])
2127                                 {
2128                                         for (;i < (int)sizeof(value);i++)
2129                                         {
2130                                                 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2131                                                 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2132                                                         j = i+1;
2133                                                 else if (value[i] == ';' || value[i] == 0)
2134                                                 {
2135                                                         k = value[i];
2136                                                         value[i] = 0;
2137                                                         W_LoadTextureWadFile(&value[j], false);
2138                                                         j = i+1;
2139                                                         if (!k)
2140                                                                 break;
2141                                                 }
2142                                         }
2143                                 }
2144                         }
2145                 }
2146         }
2147 }
2148
2149 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2150 {
2151         loadmodel->brush.entities = NULL;
2152         if (!sb->cursize)
2153                 return;
2154         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2155         MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2156         loadmodel->brush.entities[sb->cursize] = 0;
2157         if (loadmodel->brush.ishlbsp)
2158                 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2159 }
2160
2161
2162 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2163 {
2164         mvertex_t       *out;
2165         int                     i, count;
2166         size_t          structsize = 12;
2167
2168         if (sb->cursize % structsize)
2169                 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2170         count = sb->cursize / structsize;
2171         out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2172
2173         loadmodel->brushq1.vertexes = out;
2174         loadmodel->brushq1.numvertexes = count;
2175
2176         for ( i=0 ; i<count ; i++, out++)
2177         {
2178                 out->position[0] = MSG_ReadLittleFloat(sb);
2179                 out->position[1] = MSG_ReadLittleFloat(sb);
2180                 out->position[2] = MSG_ReadLittleFloat(sb);
2181         }
2182 }
2183
2184 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2185 {
2186         mmodel_t        *out;
2187         int                     i, j, count;
2188         size_t structsize = (48+4*hullinfo->filehulls);
2189
2190         if (sb->cursize % structsize)
2191                 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2192
2193         count = sb->cursize / structsize;
2194         out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2195
2196         loadmodel->brushq1.submodels = out;
2197         loadmodel->brush.numsubmodels = count;
2198
2199         for (i = 0; i < count; i++, out++)
2200         {
2201         // spread out the mins / maxs by a pixel
2202                 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2203                 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2204                 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2205                 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2206                 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2207                 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2208                 out->origin[0] = MSG_ReadLittleFloat(sb);
2209                 out->origin[1] = MSG_ReadLittleFloat(sb);
2210                 out->origin[2] = MSG_ReadLittleFloat(sb);
2211                 for (j = 0; j < hullinfo->filehulls; j++)
2212                         out->headnode[j] = MSG_ReadLittleLong(sb);
2213                 out->visleafs  = MSG_ReadLittleLong(sb);
2214                 out->firstface = MSG_ReadLittleLong(sb);
2215                 out->numfaces  = MSG_ReadLittleLong(sb);
2216         }
2217 }
2218
2219 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2220 {
2221         medge_t *out;
2222         int     i, count;
2223         size_t  structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2224
2225         if (sb->cursize % structsize)
2226                 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2227         count = sb->cursize / structsize;
2228         out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2229
2230         loadmodel->brushq1.edges = out;
2231         loadmodel->brushq1.numedges = count;
2232
2233         for ( i=0 ; i<count ; i++, out++)
2234         {
2235                 if (loadmodel->brush.isbsp2)
2236                 {
2237                         out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2238                         out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2239                 }
2240                 else
2241                 {
2242                         out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2243                         out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2244                 }
2245                 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2246                 {
2247                         Con_Printf("Mod_Q1BSP_LoadEdges: %s has invalid vertex indices in edge %i (vertices %i %i >= numvertices %i)\n", loadmodel->name, i, out->v[0], out->v[1], loadmodel->brushq1.numvertexes);
2248                         if(!loadmodel->brushq1.numvertexes)
2249                                 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2250                                 
2251                         out->v[0] = 0;
2252                         out->v[1] = 0;
2253                 }
2254         }
2255 }
2256
2257 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2258 {
2259         mtexinfo_t *out;
2260         int i, j, k, count, miptex;
2261         size_t structsize = 40;
2262
2263         if (sb->cursize % structsize)
2264                 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2265         count = sb->cursize / structsize;
2266         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2267
2268         loadmodel->brushq1.texinfo = out;
2269         loadmodel->brushq1.numtexinfo = count;
2270
2271         for (i = 0;i < count;i++, out++)
2272         {
2273                 for (k = 0;k < 2;k++)
2274                         for (j = 0;j < 4;j++)
2275                                 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2276
2277                 miptex = MSG_ReadLittleLong(sb);
2278                 out->flags = MSG_ReadLittleLong(sb);
2279
2280                 out->texture = NULL;
2281                 if (loadmodel->data_textures)
2282                 {
2283                         if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2284                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2285                         else
2286                                 out->texture = loadmodel->data_textures + miptex;
2287                 }
2288                 if (out->flags & TEX_SPECIAL)
2289                 {
2290                         // if texture chosen is NULL or the shader needs a lightmap,
2291                         // force to notexture water shader
2292                         if (out->texture == NULL)
2293                                 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 1);
2294                 }
2295                 else
2296                 {
2297                         // if texture chosen is NULL, force to notexture
2298                         if (out->texture == NULL)
2299                                 out->texture = loadmodel->data_textures + (loadmodel->num_textures - 2);
2300                 }
2301         }
2302 }
2303
2304 #if 0
2305 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2306 {
2307         int             i, j;
2308         float   *v;
2309
2310         mins[0] = mins[1] = mins[2] = 9999;
2311         maxs[0] = maxs[1] = maxs[2] = -9999;
2312         v = verts;
2313         for (i = 0;i < numverts;i++)
2314         {
2315                 for (j = 0;j < 3;j++, v++)
2316                 {
2317                         if (*v < mins[j])
2318                                 mins[j] = *v;
2319                         if (*v > maxs[j])
2320                                 maxs[j] = *v;
2321                 }
2322         }
2323 }
2324
2325 #define MAX_SUBDIVPOLYTRIANGLES 4096
2326 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2327
2328 static int subdivpolyverts, subdivpolytriangles;
2329 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2330 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2331
2332 static int subdivpolylookupvert(vec3_t v)
2333 {
2334         int i;
2335         for (i = 0;i < subdivpolyverts;i++)
2336                 if (subdivpolyvert[i][0] == v[0]
2337                  && subdivpolyvert[i][1] == v[1]
2338                  && subdivpolyvert[i][2] == v[2])
2339                         return i;
2340         if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2341                 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2342         VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2343         return subdivpolyverts++;
2344 }
2345
2346 static void SubdividePolygon(int numverts, float *verts)
2347 {
2348         int             i, i1, i2, i3, f, b, c, p;
2349         vec3_t  mins, maxs, front[256], back[256];
2350         float   m, *pv, *cv, dist[256], frac;
2351
2352         if (numverts > 250)
2353                 Host_Error("SubdividePolygon: ran out of verts in buffer");
2354
2355         BoundPoly(numverts, verts, mins, maxs);
2356
2357         for (i = 0;i < 3;i++)
2358         {
2359                 m = (mins[i] + maxs[i]) * 0.5;
2360                 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2361                 if (maxs[i] - m < 8)
2362                         continue;
2363                 if (m - mins[i] < 8)
2364                         continue;
2365
2366                 // cut it
2367                 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2368                         dist[c] = cv[i] - m;
2369
2370                 f = b = 0;
2371                 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2372                 {
2373                         if (dist[p] >= 0)
2374                         {
2375                                 VectorCopy(pv, front[f]);
2376                                 f++;
2377                         }
2378                         if (dist[p] <= 0)
2379                         {
2380                                 VectorCopy(pv, back[b]);
2381                                 b++;
2382                         }
2383                         if (dist[p] == 0 || dist[c] == 0)
2384                                 continue;
2385                         if ((dist[p] > 0) != (dist[c] > 0) )
2386                         {
2387                                 // clip point
2388                                 frac = dist[p] / (dist[p] - dist[c]);
2389                                 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2390                                 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2391                                 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2392                                 f++;
2393                                 b++;
2394                         }
2395                 }
2396
2397                 SubdividePolygon(f, front[0]);
2398                 SubdividePolygon(b, back[0]);
2399                 return;
2400         }
2401
2402         i1 = subdivpolylookupvert(verts);
2403         i2 = subdivpolylookupvert(verts + 3);
2404         for (i = 2;i < numverts;i++)
2405         {
2406                 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2407                 {
2408                         Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2409                         return;
2410                 }
2411
2412                 i3 = subdivpolylookupvert(verts + i * 3);
2413                 subdivpolyindex[subdivpolytriangles][0] = i1;
2414                 subdivpolyindex[subdivpolytriangles][1] = i2;
2415                 subdivpolyindex[subdivpolytriangles][2] = i3;
2416                 i2 = i3;
2417                 subdivpolytriangles++;
2418         }
2419 }
2420
2421 //Breaks a polygon up along axial 64 unit
2422 //boundaries so that turbulent and sky warps
2423 //can be done reasonably.
2424 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2425 {
2426         int i, j;
2427         surfvertex_t *v;
2428         surfmesh_t *mesh;
2429
2430         subdivpolytriangles = 0;
2431         subdivpolyverts = 0;
2432         SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2433         if (subdivpolytriangles < 1)
2434                 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2435
2436         surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2437         mesh->num_vertices = subdivpolyverts;
2438         mesh->num_triangles = subdivpolytriangles;
2439         mesh->vertex = (surfvertex_t *)(mesh + 1);
2440         mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2441         memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2442
2443         for (i = 0;i < mesh->num_triangles;i++)
2444                 for (j = 0;j < 3;j++)
2445                         mesh->index[i*3+j] = subdivpolyindex[i][j];
2446
2447         for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2448         {
2449                 VectorCopy(subdivpolyvert[i], v->v);
2450                 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2451                 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2452         }
2453 }
2454 #endif
2455
2456 extern cvar_t gl_max_lightmapsize;
2457 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2458 {
2459         msurface_t *surface;
2460         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2461         float texmins[2], texmaxs[2], val;
2462         rtexture_t *lightmaptexture, *deluxemaptexture;
2463         char vabuf[1024];
2464         size_t structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2465
2466         if (sb->cursize % structsize)
2467                 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2468         count = sb->cursize / structsize;
2469         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2470         loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2471
2472         loadmodel->num_surfaces = count;
2473
2474         loadmodel->brushq1.firstrender = true;
2475         loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2476
2477         totalverts = 0;
2478         totaltris = 0;
2479         for (surfacenum = 0;surfacenum < count;surfacenum++)
2480         {
2481                 if (loadmodel->brush.isbsp2)
2482                         numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2483                 else
2484                         numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2485                 totalverts += numedges;
2486                 totaltris += numedges - 2;
2487         }
2488
2489         Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2490
2491         lightmaptexture = NULL;
2492         deluxemaptexture = r_texture_blanknormalmap;
2493         lightmapnumber = 0;
2494         lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2495         totallightmapsamples = 0;
2496
2497         totalverts = 0;
2498         totaltris = 0;
2499         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2500         {
2501                 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2502                 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2503                 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2504                 firstedge = MSG_ReadLittleLong(sb);
2505                 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2506                 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2507                 for (i = 0;i < MAXLIGHTMAPS;i++)
2508                         surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2509                 lightmapoffset = MSG_ReadLittleLong(sb);
2510
2511                 // FIXME: validate edges, texinfo, etc?
2512                 if ((unsigned int) firstedge > (unsigned int) loadmodel->brushq1.numsurfedges || (unsigned int) numedges > (unsigned int) loadmodel->brushq1.numsurfedges || (unsigned int) firstedge + (unsigned int) numedges > (unsigned int) loadmodel->brushq1.numsurfedges)
2513                         Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2514                 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2515                         Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2516                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2517                         Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2518
2519                 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2520                 surface->texture = surface->lightmapinfo->texinfo->texture;
2521
2522                 //surface->flags = surface->texture->flags;
2523                 //if (LittleShort(in->side))
2524                 //      surface->flags |= SURF_PLANEBACK;
2525                 //surface->plane = loadmodel->brush.data_planes + planenum;
2526
2527                 surface->num_firstvertex = totalverts;
2528                 surface->num_vertices = numedges;
2529                 surface->num_firsttriangle = totaltris;
2530                 surface->num_triangles = numedges - 2;
2531                 totalverts += numedges;
2532                 totaltris += numedges - 2;
2533
2534                 // convert edges back to a normal polygon
2535                 for (i = 0;i < surface->num_vertices;i++)
2536                 {
2537                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2538                         float s, t;
2539                         // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2540                         if (lindex >= 0)
2541                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2542                         else
2543                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2544                         s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2545                         t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2546                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2547                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2548                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2549                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2550                         (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2551                 }
2552
2553                 for (i = 0;i < surface->num_triangles;i++)
2554                 {
2555                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2556                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2557                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2558                 }
2559
2560                 // compile additional data about the surface geometry
2561                 Mod_BuildNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, loadmodel->surfmesh.data_vertex3f, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle), loadmodel->surfmesh.data_normal3f, r_smoothnormals_areaweighting.integer != 0);
2562                 Mod_BuildTextureVectorsFromNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle), loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
2563                 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2564
2565                 // generate surface extents information
2566                 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2567                 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2568                 for (i = 1;i < surface->num_vertices;i++)
2569                 {
2570                         for (j = 0;j < 2;j++)
2571                         {
2572                                 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2573                                 texmins[j] = min(texmins[j], val);
2574                                 texmaxs[j] = max(texmaxs[j], val);
2575                         }
2576                 }
2577                 for (i = 0;i < 2;i++)
2578                 {
2579                         surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2580                         surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2581                 }
2582
2583                 smax = surface->lightmapinfo->extents[0] >> 4;
2584                 tmax = surface->lightmapinfo->extents[1] >> 4;
2585                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2586                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2587
2588                 // lighting info
2589                 surface->lightmaptexture = NULL;
2590                 surface->deluxemaptexture = r_texture_blanknormalmap;
2591                 if (lightmapoffset == -1)
2592                 {
2593                         surface->lightmapinfo->samples = NULL;
2594 #if 1
2595                         // give non-lightmapped water a 1x white lightmap
2596                         if (surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2597                         {
2598                                 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2599                                 surface->lightmapinfo->styles[0] = 0;
2600                                 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2601                         }
2602 #endif
2603                 }
2604                 else if (loadmodel->brush.ishlbsp) // LordHavoc: HalfLife map (bsp version 30)
2605                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2606                 else // LordHavoc: white lighting (bsp version 29)
2607                 {
2608                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2609                         if (loadmodel->brushq1.nmaplightdata)
2610                                 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2611                 }
2612
2613                 // check if we should apply a lightmap to this
2614                 if (!(surface->lightmapinfo->texinfo->flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2615                 {
2616                         if (ssize > 256 || tsize > 256)
2617                                 Host_Error("Bad surface extents");
2618
2619                         if (lightmapsize < ssize)
2620                                 lightmapsize = ssize;
2621                         if (lightmapsize < tsize)
2622                                 lightmapsize = tsize;
2623
2624                         totallightmapsamples += ssize*tsize;
2625
2626                         // force lightmap upload on first time seeing the surface
2627                         //
2628                         // additionally this is used by the later code to see if a
2629                         // lightmap is needed on this surface (rather than duplicating the
2630                         // logic above)
2631                         loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2632                         loadmodel->lit = true;
2633                 }
2634         }
2635
2636         // small maps (such as ammo boxes especially) don't need big lightmap
2637         // textures, so this code tries to guess a good size based on
2638         // totallightmapsamples (size of the lightmaps lump basically), as well as
2639         // trying to max out the size if there is a lot of lightmap data to store
2640         // additionally, never choose a lightmapsize that is smaller than the
2641         // largest surface encountered (as it would fail)
2642         i = lightmapsize;
2643         for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2644                 ;
2645
2646         // now that we've decided the lightmap texture size, we can do the rest
2647         if (cls.state != ca_dedicated)
2648         {
2649                 int stainmapsize = 0;
2650                 mod_alloclightmap_state_t allocState;
2651
2652                 Mod_AllocLightmap_Init(&allocState, lightmapsize, lightmapsize);
2653                 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2654                 {
2655                         int i, iu, iv, lightmapx = 0, lightmapy = 0;
2656                         float u, v, ubase, vbase, uscale, vscale;
2657
2658                         if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2659                                 continue;
2660
2661                         smax = surface->lightmapinfo->extents[0] >> 4;
2662                         tmax = surface->lightmapinfo->extents[1] >> 4;
2663                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2664                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2665                         stainmapsize += ssize * tsize * 3;
2666
2667                         if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2668                         {
2669                                 // allocate a texture pool if we need it
2670                                 if (loadmodel->texturepool == NULL)
2671                                         loadmodel->texturepool = R_AllocTexturePool();
2672                                 // could not find room, make a new lightmap
2673                                 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2674                                 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2675                                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2676                                 loadmodel->brushq3.data_lightmaps[lightmapnumber] = lightmaptexture = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2677                                 if (loadmodel->brushq1.nmaplightdata)
2678                                         loadmodel->brushq3.data_deluxemaps[lightmapnumber] = deluxemaptexture = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "deluxemap%i", lightmapnumber), lightmapsize, lightmapsize, NULL, TEXTYPE_BGRA, TEXF_FORCELINEAR | TEXF_ALLOWUPDATES, -1, NULL);
2679                                 lightmapnumber++;
2680                                 Mod_AllocLightmap_Reset(&allocState);
2681                                 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2682                         }
2683                         surface->lightmaptexture = lightmaptexture;
2684                         surface->deluxemaptexture = deluxemaptexture;
2685                         surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2686                         surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2687
2688                         uscale = 1.0f / (float)lightmapsize;
2689                         vscale = 1.0f / (float)lightmapsize;
2690                         ubase = lightmapx * uscale;
2691                         vbase = lightmapy * vscale;
2692
2693                         for (i = 0;i < surface->num_vertices;i++)
2694                         {
2695                                 u = ((DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3]) + 8 - surface->lightmapinfo->texturemins[0]) * (1.0 / 16.0);
2696                                 v = ((DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3]) + 8 - surface->lightmapinfo->texturemins[1]) * (1.0 / 16.0);
2697                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2698                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2699                                 // LordHavoc: calc lightmap data offset for vertex lighting to use
2700                                 iu = (int) u;
2701                                 iv = (int) v;
2702                                 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2703                         }
2704                 }
2705
2706                 if (cl_stainmaps.integer)
2707                 {
2708                         // allocate stainmaps for permanent marks on walls and clear white
2709                         unsigned char *stainsamples = NULL;
2710                         stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2711                         memset(stainsamples, 255, stainmapsize);
2712                         // assign pointers
2713                         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2714                         {
2715                                 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2716                                         continue;
2717                                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2718                                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2719                                 surface->lightmapinfo->stainsamples = stainsamples;
2720                                 stainsamples += ssize * tsize * 3;
2721                         }
2722                 }
2723         }
2724
2725         // generate ushort elements array if possible
2726         if (loadmodel->surfmesh.data_element3s)
2727                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2728                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2729 }
2730
2731 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2732 {
2733         //if (node->parent)
2734         //      Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2735         node->parent = parent;
2736         if (node->plane)
2737         {
2738                 // this is a node, recurse to children
2739                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2740                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2741                 // combine supercontents of children
2742                 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2743         }
2744         else
2745         {
2746                 int j;
2747                 mleaf_t *leaf = (mleaf_t *)node;
2748                 // if this is a leaf, calculate supercontents mask from all collidable
2749                 // primitives in the leaf (brushes and collision surfaces)
2750                 // also flag if the leaf contains any collision surfaces
2751                 leaf->combinedsupercontents = 0;
2752                 // combine the supercontents values of all brushes in this leaf
2753                 for (j = 0;j < leaf->numleafbrushes;j++)
2754                         leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2755                 // check if this leaf contains any collision surfaces (q3 patches)
2756                 for (j = 0;j < leaf->numleafsurfaces;j++)
2757                 {
2758                         msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2759                         if (surface->num_collisiontriangles)
2760                         {
2761                                 leaf->containscollisionsurfaces = true;
2762                                 leaf->combinedsupercontents |= surface->texture->supercontents;
2763                         }
2764                 }
2765         }
2766 }
2767
2768 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2769 {
2770         int                     i, j, count, p, child[2];
2771         mnode_t         *out;
2772         size_t structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2773
2774         if (sb->cursize % structsize)
2775                 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2776         count = sb->cursize / structsize;
2777         if (count == 0)
2778                 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2779         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2780
2781         loadmodel->brush.data_nodes = out;
2782         loadmodel->brush.num_nodes = count;
2783
2784         for ( i=0 ; i<count ; i++, out++)
2785         {
2786                 p = MSG_ReadLittleLong(sb);
2787                 out->plane = loadmodel->brush.data_planes + p;
2788
2789                 if (loadmodel->brush.isbsp2rmqe)
2790                 {
2791                         child[0] = MSG_ReadLittleLong(sb);
2792                         child[1] = MSG_ReadLittleLong(sb);
2793                         out->mins[0] = MSG_ReadLittleShort(sb);
2794                         out->mins[1] = MSG_ReadLittleShort(sb);
2795                         out->mins[2] = MSG_ReadLittleShort(sb);
2796                         out->maxs[0] = MSG_ReadLittleShort(sb);
2797                         out->maxs[1] = MSG_ReadLittleShort(sb);
2798                         out->maxs[2] = MSG_ReadLittleShort(sb);
2799                         out->firstsurface = MSG_ReadLittleLong(sb);
2800                         out->numsurfaces = MSG_ReadLittleLong(sb);
2801                 }
2802                 else if (loadmodel->brush.isbsp2)
2803                 {
2804                         child[0] = MSG_ReadLittleLong(sb);
2805                         child[1] = MSG_ReadLittleLong(sb);
2806                         out->mins[0] = MSG_ReadLittleFloat(sb);
2807                         out->mins[1] = MSG_ReadLittleFloat(sb);
2808                         out->mins[2] = MSG_ReadLittleFloat(sb);
2809                         out->maxs[0] = MSG_ReadLittleFloat(sb);
2810                         out->maxs[1] = MSG_ReadLittleFloat(sb);
2811                         out->maxs[2] = MSG_ReadLittleFloat(sb);
2812                         out->firstsurface = MSG_ReadLittleLong(sb);
2813                         out->numsurfaces = MSG_ReadLittleLong(sb);
2814                 }
2815                 else
2816                 {
2817                         child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2818                         child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2819                         if (child[0] >= count)
2820                                 child[0] -= 65536;
2821                         if (child[1] >= count)
2822                                 child[1] -= 65536;
2823
2824                         out->mins[0] = MSG_ReadLittleShort(sb);
2825                         out->mins[1] = MSG_ReadLittleShort(sb);
2826                         out->mins[2] = MSG_ReadLittleShort(sb);
2827                         out->maxs[0] = MSG_ReadLittleShort(sb);
2828                         out->maxs[1] = MSG_ReadLittleShort(sb);
2829                         out->maxs[2] = MSG_ReadLittleShort(sb);
2830
2831                         out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2832                         out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2833                 }
2834
2835                 for (j=0 ; j<2 ; j++)
2836                 {
2837                         // LordHavoc: this code supports broken bsp files produced by
2838                         // arguire qbsp which can produce more than 32768 nodes, any value
2839                         // below count is assumed to be a node number, any other value is
2840                         // assumed to be a leaf number
2841                         p = child[j];
2842                         if (p >= 0)
2843                         {
2844                                 if (p < loadmodel->brush.num_nodes)
2845                                         out->children[j] = loadmodel->brush.data_nodes + p;
2846                                 else
2847                                 {
2848                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2849                                         // map it to the solid leaf
2850                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2851                                 }
2852                         }
2853                         else
2854                         {
2855                                 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2856                                 p = -(p+1);
2857                                 if (p < loadmodel->brush.num_leafs)
2858                                         out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2859                                 else
2860                                 {
2861                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2862                                         // map it to the solid leaf
2863                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2864                                 }
2865                         }
2866                 }
2867         }
2868
2869         Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);      // sets nodes and leafs
2870 }
2871
2872 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2873 {
2874         mleaf_t *out;
2875         int i, j, count, p, firstmarksurface, nummarksurfaces;
2876         size_t structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2877
2878         if (sb->cursize % structsize)
2879                 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2880         count = sb->cursize / structsize;
2881         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2882
2883         loadmodel->brush.data_leafs = out;
2884         loadmodel->brush.num_leafs = count;
2885         // get visleafs from the submodel data
2886         loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2887         loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2888         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2889         memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2890
2891         // FIXME: this function could really benefit from some error checking
2892         for ( i=0 ; i<count ; i++, out++)
2893         {
2894                 out->contents = MSG_ReadLittleLong(sb);
2895
2896                 out->clusterindex = i - 1;
2897                 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
2898                         out->clusterindex = -1;
2899
2900                 p = MSG_ReadLittleLong(sb);
2901                 // ignore visofs errors on leaf 0 (solid)
2902                 if (p >= 0 && out->clusterindex >= 0)
2903                 {
2904                         if (p >= loadmodel->brushq1.num_compressedpvs)
2905                                 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
2906                         else
2907                                 Mod_Q1BSP_DecompressVis(loadmodel->brushq1.data_compressedpvs + p, loadmodel->brushq1.data_compressedpvs + loadmodel->brushq1.num_compressedpvs, loadmodel->brush.data_pvsclusters + out->clusterindex * loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.data_pvsclusters + (out->clusterindex + 1) * loadmodel->brush.num_pvsclusterbytes);
2908                 }
2909
2910                 if (loadmodel->brush.isbsp2rmqe)
2911                 {
2912                         out->mins[0] = MSG_ReadLittleShort(sb);
2913                         out->mins[1] = MSG_ReadLittleShort(sb);
2914                         out->mins[2] = MSG_ReadLittleShort(sb);
2915                         out->maxs[0] = MSG_ReadLittleShort(sb);
2916                         out->maxs[1] = MSG_ReadLittleShort(sb);
2917                         out->maxs[2] = MSG_ReadLittleShort(sb);
2918         
2919                         firstmarksurface = MSG_ReadLittleLong(sb);
2920                         nummarksurfaces = MSG_ReadLittleLong(sb);
2921                 }
2922                 else if (loadmodel->brush.isbsp2)
2923                 {
2924                         out->mins[0] = MSG_ReadLittleFloat(sb);
2925                         out->mins[1] = MSG_ReadLittleFloat(sb);
2926                         out->mins[2] = MSG_ReadLittleFloat(sb);
2927                         out->maxs[0] = MSG_ReadLittleFloat(sb);
2928                         out->maxs[1] = MSG_ReadLittleFloat(sb);
2929                         out->maxs[2] = MSG_ReadLittleFloat(sb);
2930         
2931                         firstmarksurface = MSG_ReadLittleLong(sb);
2932                         nummarksurfaces = MSG_ReadLittleLong(sb);
2933                 }
2934                 else
2935                 {
2936                         out->mins[0] = MSG_ReadLittleShort(sb);
2937                         out->mins[1] = MSG_ReadLittleShort(sb);
2938                         out->mins[2] = MSG_ReadLittleShort(sb);
2939                         out->maxs[0] = MSG_ReadLittleShort(sb);
2940                         out->maxs[1] = MSG_ReadLittleShort(sb);
2941                         out->maxs[2] = MSG_ReadLittleShort(sb);
2942         
2943                         firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
2944                         nummarksurfaces  = (unsigned short)MSG_ReadLittleShort(sb);
2945                 }
2946
2947                 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
2948                 {
2949                         out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
2950                         out->numleafsurfaces = nummarksurfaces;
2951                 }
2952                 else
2953                 {
2954                         Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
2955                         out->firstleafsurface = NULL;
2956                         out->numleafsurfaces = 0;
2957                 }
2958
2959                 for (j = 0;j < 4;j++)
2960                         out->ambient_sound_level[j] = MSG_ReadByte(sb);
2961         }
2962 }
2963
2964 static qboolean Mod_Q1BSP_CheckWaterAlphaSupport(void)
2965 {
2966         int i, j;
2967         mleaf_t *leaf;
2968         const unsigned char *pvs;
2969         // if there's no vis data, assume supported (because everything is visible all the time)
2970         if (!loadmodel->brush.data_pvsclusters)
2971                 return true;
2972         // check all liquid leafs to see if they can see into empty leafs, if any
2973         // can we can assume this map supports r_wateralpha
2974         for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
2975         {
2976                 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
2977                 {
2978                         pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
2979                         for (j = 0;j < loadmodel->brush.num_leafs;j++)
2980                                 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
2981                                         return true;
2982                 }
2983         }
2984         return false;
2985 }
2986
2987 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
2988 {
2989         mclipnode_t *out;
2990         int                     i, count;
2991         hull_t          *hull;
2992         size_t structsize = loadmodel->brush.isbsp2 ? 12 : 8;
2993
2994         if (sb->cursize % structsize)
2995                 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
2996         count = sb->cursize / structsize;
2997         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2998
2999         loadmodel->brushq1.clipnodes = out;
3000         loadmodel->brushq1.numclipnodes = count;
3001
3002         for (i = 1; i < MAX_MAP_HULLS; i++)
3003         {
3004                 hull = &loadmodel->brushq1.hulls[i];
3005                 hull->clipnodes = out;
3006                 hull->firstclipnode = 0;
3007                 hull->lastclipnode = count-1;
3008                 hull->planes = loadmodel->brush.data_planes;
3009                 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3010                 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3011                 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3012                 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3013                 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3014                 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3015                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3016         }
3017
3018         for (i=0 ; i<count ; i++, out++)
3019         {
3020                 out->planenum = MSG_ReadLittleLong(sb);
3021                 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3022                         Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3023                 if (loadmodel->brush.isbsp2)
3024                 {
3025                         out->children[0] = MSG_ReadLittleLong(sb);
3026                         out->children[1] = MSG_ReadLittleLong(sb);
3027                         if (out->children[0] >= count)
3028                                 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3029                         if (out->children[1] >= count)
3030                                 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3031                 }
3032                 else
3033                 {
3034                         // LordHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3035                         out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3036                         out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3037                         if (out->children[0] >= count)
3038                                 out->children[0] -= 65536;
3039                         if (out->children[1] >= count)
3040                                 out->children[1] -= 65536;
3041                 }
3042         }
3043 }
3044
3045 //Duplicate the drawing hull structure as a clipping hull
3046 static void Mod_Q1BSP_MakeHull0(void)
3047 {
3048         mnode_t         *in;
3049         mclipnode_t *out;
3050         int                     i;
3051         hull_t          *hull;
3052
3053         hull = &loadmodel->brushq1.hulls[0];
3054
3055         in = loadmodel->brush.data_nodes;
3056         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3057
3058         hull->clipnodes = out;
3059         hull->firstclipnode = 0;
3060         hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3061         hull->planes = loadmodel->brush.data_planes;
3062
3063         for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3064         {
3065                 out->planenum = in->plane - loadmodel->brush.data_planes;
3066                 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3067                 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3068         }
3069 }
3070
3071 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3072 {
3073         int i, j;
3074         size_t structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3075
3076         if (sb->cursize % structsize)
3077                 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3078         loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3079         loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3080
3081         if (loadmodel->brush.isbsp2)
3082         {
3083                 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3084                 {
3085                         j = MSG_ReadLittleLong(sb);
3086                         if (j < 0 || j >= loadmodel->num_surfaces)
3087                                 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3088                         loadmodel->brush.data_leafsurfaces[i] = j;
3089                 }
3090         }
3091         else
3092         {
3093                 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3094                 {
3095                         j = (unsigned short) MSG_ReadLittleShort(sb);
3096                         if (j >= loadmodel->num_surfaces)
3097                                 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3098                         loadmodel->brush.data_leafsurfaces[i] = j;
3099                 }
3100         }
3101 }
3102
3103 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3104 {
3105         int             i;
3106         size_t structsize = 4;
3107
3108         if (sb->cursize % structsize)
3109                 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3110         loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3111         loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3112
3113         for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3114                 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3115 }
3116
3117
3118 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3119 {
3120         int                     i;
3121         mplane_t        *out;
3122         size_t structsize = 20;
3123
3124         if (sb->cursize % structsize)
3125                 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3126         loadmodel->brush.num_planes = sb->cursize / structsize;
3127         loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3128
3129         for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3130         {
3131                 out->normal[0] = MSG_ReadLittleFloat(sb);
3132                 out->normal[1] = MSG_ReadLittleFloat(sb);
3133                 out->normal[2] = MSG_ReadLittleFloat(sb);
3134                 out->dist = MSG_ReadLittleFloat(sb);
3135                 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3136                 PlaneClassify(out);
3137         }
3138 }
3139
3140 static void Mod_Q1BSP_LoadMapBrushes(void)
3141 {
3142 #if 0
3143 // unfinished
3144         int submodel, numbrushes;
3145         qboolean firstbrush;
3146         char *text, *maptext;
3147         char mapfilename[MAX_QPATH];
3148         FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3149         strlcat (mapfilename, ".map", sizeof (mapfilename));
3150         maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3151         if (!maptext)
3152                 return;
3153         text = maptext;
3154         if (!COM_ParseToken_Simple(&data, false, false, true))
3155                 return; // error
3156         submodel = 0;
3157         for (;;)
3158         {
3159                 if (!COM_ParseToken_Simple(&data, false, false, true))
3160                         break;
3161                 if (com_token[0] != '{')
3162                         return; // error
3163                 // entity
3164                 firstbrush = true;
3165                 numbrushes = 0;
3166                 maxbrushes = 256;
3167                 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3168                 for (;;)
3169                 {
3170                         if (!COM_ParseToken_Simple(&data, false, false, true))
3171                                 return; // error
3172                         if (com_token[0] == '}')
3173                                 break; // end of entity
3174                         if (com_token[0] == '{')
3175                         {
3176                                 // brush
3177                                 if (firstbrush)
3178                                 {
3179                                         if (submodel)
3180                                         {
3181                                                 if (submodel > loadmodel->brush.numsubmodels)
3182                                                 {
3183                                                         Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3184                                                         model = NULL;
3185                                                 }
3186                                                 else
3187                                                         model = loadmodel->brush.submodels[submodel];
3188                                         }
3189                                         else
3190                                                 model = loadmodel;
3191                                 }
3192                                 for (;;)
3193                                 {
3194                                         if (!COM_ParseToken_Simple(&data, false, false, true))
3195                                                 return; // error
3196                                         if (com_token[0] == '}')
3197                                                 break; // end of brush
3198                                         // each brush face should be this format:
3199                                         // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3200                                         // FIXME: support hl .map format
3201                                         for (pointnum = 0;pointnum < 3;pointnum++)
3202                                         {
3203                                                 COM_ParseToken_Simple(&data, false, false, true);
3204                                                 for (componentnum = 0;componentnum < 3;componentnum++)
3205                                                 {
3206                                                         COM_ParseToken_Simple(&data, false, false, true);
3207                                                         point[pointnum][componentnum] = atof(com_token);
3208                                                 }
3209                                                 COM_ParseToken_Simple(&data, false, false, true);
3210                                         }
3211                                         COM_ParseToken_Simple(&data, false, false, true);
3212                                         strlcpy(facetexture, com_token, sizeof(facetexture));
3213                                         COM_ParseToken_Simple(&data, false, false, true);
3214                                         //scroll_s = atof(com_token);
3215                                         COM_ParseToken_Simple(&data, false, false, true);
3216                                         //scroll_t = atof(com_token);
3217                                         COM_ParseToken_Simple(&data, false, false, true);
3218                                         //rotate = atof(com_token);
3219                                         COM_ParseToken_Simple(&data, false, false, true);
3220                                         //scale_s = atof(com_token);
3221                                         COM_ParseToken_Simple(&data, false, false, true);
3222                                         //scale_t = atof(com_token);
3223                                         TriangleNormal(point[0], point[1], point[2], planenormal);
3224                                         VectorNormalizeDouble(planenormal);
3225                                         planedist = DotProduct(point[0], planenormal);
3226                                         //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3227                                 }
3228                                 continue;
3229                         }
3230                 }
3231         }
3232 #endif
3233 }
3234
3235
3236 #define MAX_PORTALPOINTS 64
3237
3238 typedef struct portal_s
3239 {
3240         mplane_t plane;
3241         mnode_t *nodes[2];              // [0] = front side of plane
3242         struct portal_s *next[2];
3243         int numpoints;
3244         double points[3*MAX_PORTALPOINTS];
3245         struct portal_s *chain; // all portals are linked into a list
3246 }
3247 portal_t;
3248
3249 static memexpandablearray_t portalarray;
3250
3251 static void Mod_Q1BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3252 {
3253         // process only nodes (leafs already had their box calculated)
3254         if (!node->plane)
3255                 return;
3256
3257         // calculate children first
3258         Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[0]);
3259         Mod_Q1BSP_RecursiveRecalcNodeBBox(node->children[1]);
3260
3261         // make combined bounding box from children
3262         node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3263         node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3264         node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3265         node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3266         node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3267         node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3268 }
3269
3270 static void Mod_Q1BSP_FinalizePortals(void)
3271 {
3272         int i, j, numportals, numpoints, portalindex, portalrange = Mem_ExpandableArray_IndexRange(&portalarray);
3273         portal_t *p;
3274         mportal_t *portal;
3275         mvertex_t *point;
3276         mleaf_t *leaf, *endleaf;
3277
3278         // tally up portal and point counts and recalculate bounding boxes for all
3279         // leafs (because qbsp is very sloppy)
3280         leaf = loadmodel->brush.data_leafs;
3281         endleaf = leaf + loadmodel->brush.num_leafs;
3282         if (mod_recalculatenodeboxes.integer)
3283         {
3284                 for (;leaf < endleaf;leaf++)
3285                 {
3286                         VectorSet(leaf->mins,  2000000000,  2000000000,  2000000000);
3287                         VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3288                 }
3289         }
3290         numportals = 0;
3291         numpoints = 0;
3292         for (portalindex = 0;portalindex < portalrange;portalindex++)
3293         {
3294                 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3295                 if (!p)
3296                         continue;
3297                 // note: this check must match the one below or it will usually corrupt memory
3298                 // the nodes[0] != nodes[1] check is because leaf 0 is the shared solid leaf, it can have many portals inside with leaf 0 on both sides
3299                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3300                 {
3301                         numportals += 2;
3302                         numpoints += p->numpoints * 2;
3303                 }
3304         }
3305         loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3306         loadmodel->brush.num_portals = numportals;
3307         loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3308         loadmodel->brush.num_portalpoints = numpoints;
3309         // clear all leaf portal chains
3310         for (i = 0;i < loadmodel->brush.num_leafs;i++)
3311                 loadmodel->brush.data_leafs[i].portals = NULL;
3312         // process all portals in the global portal chain, while freeing them
3313         portal = loadmodel->brush.data_portals;
3314         point = loadmodel->brush.data_portalpoints;
3315         for (portalindex = 0;portalindex < portalrange;portalindex++)
3316         {
3317                 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3318                 if (!p)
3319                         continue;
3320                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3321                 {
3322                         // note: this check must match the one above or it will usually corrupt memory
3323                         // the nodes[0] != nodes[1] check is because leaf 0 is the shared solid leaf, it can have many portals inside with leaf 0 on both sides
3324                         if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3325                         {
3326                                 // first make the back to front portal(forward portal)
3327                                 portal->points = point;
3328                                 portal->numpoints = p->numpoints;
3329                                 portal->plane.dist = p->plane.dist;
3330                                 VectorCopy(p->plane.normal, portal->plane.normal);
3331                                 portal->here = (mleaf_t *)p->nodes[1];
3332                                 portal->past = (mleaf_t *)p->nodes[0];
3333                                 // copy points
3334                                 for (j = 0;j < portal->numpoints;j++)
3335                                 {
3336                                         VectorCopy(p->points + j*3, point->position);
3337                                         point++;
3338                                 }
3339                                 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3340                                 PlaneClassify(&portal->plane);
3341
3342                                 // link into leaf's portal chain
3343                                 portal->next = portal->here->portals;
3344                                 portal->here->portals = portal;
3345
3346                                 // advance to next portal
3347                                 portal++;
3348
3349                                 // then make the front to back portal(backward portal)
3350                                 portal->points = point;
3351                                 portal->numpoints = p->numpoints;
3352                                 portal->plane.dist = -p->plane.dist;
3353                                 VectorNegate(p->plane.normal, portal->plane.normal);
3354                                 portal->here = (mleaf_t *)p->nodes[0];
3355                                 portal->past = (mleaf_t *)p->nodes[1];
3356                                 // copy points
3357                                 for (j = portal->numpoints - 1;j >= 0;j--)
3358                                 {
3359                                         VectorCopy(p->points + j*3, point->position);
3360                                         point++;
3361                                 }
3362                                 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3363                                 PlaneClassify(&portal->plane);
3364
3365                                 // link into leaf's portal chain
3366                                 portal->next = portal->here->portals;
3367                                 portal->here->portals = portal;
3368
3369                                 // advance to next portal
3370                                 portal++;
3371                         }
3372                         // add the portal's polygon points to the leaf bounding boxes
3373                         if (mod_recalculatenodeboxes.integer)
3374                         {
3375                                 for (i = 0;i < 2;i++)
3376                                 {
3377                                         leaf = (mleaf_t *)p->nodes[i];
3378                                         for (j = 0;j < p->numpoints;j++)
3379                                         {
3380                                                 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3381                                                 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3382                                                 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3383                                                 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3384                                                 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3385                                                 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3386                                         }
3387                                 }
3388                         }
3389                 }
3390         }
3391         // now recalculate the node bounding boxes from the leafs
3392         if (mod_recalculatenodeboxes.integer)
3393                 Mod_Q1BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3394 }
3395
3396 /*
3397 =============
3398 AddPortalToNodes
3399 =============
3400 */
3401 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3402 {
3403         if (!front)
3404                 Host_Error("AddPortalToNodes: NULL front node");
3405         if (!back)
3406                 Host_Error("AddPortalToNodes: NULL back node");
3407         if (p->nodes[0] || p->nodes[1])
3408                 Host_Error("AddPortalToNodes: already included");
3409         // note: front == back is handled gracefully, because leaf 0 is the shared solid leaf, it can often have portals with the same leaf on both sides
3410
3411         p->nodes[0] = front;
3412         p->next[0] = (portal_t *)front->portals;
3413         front->portals = (mportal_t *)p;
3414
3415         p->nodes[1] = back;
3416         p->next[1] = (portal_t *)back->portals;
3417         back->portals = (mportal_t *)p;
3418 }
3419
3420 /*
3421 =============
3422 RemovePortalFromNode
3423 =============
3424 */
3425 static void RemovePortalFromNodes(portal_t *portal)
3426 {
3427         int i;
3428         mnode_t *node;
3429         void **portalpointer;
3430         portal_t *t;
3431         for (i = 0;i < 2;i++)
3432         {
3433                 node = portal->nodes[i];
3434
3435                 portalpointer = (void **) &node->portals;
3436                 while (1)
3437                 {
3438                         t = (portal_t *)*portalpointer;
3439                         if (!t)
3440                                 Host_Error("RemovePortalFromNodes: portal not in leaf");
3441
3442                         if (t == portal)
3443                         {
3444                                 if (portal->nodes[0] == node)
3445                                 {
3446                                         *portalpointer = portal->next[0];
3447                                         portal->nodes[0] = NULL;
3448                                 }
3449                                 else if (portal->nodes[1] == node)
3450                                 {
3451                                         *portalpointer = portal->next[1];
3452                                         portal->nodes[1] = NULL;
3453                                 }
3454                                 else
3455                                         Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3456                                 break;
3457                         }
3458
3459                         if (t->nodes[0] == node)
3460                                 portalpointer = (void **) &t->next[0];
3461                         else if (t->nodes[1] == node)
3462                                 portalpointer = (void **) &t->next[1];
3463                         else
3464                                 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3465                 }
3466         }
3467 }
3468
3469 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3470 static double *portalpointsbuffer;
3471 static int portalpointsbufferoffset;
3472 static int portalpointsbuffersize;
3473 static void Mod_Q1BSP_RecursiveNodePortals(mnode_t *node)
3474 {
3475         int i, side;
3476         mnode_t *front, *back, *other_node;
3477         mplane_t clipplane, *plane;
3478         portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3479         int numfrontpoints, numbackpoints;
3480         double *frontpoints, *backpoints;
3481
3482         // if a leaf, we're done
3483         if (!node->plane)
3484                 return;
3485
3486         // get some space for our clipping operations to use
3487         if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3488         {
3489                 portalpointsbuffersize = portalpointsbufferoffset * 2;
3490                 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3491         }
3492         frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3493         portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3494         backpoints = portalpointsbuffer + portalpointsbufferoffset;
3495         portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3496
3497         plane = node->plane;
3498
3499         front = node->children[0];
3500         back = node->children[1];
3501         if (front == back)
3502                 Host_Error("Mod_Q1BSP_RecursiveNodePortals: corrupt node hierarchy");
3503
3504         // create the new portal by generating a polygon for the node plane,
3505         // and clipping it by all of the other portals(which came from nodes above this one)
3506         nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3507         nodeportal->plane = *plane;
3508
3509         // TODO: calculate node bounding boxes during recursion and calculate a maximum plane size accordingly to improve precision (as most maps do not need 1 billion unit plane polygons)
3510         PolygonD_QuadForPlane(nodeportal->points, nodeportal->plane.normal[0], nodeportal->plane.normal[1], nodeportal->plane.normal[2], nodeportal->plane.dist, 1024.0*1024.0*1024.0);
3511         nodeportal->numpoints = 4;
3512         // side = 0;    // shut up compiler warning -> should be no longer needed, Host_Error is declared noreturn now
3513         for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3514         {
3515                 clipplane = portal->plane;
3516                 if (portal->nodes[0] == portal->nodes[1])
3517                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3518                 if (portal->nodes[0] == node)
3519                         side = 0;
3520                 else if (portal->nodes[1] == node)
3521                 {
3522                         clipplane.dist = -clipplane.dist;
3523                         VectorNegate(clipplane.normal, clipplane.normal);
3524                         side = 1;
3525                 }
3526                 else
3527                 {
3528                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3529                         side = 0; // hush warning
3530                 }
3531
3532                 for (i = 0;i < nodeportal->numpoints*3;i++)
3533                         frontpoints[i] = nodeportal->points[i];
3534                 PolygonD_Divide(nodeportal->numpoints, frontpoints, clipplane.normal[0], clipplane.normal[1], clipplane.normal[2], clipplane.dist, PORTAL_DIST_EPSILON, MAX_PORTALPOINTS, nodeportal->points, &nodeportal->numpoints, 0, NULL, NULL, NULL);
3535                 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3536                         break;
3537         }
3538
3539         if (nodeportal->numpoints < 3)
3540         {
3541                 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3542                 nodeportal->numpoints = 0;
3543         }
3544         else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3545         {
3546                 Con_Print("Mod_Q1BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3547                 nodeportal->numpoints = 0;
3548         }
3549
3550         AddPortalToNodes(nodeportal, front, back);
3551
3552         // split the portals of this node along this node's plane and assign them to the children of this node
3553         // (migrating the portals downward through the tree)
3554         for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3555         {
3556                 if (portal->nodes[0] == portal->nodes[1])
3557                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3558                 if (portal->nodes[0] == node)
3559                         side = 0;
3560                 else if (portal->nodes[1] == node)
3561                         side = 1;
3562                 else
3563                 {
3564                         Host_Error("Mod_Q1BSP_RecursiveNodePortals: mislinked portal");
3565                         side = 0; // hush warning
3566                 }
3567                 nextportal = portal->next[side];
3568                 if (!portal->numpoints)
3569                         continue;
3570
3571                 other_node = portal->nodes[!side];
3572                 RemovePortalFromNodes(portal);
3573
3574                 // cut the portal into two portals, one on each side of the node plane
3575                 PolygonD_Divide(portal->numpoints, portal->points, plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, PORTAL_DIST_EPSILON, MAX_PORTALPOINTS, frontpoints, &numfrontpoints, MAX_PORTALPOINTS, backpoints, &numbackpoints, NULL);
3576
3577                 if (!numfrontpoints)
3578                 {
3579                         if (side == 0)
3580                                 AddPortalToNodes(portal, back, other_node);
3581                         else
3582                                 AddPortalToNodes(portal, other_node, back);
3583                         continue;
3584                 }
3585                 if (!numbackpoints)
3586                 {
3587                         if (side == 0)
3588                                 AddPortalToNodes(portal, front, other_node);
3589                         else
3590                                 AddPortalToNodes(portal, other_node, front);
3591                         continue;
3592                 }
3593
3594                 // the portal is split
3595                 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3596                 temp = splitportal->chain;
3597                 *splitportal = *portal;
3598                 splitportal->chain = temp;
3599                 for (i = 0;i < numbackpoints*3;i++)
3600                         splitportal->points[i] = backpoints[i];
3601                 splitportal->numpoints = numbackpoints;
3602                 for (i = 0;i < numfrontpoints*3;i++)
3603                         portal->points[i] = frontpoints[i];
3604                 portal->numpoints = numfrontpoints;
3605
3606                 if (side == 0)
3607                 {
3608                         AddPortalToNodes(portal, front, other_node);
3609                         AddPortalToNodes(splitportal, back, other_node);
3610                 }
3611                 else
3612                 {
3613                         AddPortalToNodes(portal, other_node, front);
3614                         AddPortalToNodes(splitportal, other_node, back);
3615                 }
3616         }
3617
3618         Mod_Q1BSP_RecursiveNodePortals(front);
3619         Mod_Q1BSP_RecursiveNodePortals(back);
3620
3621         portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3622 }
3623
3624 static void Mod_Q1BSP_MakePortals(void)
3625 {
3626         Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3627         portalpointsbufferoffset = 0;
3628         portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3629         portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3630         Mod_Q1BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3631         Mem_Free(portalpointsbuffer);
3632         portalpointsbuffer = NULL;
3633         portalpointsbufferoffset = 0;
3634         portalpointsbuffersize = 0;
3635         Mod_Q1BSP_FinalizePortals();
3636         Mem_ExpandableArray_FreeArray(&portalarray);
3637 }
3638
3639 //Returns PVS data for a given point
3640 //(note: can return NULL)
3641 static unsigned char *Mod_Q1BSP_GetPVS(dp_model_t *model, const vec3_t p)
3642 {
3643         mnode_t *node;
3644         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3645         while (node->plane)
3646                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3647         if (((mleaf_t *)node)->clusterindex >= 0)
3648                 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3649         else
3650                 return NULL;
3651 }
3652
3653 static void Mod_Q1BSP_FatPVS_RecursiveBSPNode(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbytes, mnode_t *node)
3654 {
3655         while (node->plane)
3656         {
3657                 float d = PlaneDiff(org, node->plane);
3658                 if (d > radius)
3659                         node = node->children[0];
3660                 else if (d < -radius)
3661                         node = node->children[1];
3662                 else
3663                 {
3664                         // go down both sides
3665                         Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3666                         node = node->children[1];
3667                 }
3668         }
3669         // if this leaf is in a cluster, accumulate the pvs bits
3670         if (((mleaf_t *)node)->clusterindex >= 0)
3671         {
3672                 int i;
3673                 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3674                 for (i = 0;i < pvsbytes;i++)
3675                         pvsbuffer[i] |= pvs[i];
3676         }
3677 }
3678
3679 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3680 //of the given point.
3681 static int Mod_Q1BSP_FatPVS(dp_model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qboolean merge)
3682 {
3683         int bytes = model->brush.num_pvsclusterbytes;
3684         bytes = min(bytes, pvsbufferlength);
3685         if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_Q1BSP_GetPVS(model, org))
3686         {
3687                 memset(pvsbuffer, 0xFF, bytes);
3688                 return bytes;
3689         }
3690         if (!merge)
3691                 memset(pvsbuffer, 0, bytes);
3692         Mod_Q1BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3693         return bytes;
3694 }
3695
3696 static void Mod_Q1BSP_RoundUpToHullSize(dp_model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3697 {
3698         vec3_t size;
3699         const hull_t *hull;
3700
3701         VectorSubtract(inmaxs, inmins, size);
3702         if (cmodel->brush.ishlbsp)
3703         {
3704                 if (size[0] < 3)
3705                         hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3706                 else if (size[0] <= 32)
3707                 {
3708                         if (size[2] < 54) // pick the nearest of 36 or 72
3709                                 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3710                         else
3711                                 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3712                 }
3713                 else
3714                         hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3715         }
3716         else
3717         {
3718                 if (size[0] < 3)
3719                         hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3720                 else if (size[0] <= 32)
3721                         hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3722                 else
3723                         hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3724         }
3725         VectorCopy(inmins, outmins);
3726         VectorAdd(inmins, hull->clip_size, outmaxs);
3727 }
3728
3729 static int Mod_Q1BSP_CreateShadowMesh(dp_model_t *mod)
3730 {
3731         int j;
3732         int numshadowmeshtriangles = 0;
3733         msurface_t *surface;
3734         if (cls.state == ca_dedicated)
3735                 return 0;
3736         // make a single combined shadow mesh to allow optimized shadow volume creation
3737
3738         for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3739         {
3740                 surface->num_firstshadowmeshtriangle = numshadowmeshtriangles;
3741                 numshadowmeshtriangles += surface->num_triangles;
3742         }
3743         mod->brush.shadowmesh = Mod_ShadowMesh_Begin(mod->mempool, numshadowmeshtriangles * 3, numshadowmeshtriangles, NULL, NULL, NULL, false, false, true);
3744         for (j = 0, surface = mod->data_surfaces;j < mod->num_surfaces;j++, surface++)
3745                 if (surface->num_triangles > 0)
3746                         Mod_ShadowMesh_AddMesh(mod->mempool, mod->brush.shadowmesh, NULL, NULL, NULL, mod->surfmesh.data_vertex3f, NULL, NULL, NULL, NULL, surface->num_triangles, (mod->surfmesh.data_element3i + 3 * surface->num_firsttriangle));
3747         mod->brush.shadowmesh = Mod_ShadowMesh_Finish(mod->mempool, mod->brush.shadowmesh, false, r_enableshadowvolumes.integer != 0, false);
3748         if (mod->brush.shadowmesh && mod->brush.shadowmesh->neighbor3i)
3749                 Mod_BuildTriangleNeighbors(mod->brush.shadowmesh->neighbor3i, mod->brush.shadowmesh->element3i, mod->brush.shadowmesh->numtriangles);
3750
3751         return numshadowmeshtriangles;
3752 }
3753
3754 void Mod_CollisionBIH_TraceLineAgainstSurfaces(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask);
3755
3756 void Mod_Q1BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
3757 {
3758         int i, j, k;
3759         sizebuf_t lumpsb[HEADER_LUMPS];
3760         mmodel_t *bm;
3761         float dist, modelyawradius, modelradius;
3762         msurface_t *surface;
3763         hullinfo_t hullinfo;
3764         int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3765         model_brush_lightstyleinfo_t styleinfo[256];
3766         unsigned char *datapointer;
3767         sizebuf_t sb;
3768
3769         MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3770
3771         mod->type = mod_brushq1;
3772
3773         mod->brush.isbsp2 = false;
3774         mod->brush.ishlbsp = false;
3775         i = MSG_ReadLittleLong(&sb);
3776         switch(i)
3777         {
3778         case BSPVERSION:
3779                 mod->modeldatatypestring = "Q1BSP";
3780                 break;
3781         case 30:
3782                 mod->brush.ishlbsp = true;
3783                 mod->modeldatatypestring = "HLBSP";
3784                 break;
3785         case ('2' + 'P' * 256 + 'S' * 65536 + 'B' * 16777216):
3786                 mod->brush.isbsp2 = true;
3787                 mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3788                 mod->modeldatatypestring = "Q1BSP2rmqe";
3789                 break;
3790         case ('B' + 'S' * 256 + 'P' * 65536 + '2' * 16777216):
3791                 mod->brush.isbsp2 = true;
3792                 mod->modeldatatypestring = "Q1BSP2";
3793                 break;
3794         default:
3795                 mod->modeldatatypestring = "Unknown BSP";
3796                 Host_Error("Mod_Q1BSP_Load: %s has wrong version number %i: supported versions are 29 (Quake), 30 (Half-Life), \"BSP2\" or \"2PSB\" (rmqe)", mod->name, i);
3797                 return;
3798         }
3799
3800 // fill in hull info
3801         VectorClear (hullinfo.hullsizes[0][0]);
3802         VectorClear (hullinfo.hullsizes[0][1]);
3803         if (mod->brush.ishlbsp)
3804         {
3805                 hullinfo.filehulls = 4;
3806                 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3807                 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3808                 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3809                 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3810                 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3811                 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3812         }
3813         else
3814         {
3815                 hullinfo.filehulls = 4;
3816                 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3817                 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3818                 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3819                 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3820         }
3821
3822 // read lumps
3823         for (i = 0; i < HEADER_LUMPS; i++)
3824         {
3825                 int offset = MSG_ReadLittleLong(&sb);
3826                 int size = MSG_ReadLittleLong(&sb);
3827                 if (offset < 0 || offset + size > sb.cursize)
3828                         Host_Error("Mod_Q1BSP_Load: %s has invalid lump %i (offset %i, size %i, file size %i)\n", mod->name, i, offset, size, (int)sb.cursize);
3829                 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3830         }
3831
3832         mod->soundfromcenter = true;
3833         mod->TraceBox = Mod_Q1BSP_TraceBox;
3834         mod->TraceLine = Mod_Q1BSP_TraceLine;
3835         mod->TracePoint = Mod_Q1BSP_TracePoint;
3836         mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3837         mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3838         mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3839         mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3840         mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3841         mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
3842         mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
3843         mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
3844         mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
3845         mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
3846         mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
3847         mod->brush.LightPoint = Mod_Q1BSP_LightPoint;
3848         mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
3849         mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3850         mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3851         mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
3852         mod->Draw = R_Q1BSP_Draw;
3853         mod->DrawDepth = R_Q1BSP_DrawDepth;
3854         mod->DrawDebug = R_Q1BSP_DrawDebug;
3855         mod->DrawPrepass = R_Q1BSP_DrawPrepass;
3856         mod->GetLightInfo = R_Q1BSP_GetLightInfo;
3857         mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
3858         mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
3859         mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
3860         mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
3861         mod->DrawLight = R_Q1BSP_DrawLight;
3862
3863 // load into heap
3864
3865         mod->brush.qw_md4sum = 0;
3866         mod->brush.qw_md4sum2 = 0;
3867         for (i = 0;i < HEADER_LUMPS;i++)
3868         {
3869                 int temp;
3870                 if (i == LUMP_ENTITIES)
3871                         continue;
3872                 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3873                 mod->brush.qw_md4sum ^= LittleLong(temp);
3874                 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3875                         continue;
3876                 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3877         }
3878
3879         Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3880         Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3881         Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3882         Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3883         Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3884         Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3885         Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3886         Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3887         Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3888         Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3889         Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3890         // load submodels before leafs because they contain the number of vis leafs
3891         Mod_Q1BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3892         Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3893         Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3894         Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3895
3896         for (i = 0; i < HEADER_LUMPS; i++)
3897                 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
3898                         Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
3899
3900         // check if the map supports transparent water rendering
3901         loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
3902
3903         if (mod->brushq1.data_compressedpvs)
3904                 Mem_Free(mod->brushq1.data_compressedpvs);
3905         mod->brushq1.data_compressedpvs = NULL;
3906         mod->brushq1.num_compressedpvs = 0;
3907
3908         Mod_Q1BSP_MakeHull0();
3909         if (mod_bsp_portalize.integer)
3910                 Mod_Q1BSP_MakePortals();
3911
3912         mod->numframes = 2;             // regular and alternate animation
3913         mod->numskins = 1;
3914
3915         // make a single combined shadow mesh to allow optimized shadow volume creation
3916         Mod_Q1BSP_CreateShadowMesh(loadmodel);
3917
3918         if (loadmodel->brush.numsubmodels)
3919                 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
3920
3921         // LordHavoc: to clear the fog around the original quake submodel code, I
3922         // will explain:
3923         // first of all, some background info on the submodels:
3924         // model 0 is the map model (the world, named maps/e1m1.bsp for example)
3925         // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
3926         // now the weird for loop itself:
3927         // the loop functions in an odd way, on each iteration it sets up the
3928         // current 'mod' model (which despite the confusing code IS the model of
3929         // the number i), at the end of the loop it duplicates the model to become
3930         // the next submodel, and loops back to set up the new submodel.
3931
3932         // LordHavoc: now the explanation of my sane way (which works identically):
3933         // set up the world model, then on each submodel copy from the world model
3934         // and set up the submodel with the respective model info.
3935         totalstylesurfaces = 0;
3936         totalstyles = 0;
3937         for (i = 0;i < mod->brush.numsubmodels;i++)
3938         {
3939                 memset(stylecounts, 0, sizeof(stylecounts));
3940                 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
3941                 {
3942                         surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
3943                         for (j = 0;j < MAXLIGHTMAPS;j++)
3944                                 stylecounts[surface->lightmapinfo->styles[j]]++;
3945                 }
3946                 for (k = 0;k < 255;k++)
3947                 {
3948                         totalstyles++;
3949                         if (stylecounts[k])
3950                                 totalstylesurfaces += stylecounts[k];
3951                 }
3952         }
3953         datapointer = (unsigned char *)Mem_Alloc(mod->mempool, mod->num_surfaces * sizeof(int) + totalstyles * sizeof(model_brush_lightstyleinfo_t) + totalstylesurfaces * sizeof(int *));
3954         for (i = 0;i < mod->brush.numsubmodels;i++)
3955         {
3956                 // LordHavoc: this code was originally at the end of this loop, but
3957                 // has been transformed to something more readable at the start here.
3958
3959                 if (i > 0)
3960                 {
3961                         char name[10];
3962                         // duplicate the basic information
3963                         dpsnprintf(name, sizeof(name), "*%i", i);
3964                         mod = Mod_FindName(name, loadmodel->name);
3965                         // copy the base model to this one
3966                         *mod = *loadmodel;
3967                         // rename the clone back to its proper name
3968                         strlcpy(mod->name, name, sizeof(mod->name));
3969                         mod->brush.parentmodel = loadmodel;
3970                         // textures and memory belong to the main model
3971                         mod->texturepool = NULL;
3972                         mod->mempool = NULL;
3973                         mod->brush.GetPVS = NULL;
3974                         mod->brush.FatPVS = NULL;
3975                         mod->brush.BoxTouchingPVS = NULL;
3976                         mod->brush.BoxTouchingLeafPVS = NULL;
3977                         mod->brush.BoxTouchingVisibleLeafs = NULL;
3978                         mod->brush.FindBoxClusters = NULL;
3979                         mod->brush.LightPoint = NULL;
3980                         mod->brush.AmbientSoundLevelsForPoint = NULL;
3981                 }
3982
3983                 mod->brush.submodel = i;
3984
3985                 if (loadmodel->brush.submodels)
3986                         loadmodel->brush.submodels[i] = mod;
3987
3988                 bm = &mod->brushq1.submodels[i];
3989
3990                 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
3991                 for (j=1 ; j<MAX_MAP_HULLS ; j++)
3992                 {
3993                         mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
3994                         mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
3995                 }
3996
3997                 mod->firstmodelsurface = bm->firstface;
3998                 mod->nummodelsurfaces = bm->numfaces;
3999
4000                 // set node/leaf parents for this submodel
4001                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4002
4003                 // make the model surface list (used by shadowing/lighting)
4004                 mod->sortedmodelsurfaces = (int *)datapointer;datapointer += mod->nummodelsurfaces * sizeof(int);
4005                 Mod_MakeSortedSurfaces(mod);
4006
4007                 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4008                 // (previously this code measured the radius of the vertices of surfaces in the submodel, but that broke submodels that contain only CLIP brushes, which do not produce surfaces)
4009                 VectorCopy(bm->mins, mod->normalmins);
4010                 VectorCopy(bm->maxs, mod->normalmaxs);
4011                 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4012                 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4013                 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4014                 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4015                 modelradius = modelyawradius + modelradius * modelradius;
4016                 modelyawradius = sqrt(modelyawradius);
4017                 modelradius = sqrt(modelradius);
4018                 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4019                 mod->yawmins[2] = mod->normalmins[2];
4020                 mod->yawmaxs[0] = mod->yawmaxs[1] =  modelyawradius;
4021                 mod->yawmaxs[2] = mod->normalmaxs[2];
4022                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4023                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] =  modelradius;
4024                 mod->radius = modelradius;
4025                 mod->radius2 = modelradius * modelradius;
4026
4027                 // this gets altered below if sky or water is used
4028                 mod->DrawSky = NULL;
4029                 mod->DrawAddWaterPlanes = NULL;
4030
4031                 // scan surfaces for sky and water and flag the submodel as possessing these features or not
4032                 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
4033                 if (mod->nummodelsurfaces)
4034                 {
4035                         for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4036                                 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
4037                                         break;
4038                         if (j < mod->nummodelsurfaces)
4039                                 mod->DrawSky = R_Q1BSP_DrawSky;
4040
4041                         for (j = 0, surface = &mod->data_surfaces[mod->firstmodelsurface];j < mod->nummodelsurfaces;j++, surface++)
4042                                 if (surface->texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
4043                                         break;
4044                         if (j < mod->nummodelsurfaces)
4045                                 mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
4046
4047                         // build lightstyle update chains
4048                         // (used to rapidly mark lightmapupdateflags on many surfaces
4049                         // when d_lightstylevalue changes)
4050                         memset(stylecounts, 0, sizeof(stylecounts));
4051                         for (k = 0;k < mod->nummodelsurfaces;k++)
4052                         {
4053                                 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4054                                 for (j = 0;j < MAXLIGHTMAPS;j++)
4055                                         stylecounts[surface->lightmapinfo->styles[j]]++;
4056                         }
4057                         mod->brushq1.num_lightstyles = 0;
4058                         for (k = 0;k < 255;k++)
4059                         {
4060                                 if (stylecounts[k])
4061                                 {
4062                                         styleinfo[mod->brushq1.num_lightstyles].style = k;
4063                                         styleinfo[mod->brushq1.num_lightstyles].value = 0;
4064                                         styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4065                                         styleinfo[mod->brushq1.num_lightstyles].surfacelist = (int *)datapointer;datapointer += stylecounts[k] * sizeof(int);
4066                                         remapstyles[k] = mod->brushq1.num_lightstyles;
4067                                         mod->brushq1.num_lightstyles++;
4068                                 }
4069                         }
4070                         for (k = 0;k < mod->nummodelsurfaces;k++)
4071                         {
4072                                 surface = mod->data_surfaces + mod->firstmodelsurface + k;
4073                                 for (j = 0;j < MAXLIGHTMAPS;j++)
4074                                 {
4075                                         if (surface->lightmapinfo->styles[j] != 255)
4076                                         {
4077                                                 int r = remapstyles[surface->lightmapinfo->styles[j]];
4078                                                 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = mod->firstmodelsurface + k;
4079                                         }
4080                                 }
4081                         }
4082                         mod->brushq1.data_lightstyleinfo = (model_brush_lightstyleinfo_t *)datapointer;datapointer += mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t);
4083                         memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4084                 }
4085                 else
4086                 {
4087                         // LordHavoc: empty submodel(lacrima.bsp has such a glitch)
4088                         Con_Printf("warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4089                 }
4090                 //mod->brushq1.num_visleafs = bm->visleafs;
4091
4092                 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4093                 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4094
4095                 if (mod_q1bsp_polygoncollisions.integer)
4096                 {
4097                         mod->collision_bih = mod->render_bih;
4098                         // point traces and contents checks still use the bsp tree
4099                         mod->TraceLine = Mod_CollisionBIH_TraceLine;
4100                         mod->TraceBox = Mod_CollisionBIH_TraceBox;
4101                         mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4102                         mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4103                 }
4104
4105                 // generate VBOs and other shared data before cloning submodels
4106                 if (i == 0)
4107                 {
4108                         Mod_BuildVBOs();
4109                         Mod_Q1BSP_LoadMapBrushes();
4110                         //Mod_Q1BSP_ProcessLightList();
4111                 }
4112         }
4113
4114         Con_DPrintf("Stats for q1bsp model \"%s\": %i faces, %i nodes, %i leafs, %i visleafs, %i visleafportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
4115 }
4116
4117 static void Mod_Q2BSP_LoadEntities(lump_t *l)
4118 {
4119 }
4120
4121 static void Mod_Q2BSP_LoadPlanes(lump_t *l)
4122 {
4123 /*
4124         d_t *in;
4125         m_t *out;
4126         int i, count;
4127
4128         in = (void *)(mod_base + l->fileofs);
4129         if (l->filelen % sizeof(*in))
4130                 Host_Error("Mod_Q2BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4131         count = l->filelen / sizeof(*in);
4132         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4133
4134         loadmodel-> = out;
4135         loadmodel->num = count;
4136
4137         for (i = 0;i < count;i++, in++, out++)
4138         {
4139         }
4140 */
4141 }
4142
4143 static void Mod_Q2BSP_LoadVertices(lump_t *l)
4144 {
4145 /*
4146         d_t *in;
4147         m_t *out;
4148         int i, count;
4149
4150         in = (void *)(mod_base + l->fileofs);
4151         if (l->filelen % sizeof(*in))
4152                 Host_Error("Mod_Q2BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4153         count = l->filelen / sizeof(*in);
4154         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4155
4156         loadmodel-> = out;
4157         loadmodel->num = count;
4158
4159         for (i = 0;i < count;i++, in++, out++)
4160         {
4161         }
4162 */
4163 }
4164
4165 static void Mod_Q2BSP_LoadVisibility(lump_t *l)
4166 {
4167 /*
4168         d_t *in;
4169         m_t *out;
4170         int i, count;
4171
4172         in = (void *)(mod_base + l->fileofs);
4173         if (l->filelen % sizeof(*in))
4174                 Host_Error("Mod_Q2BSP_LoadVisibility: funny lump size in %s",loadmodel->name);
4175         count = l->filelen / sizeof(*in);
4176         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4177
4178         loadmodel-> = out;
4179         loadmodel->num = count;
4180
4181         for (i = 0;i < count;i++, in++, out++)
4182         {
4183         }
4184 */
4185 }
4186
4187 static void Mod_Q2BSP_LoadNodes(lump_t *l)
4188 {
4189 /*
4190         d_t *in;
4191         m_t *out;
4192         int i, count;
4193
4194         in = (void *)(mod_base + l->fileofs);
4195         if (l->filelen % sizeof(*in))
4196                 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4197         count = l->filelen / sizeof(*in);
4198         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4199
4200         loadmodel-> = out;
4201         loadmodel->num = count;
4202
4203         for (i = 0;i < count;i++, in++, out++)
4204         {
4205         }
4206 */
4207 }
4208
4209 static void Mod_Q2BSP_LoadTexInfo(lump_t *l)
4210 {
4211 /*
4212         d_t *in;
4213         m_t *out;
4214         int i, count;
4215
4216         in = (void *)(mod_base + l->fileofs);
4217         if (l->filelen % sizeof(*in))
4218                 Host_Error("Mod_Q2BSP_LoadTexInfo: funny lump size in %s",loadmodel->name);
4219         count = l->filelen / sizeof(*in);
4220         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4221
4222         loadmodel-> = out;
4223         loadmodel->num = count;
4224
4225         for (i = 0;i < count;i++, in++, out++)
4226         {
4227         }
4228 */
4229 }
4230
4231 static void Mod_Q2BSP_LoadFaces(lump_t *l)
4232 {
4233 /*
4234         d_t *in;
4235         m_t *out;
4236         int i, count;
4237
4238         in = (void *)(mod_base + l->fileofs);
4239         if (l->filelen % sizeof(*in))
4240                 Host_Error("Mod_Q2BSP_LoadFaces: funny lump size in %s",loadmodel->name);
4241         count = l->filelen / sizeof(*in);
4242         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4243
4244         loadmodel-> = out;
4245         loadmodel->num = count;
4246
4247         for (i = 0;i < count;i++, in++, out++)
4248         {
4249         }
4250 */
4251 }
4252
4253 static void Mod_Q2BSP_LoadLighting(lump_t *l)
4254 {
4255 /*
4256         d_t *in;
4257         m_t *out;
4258         int i, count;
4259
4260         in = (void *)(mod_base + l->fileofs);
4261         if (l->filelen % sizeof(*in))
4262                 Host_Error("Mod_Q2BSP_LoadLighting: funny lump size in %s",loadmodel->name);
4263         count = l->filelen / sizeof(*in);
4264         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4265
4266         loadmodel-> = out;
4267         loadmodel->num = count;
4268
4269         for (i = 0;i < count;i++, in++, out++)
4270         {
4271         }
4272 */
4273 }
4274
4275 static void Mod_Q2BSP_LoadLeafs(lump_t *l)
4276 {
4277 /*
4278         d_t *in;
4279         m_t *out;
4280         int i, count;
4281
4282         in = (void *)(mod_base + l->fileofs);
4283         if (l->filelen % sizeof(*in))
4284                 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4285         count = l->filelen / sizeof(*in);
4286         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4287
4288         loadmodel-> = out;
4289         loadmodel->num = count;
4290
4291         for (i = 0;i < count;i++, in++, out++)
4292         {
4293         }
4294 */
4295 }
4296
4297 static void Mod_Q2BSP_LoadLeafFaces(lump_t *l)
4298 {
4299 /*
4300         d_t *in;
4301         m_t *out;
4302         int i, count;
4303
4304         in = (void *)(mod_base + l->fileofs);
4305         if (l->filelen % sizeof(*in))
4306                 Host_Error("Mod_Q2BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
4307         count = l->filelen / sizeof(*in);
4308         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4309
4310         loadmodel-> = out;
4311         loadmodel->num = count;
4312
4313         for (i = 0;i < count;i++, in++, out++)
4314         {
4315         }
4316 */
4317 }
4318
4319 static void Mod_Q2BSP_LoadLeafBrushes(lump_t *l)
4320 {
4321 /*
4322         d_t *in;
4323         m_t *out;
4324         int i, count;
4325
4326         in = (void *)(mod_base + l->fileofs);
4327         if (l->filelen % sizeof(*in))
4328                 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4329         count = l->filelen / sizeof(*in);
4330         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4331
4332         loadmodel-> = out;
4333         loadmodel->num = count;
4334
4335         for (i = 0;i < count;i++, in++, out++)
4336         {
4337         }
4338 */
4339 }
4340
4341 static void Mod_Q2BSP_LoadEdges(lump_t *l)
4342 {
4343 /*
4344         d_t *in;
4345         m_t *out;
4346         int i, count;
4347
4348         in = (void *)(mod_base + l->fileofs);
4349         if (l->filelen % sizeof(*in))
4350                 Host_Error("Mod_Q2BSP_LoadEdges: funny lump size in %s",loadmodel->name);
4351         count = l->filelen / sizeof(*in);
4352         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4353
4354         loadmodel-> = out;
4355         loadmodel->num = count;
4356
4357         for (i = 0;i < count;i++, in++, out++)
4358         {
4359         }
4360 */
4361 }
4362
4363 static void Mod_Q2BSP_LoadSurfEdges(lump_t *l)
4364 {
4365 /*
4366         d_t *in;
4367         m_t *out;
4368         int i, count;
4369
4370         in = (void *)(mod_base + l->fileofs);
4371         if (l->filelen % sizeof(*in))
4372                 Host_Error("Mod_Q2BSP_LoadSurfEdges: funny lump size in %s",loadmodel->name);
4373         count = l->filelen / sizeof(*in);
4374         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4375
4376         loadmodel-> = out;
4377         loadmodel->num = count;
4378
4379         for (i = 0;i < count;i++, in++, out++)
4380         {
4381         }
4382 */
4383 }
4384
4385 static void Mod_Q2BSP_LoadBrushes(lump_t *l)
4386 {
4387 /*
4388         d_t *in;
4389         m_t *out;
4390         int i, count;
4391
4392         in = (void *)(mod_base + l->fileofs);
4393         if (l->filelen % sizeof(*in))
4394                 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4395         count = l->filelen / sizeof(*in);
4396         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4397
4398         loadmodel-> = out;
4399         loadmodel->num = count;
4400
4401         for (i = 0;i < count;i++, in++, out++)
4402         {
4403         }
4404 */
4405 }
4406
4407 static void Mod_Q2BSP_LoadBrushSides(lump_t *l)
4408 {
4409 /*
4410         d_t *in;
4411         m_t *out;
4412         int i, count;
4413
4414         in = (void *)(mod_base + l->fileofs);
4415         if (l->filelen % sizeof(*in))
4416                 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4417         count = l->filelen / sizeof(*in);
4418         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4419
4420         loadmodel-> = out;
4421         loadmodel->num = count;
4422
4423         for (i = 0;i < count;i++, in++, out++)
4424         {
4425         }
4426 */
4427 }
4428
4429 static void Mod_Q2BSP_LoadAreas(lump_t *l)
4430 {
4431 /*
4432         d_t *in;
4433         m_t *out;
4434         int i, count;
4435
4436         in = (void *)(mod_base + l->fileofs);
4437         if (l->filelen % sizeof(*in))
4438                 Host_Error("Mod_Q2BSP_LoadAreas: funny lump size in %s",loadmodel->name);
4439         count = l->filelen / sizeof(*in);
4440         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4441
4442         loadmodel-> = out;
4443         loadmodel->num = count;
4444
4445         for (i = 0;i < count;i++, in++, out++)
4446         {
4447         }
4448 */
4449 }
4450
4451 static void Mod_Q2BSP_LoadAreaPortals(lump_t *l)
4452 {
4453 /*
4454         d_t *in;
4455         m_t *out;
4456         int i, count;
4457
4458         in = (void *)(mod_base + l->fileofs);
4459         if (l->filelen % sizeof(*in))
4460                 Host_Error("Mod_Q2BSP_LoadAreaPortals: funny lump size in %s",loadmodel->name);
4461         count = l->filelen / sizeof(*in);
4462         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4463
4464         loadmodel-> = out;
4465         loadmodel->num = count;
4466
4467         for (i = 0;i < count;i++, in++, out++)
4468         {
4469         }
4470 */
4471 }
4472
4473 static void Mod_Q2BSP_LoadModels(lump_t *l)
4474 {
4475 /*
4476         d_t *in;
4477         m_t *out;
4478         int i, count;
4479
4480         in = (void *)(mod_base + l->fileofs);
4481         if (l->filelen % sizeof(*in))
4482                 Host_Error("Mod_Q2BSP_LoadModels: funny lump size in %s",loadmodel->name);
4483         count = l->filelen / sizeof(*in);
4484         out = Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4485
4486         loadmodel-> = out;
4487         loadmodel->num = count;
4488
4489         for (i = 0;i < count;i++, in++, out++)
4490         {
4491         }
4492 */
4493 }
4494
4495 static void Mod_Q2BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
4496 {
4497         int i;
4498         q2dheader_t *header;
4499
4500         Host_Error("Mod_Q2BSP_Load: not yet implemented");
4501
4502         mod->modeldatatypestring = "Q2BSP";
4503
4504         mod->type = mod_brushq2;
4505
4506         header = (q2dheader_t *)buffer;
4507
4508         i = LittleLong(header->version);
4509         if (i != Q2BSPVERSION)
4510                 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4511
4512         mod_base = (unsigned char *)header;
4513
4514         // swap all the lumps
4515         for (i = 0;i < (int) sizeof(*header) / 4;i++)
4516                 ((int *)header)[i] = LittleLong(((int *)header)[i]);
4517
4518         mod->brush.qw_md4sum = 0;
4519         mod->brush.qw_md4sum2 = 0;
4520         for (i = 0;i < Q2HEADER_LUMPS;i++)
4521         {
4522                 if (i == Q2LUMP_ENTITIES)
4523                         continue;
4524                 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4525                 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4526                         continue;
4527                 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
4528         }
4529
4530         Mod_Q2BSP_LoadEntities(&header->lumps[Q2LUMP_ENTITIES]);
4531         Mod_Q2BSP_LoadPlanes(&header->lumps[Q2LUMP_PLANES]);
4532         Mod_Q2BSP_LoadVertices(&header->lumps[Q2LUMP_VERTEXES]);
4533         Mod_Q2BSP_LoadVisibility(&header->lumps[Q2LUMP_VISIBILITY]);
4534         Mod_Q2BSP_LoadNodes(&header->lumps[Q2LUMP_NODES]);
4535         Mod_Q2BSP_LoadTexInfo(&header->lumps[Q2LUMP_TEXINFO]);
4536         Mod_Q2BSP_LoadFaces(&header->lumps[Q2LUMP_FACES]);
4537         Mod_Q2BSP_LoadLighting(&header->lumps[Q2LUMP_LIGHTING]);
4538         Mod_Q2BSP_LoadLeafs(&header->lumps[Q2LUMP_LEAFS]);
4539         Mod_Q2BSP_LoadLeafFaces(&header->lumps[Q2LUMP_LEAFFACES]);
4540         Mod_Q2BSP_LoadLeafBrushes(&header->lumps[Q2LUMP_LEAFBRUSHES]);
4541         Mod_Q2BSP_LoadEdges(&header->lumps[Q2LUMP_EDGES]);
4542         Mod_Q2BSP_LoadSurfEdges(&header->lumps[Q2LUMP_SURFEDGES]);
4543         Mod_Q2BSP_LoadBrushes(&header->lumps[Q2LUMP_BRUSHES]);
4544         Mod_Q2BSP_LoadBrushSides(&header->lumps[Q2LUMP_BRUSHSIDES]);
4545         Mod_Q2BSP_LoadAreas(&header->lumps[Q2LUMP_AREAS]);
4546         Mod_Q2BSP_LoadAreaPortals(&header->lumps[Q2LUMP_AREAPORTALS]);
4547         // LordHavoc: must go last because this makes the submodels
4548         Mod_Q2BSP_LoadModels(&header->lumps[Q2LUMP_MODELS]);
4549 }
4550
4551 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents);
4552 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents);
4553
4554 static void Mod_Q3BSP_LoadEntities(lump_t *l)
4555 {
4556         const char *data;
4557         char key[128], value[MAX_INPUTLINE];
4558         float v[3];
4559         loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
4560         loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
4561         loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
4562         if (!l->filelen)
4563                 return;
4564         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
4565         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
4566         loadmodel->brush.entities[l->filelen] = 0;
4567         data = loadmodel->brush.entities;
4568         // some Q3 maps override the lightgrid_cellsize with a worldspawn key
4569         // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
4570         loadmodel->brushq3.deluxemapping = false;
4571         if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
4572         {
4573                 while (1)
4574                 {
4575                         if (!COM_ParseToken_Simple(&data, false, false, true))
4576                                 break; // error
4577                         if (com_token[0] == '}')
4578                                 break; // end of worldspawn
4579                         if (com_token[0] == '_')
4580                                 strlcpy(key, com_token + 1, sizeof(key));
4581                         else
4582                                 strlcpy(key, com_token, sizeof(key));
4583                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
4584                                 key[strlen(key)-1] = 0;
4585                         if (!COM_ParseToken_Simple(&data, false, false, true))
4586                                 break; // error
4587                         strlcpy(value, com_token, sizeof(value));
4588                         if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
4589                         {
4590 #if _MSC_VER >= 1400
4591 #define sscanf sscanf_s
4592 #endif
4593 #if 0
4594                                 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
4595                                         VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4596 #else
4597                                 VectorSet(v, 64, 64, 128);
4598                                 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
4599                                         Con_Printf("Mod_Q3BSP_LoadEntities: funny gridsize \"%s\" in %s, interpreting as \"%f %f %f\" to match q3map2's parsing\n", value, loadmodel->name, v[0], v[1], v[2]);
4600                                 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
4601                                         VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
4602 #endif
4603                         }
4604                         else if (!strcmp("deluxeMaps", key))
4605                         {
4606                                 if (!strcmp(com_token, "1"))
4607                                 {
4608                                         loadmodel->brushq3.deluxemapping = true;
4609                                         loadmodel->brushq3.deluxemapping_modelspace = true;
4610                                 }
4611                                 else if (!strcmp(com_token, "2"))
4612                                 {
4613                                         loadmodel->brushq3.deluxemapping = true;
4614                                         loadmodel->brushq3.deluxemapping_modelspace = false;
4615                                 }
4616                         }
4617                 }
4618         }
4619 }
4620
4621 static void Mod_Q3BSP_LoadTextures(lump_t *l)
4622 {
4623         q3dtexture_t *in;
4624         texture_t *out;
4625         int i, count;
4626
4627         in = (q3dtexture_t *)(mod_base + l->fileofs);
4628         if (l->filelen % sizeof(*in))
4629                 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
4630         count = l->filelen / sizeof(*in);
4631         out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4632
4633         loadmodel->data_textures = out;
4634         loadmodel->num_textures = count;
4635         loadmodel->num_texturesperskin = loadmodel->num_textures;
4636
4637         for (i = 0;i < count;i++)
4638         {
4639                 strlcpy (out[i].name, in[i].name, sizeof (out[i].name));
4640                 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4641                 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4642                 Mod_LoadTextureFromQ3Shader(out + i, out[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS);
4643                 // restore the surfaceflags and supercontents
4644                 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
4645                 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(loadmodel, LittleLong(in[i].contents));
4646         }
4647 }
4648
4649 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
4650 {
4651         q3dplane_t *in;
4652         mplane_t *out;
4653         int i, count;
4654
4655         in = (q3dplane_t *)(mod_base + l->fileofs);
4656         if (l->filelen % sizeof(*in))
4657                 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
4658         count = l->filelen / sizeof(*in);
4659         out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4660
4661         loadmodel->brush.data_planes = out;
4662         loadmodel->brush.num_planes = count;
4663
4664         for (i = 0;i < count;i++, in++, out++)
4665         {
4666                 out->normal[0] = LittleFloat(in->normal[0]);
4667                 out->normal[1] = LittleFloat(in->normal[1]);
4668                 out->normal[2] = LittleFloat(in->normal[2]);
4669                 out->dist = LittleFloat(in->dist);
4670                 PlaneClassify(out);
4671         }
4672 }
4673
4674 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
4675 {
4676         q3dbrushside_t *in;
4677         q3mbrushside_t *out;
4678         int i, n, count;
4679
4680         in = (q3dbrushside_t *)(mod_base + l->fileofs);
4681         if (l->filelen % sizeof(*in))
4682                 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4683         count = l->filelen / sizeof(*in);
4684         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4685
4686         loadmodel->brush.data_brushsides = out;
4687         loadmodel->brush.num_brushsides = count;
4688
4689         for (i = 0;i < count;i++, in++, out++)
4690         {
4691                 n = LittleLong(in->planeindex);
4692                 if (n < 0 || n >= loadmodel->brush.num_planes)
4693                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4694                 out->plane = loadmodel->brush.data_planes + n;
4695                 n = LittleLong(in->textureindex);
4696                 if (n < 0 || n >= loadmodel->num_textures)
4697                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4698                 out->texture = loadmodel->data_textures + n;
4699         }
4700 }
4701
4702 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
4703 {
4704         q3dbrushside_ig_t *in;
4705         q3mbrushside_t *out;
4706         int i, n, count;
4707
4708         in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
4709         if (l->filelen % sizeof(*in))
4710                 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4711         count = l->filelen / sizeof(*in);
4712         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4713
4714         loadmodel->brush.data_brushsides = out;
4715         loadmodel->brush.num_brushsides = count;
4716
4717         for (i = 0;i < count;i++, in++, out++)
4718         {
4719                 n = LittleLong(in->planeindex);
4720                 if (n < 0 || n >= loadmodel->brush.num_planes)
4721                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4722                 out->plane = loadmodel->brush.data_planes + n;
4723                 n = LittleLong(in->textureindex);
4724                 if (n < 0 || n >= loadmodel->num_textures)
4725                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4726                 out->texture = loadmodel->data_textures + n;
4727         }
4728 }
4729
4730 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
4731 {
4732         q3dbrush_t *in;
4733         q3mbrush_t *out;
4734         int i, j, n, c, count, maxplanes, q3surfaceflags;
4735         colplanef_t *planes;
4736
4737         in = (q3dbrush_t *)(mod_base + l->fileofs);
4738         if (l->filelen % sizeof(*in))
4739                 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4740         count = l->filelen / sizeof(*in);
4741         out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4742
4743         loadmodel->brush.data_brushes = out;
4744         loadmodel->brush.num_brushes = count;
4745
4746         maxplanes = 0;
4747         planes = NULL;
4748
4749         for (i = 0;i < count;i++, in++, out++)
4750         {
4751                 n = LittleLong(in->firstbrushside);
4752                 c = LittleLong(in->numbrushsides);
4753                 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
4754                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
4755                 out->firstbrushside = loadmodel->brush.data_brushsides + n;
4756                 out->numbrushsides = c;
4757                 n = LittleLong(in->textureindex);
4758                 if (n < 0 || n >= loadmodel->num_textures)
4759                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
4760                 out->texture = loadmodel->data_textures + n;
4761
4762                 // make a list of mplane_t structs to construct a colbrush from
4763                 if (maxplanes < out->numbrushsides)
4764                 {
4765                         maxplanes = out->numbrushsides;
4766                         if (planes)
4767                                 Mem_Free(planes);
4768                         planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4769                 }
4770                 q3surfaceflags = 0;
4771                 for (j = 0;j < out->numbrushsides;j++)
4772                 {
4773                         VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4774                         planes[j].dist = out->firstbrushside[j].plane->dist;
4775                         planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4776                         planes[j].texture = out->firstbrushside[j].texture;
4777                         q3surfaceflags |= planes[j].q3surfaceflags;
4778                 }
4779                 // make the colbrush from the planes
4780                 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4781
4782                 // this whole loop can take a while (e.g. on redstarrepublic4)
4783                 CL_KeepaliveMessage(false);
4784         }
4785         if (planes)
4786                 Mem_Free(planes);
4787 }
4788
4789 static void Mod_Q3BSP_LoadEffects(lump_t *l)
4790 {
4791         q3deffect_t *in;
4792         q3deffect_t *out;
4793         int i, n, count;
4794
4795         in = (q3deffect_t *)(mod_base + l->fileofs);
4796         if (l->filelen % sizeof(*in))
4797                 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
4798         count = l->filelen / sizeof(*in);
4799         out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4800
4801         loadmodel->brushq3.data_effects = out;
4802         loadmodel->brushq3.num_effects = count;
4803
4804         for (i = 0;i < count;i++, in++, out++)
4805         {
4806                 strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
4807                 n = LittleLong(in->brushindex);
4808                 if (n >= loadmodel->brush.num_brushes)
4809                 {
4810                         Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
4811                         n = -1;
4812                 }
4813                 out->brushindex = n;
4814                 out->unknown = LittleLong(in->unknown);
4815         }
4816 }
4817
4818 static void Mod_Q3BSP_LoadVertices(lump_t *l)
4819 {
4820         q3dvertex_t *in;
4821         int i, count;
4822
4823         in = (q3dvertex_t *)(mod_base + l->fileofs);
4824         if (l->filelen % sizeof(*in))
4825                 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
4826         loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
4827         loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
4828         loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
4829         loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
4830         loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
4831         loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
4832
4833         for (i = 0;i < count;i++, in++)
4834         {
4835                 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
4836                 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
4837                 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
4838                 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
4839                 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
4840                 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
4841                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
4842                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
4843                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
4844                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
4845                 // svector/tvector are calculated later in face loading
4846                 if(mod_q3bsp_sRGBlightmaps.integer)
4847                 {
4848                         // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
4849                         // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
4850                         // working like this may be odd, but matches q3map2 -gamma 2.2
4851                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4852                         {
4853                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4854                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4855                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4856                                 // we fix the brightness consistently via lightmapscale
4857                         }
4858                         else
4859                         {
4860                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
4861                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
4862                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
4863                         }
4864                 }
4865                 else
4866                 {
4867                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
4868                         {
4869                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
4870                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
4871                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
4872                         }
4873                         else
4874                         {
4875                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
4876                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
4877                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
4878                         }
4879                 }
4880                 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
4881                 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
4882                         loadmodel->lit = true;
4883         }
4884 }
4885
4886 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
4887 {
4888         int *in;
4889         int *out;
4890         int i, count;
4891
4892         in = (int *)(mod_base + l->fileofs);
4893         if (l->filelen % sizeof(int[3]))
4894                 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
4895         count = l->filelen / sizeof(*in);
4896
4897         if(!loadmodel->brushq3.num_vertices)
4898         {
4899                 if (count)
4900                         Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
4901                 loadmodel->brushq3.num_triangles = 0;
4902                 return;
4903         }
4904
4905         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4906         loadmodel->brushq3.num_triangles = count / 3;
4907         loadmodel->brushq3.data_element3i = out;
4908
4909         for (i = 0;i < count;i++, in++, out++)
4910         {
4911                 *out = LittleLong(*in);
4912                 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
4913                 {
4914                         Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
4915                         *out = 0;
4916                 }
4917         }
4918 }
4919
4920 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
4921 {
4922         q3dlightmap_t *input_pointer;
4923         int i;
4924         int j;
4925         int k;
4926         int count;
4927         int powerx;
4928         int powery;
4929         int powerxy;
4930         int powerdxy;
4931         int endlightmap;
4932         int mergegoal;
4933         int lightmapindex;
4934         int realcount;
4935         int realindex;
4936         int mergedwidth;
4937         int mergedheight;
4938         int mergedcolumns;
4939         int mergedrows;
4940         int mergedrowsxcolumns;
4941         int size;
4942         int bytesperpixel;
4943         int rgbmap[3];
4944         unsigned char *c;
4945         unsigned char *mergedpixels;
4946         unsigned char *mergeddeluxepixels;
4947         unsigned char *mergebuf;
4948         char mapname[MAX_QPATH];
4949         qboolean external;
4950         unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
4951         char vabuf[1024];
4952
4953         // defaults for q3bsp
4954         size = 128;
4955         bytesperpixel = 3;
4956         rgbmap[0] = 2;
4957         rgbmap[1] = 1;
4958         rgbmap[2] = 0;
4959         external = false;
4960         loadmodel->brushq3.lightmapsize = 128;
4961
4962         if (cls.state == ca_dedicated)
4963                 return;
4964
4965         if(mod_q3bsp_nolightmaps.integer)
4966         {
4967                 return;
4968         }
4969         else if(l->filelen)
4970         {
4971                 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
4972                 if (developer_loading.integer)
4973                         Con_Printf("Using internal lightmaps\n");
4974                 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
4975                 if (l->filelen % sizeof(*input_pointer))
4976                         Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
4977                 count = l->filelen / sizeof(*input_pointer);
4978                 for(i = 0; i < count; ++i)
4979                         inpixels[i] = input_pointer[i].rgb;
4980         }
4981         else
4982         {
4983                 // no internal lightmaps
4984                 // try external lightmaps
4985                 if (developer_loading.integer)
4986                         Con_Printf("Using external lightmaps\n");
4987                 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
4988                 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
4989                 if(!inpixels[0])
4990                         return;
4991
4992                 // using EXTERNAL lightmaps instead
4993                 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
4994                 {
4995                         Mem_Free(inpixels[0]);
4996                         Host_Error("Mod_Q3BSP_LoadLightmaps: invalid external lightmap size in %s",loadmodel->name);
4997                 }
4998
4999                 size = image_width;
5000                 bytesperpixel = 4;
5001                 rgbmap[0] = 0;
5002                 rgbmap[1] = 1;
5003                 rgbmap[2] = 2;
5004                 external = true;
5005
5006                 for(count = 1; ; ++count)
5007                 {
5008                         inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5009                         if(!inpixels[count])
5010                                 break; // we got all of them
5011                         if(image_width != size || image_height != size)
5012                         {
5013                                 Mem_Free(inpixels[count]);
5014                                 inpixels[count] = NULL;
5015                                 Con_Printf("Mod_Q3BSP_LoadLightmaps: mismatched lightmap size in %s - external lightmap %s/lm_%04d does not match earlier ones\n", loadmodel->name, mapname, count);
5016                                 break;
5017                         }
5018                 }
5019         }
5020
5021         loadmodel->brushq3.lightmapsize = size;
5022         loadmodel->brushq3.num_originallightmaps = count;
5023
5024         // now check the surfaces to see if any of them index an odd numbered
5025         // lightmap, if so this is not a deluxemapped bsp file
5026         //
5027         // also check what lightmaps are actually used, because q3map2 sometimes
5028         // (always?) makes an unused one at the end, which
5029         // q3map2 sometimes (or always?) makes a second blank lightmap for no
5030         // reason when only one lightmap is used, which can throw off the
5031         // deluxemapping detection method, so check 2-lightmap bsp's specifically
5032         // to see if the second lightmap is blank, if so it is not deluxemapped.
5033         // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5034         // in Mod_Q3BSP_LoadEntities was failed
5035         if (!loadmodel->brushq3.deluxemapping)
5036         {
5037                 loadmodel->brushq3.deluxemapping = !(count & 1);
5038                 loadmodel->brushq3.deluxemapping_modelspace = true;
5039                 endlightmap = 0;
5040                 if (loadmodel->brushq3.deluxemapping)
5041                 {
5042                         int facecount = faceslump->filelen / sizeof(q3dface_t);
5043                         q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5044                         for (i = 0;i < facecount;i++)
5045                         {
5046                                 j = LittleLong(faces[i].lightmapindex);
5047                                 if (j >= 0)
5048                                 {
5049                                         endlightmap = max(endlightmap, j + 1);
5050                                         if ((j & 1) || j + 1 >= count)
5051                                         {
5052                                                 loadmodel->brushq3.deluxemapping = false;
5053                                                 break;
5054                                         }
5055                                 }
5056                         }
5057                 }
5058
5059                 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5060                 // reason when only one lightmap is used, which can throw off the
5061                 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5062                 // to see if the second lightmap is blank, if so it is not deluxemapped.
5063                 //
5064                 // further research has shown q3map2 sometimes creates a deluxemap and two
5065                 // blank lightmaps, which must be handled properly as well
5066                 if (endlightmap == 1 && count > 1)
5067                 {
5068                         c = inpixels[1];
5069                         for (i = 0;i < size*size;i++)
5070                         {
5071                                 if (c[bytesperpixel*i + rgbmap[0]])
5072                                         break;
5073                                 if (c[bytesperpixel*i + rgbmap[1]])
5074                                         break;
5075                                 if (c[bytesperpixel*i + rgbmap[2]])
5076                                         break;
5077                         }
5078                         if (i == size*size)
5079                         {
5080                                 // all pixels in the unused lightmap were black...
5081                                 loadmodel->brushq3.deluxemapping = false;
5082                         }
5083                 }
5084         }
5085
5086         Con_DPrintf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5087
5088         // figure out what the most reasonable merge power is within limits
5089
5090         // find the appropriate NxN dimensions to merge to, to avoid wasted space
5091         realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5092
5093         // figure out how big the merged texture has to be
5094         mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5095         mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5096         while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5097                 mergegoal /= 2;
5098         mergedwidth = mergegoal;
5099         mergedheight = mergegoal;
5100         // choose non-square size (2x1 aspect) if only half the space is used;
5101         // this really only happens when the entire set fits in one texture, if
5102         // there are multiple textures, we don't worry about shrinking the last
5103         // one to fit, because the driver prefers the same texture size on
5104         // consecutive draw calls...
5105         if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5106                 mergedheight /= 2;
5107
5108         loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5109         loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5110         while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5111                 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5112         while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5113                 loadmodel->brushq3.num_lightmapmergedheightpower++;
5114         loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5115
5116         powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5117         powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5118         powerxy = powerx+powery;
5119         powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5120
5121         mergedcolumns = 1 << powerx;
5122         mergedrows = 1 << powery;
5123         mergedrowsxcolumns = 1 << powerxy;
5124
5125         loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5126         loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5127         if (loadmodel->brushq3.deluxemapping)
5128                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5129
5130         // allocate a texture pool if we need it
5131         if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
5132                 loadmodel->texturepool = R_AllocTexturePool();
5133
5134         mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5135         mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5136         for (i = 0;i < count;i++)
5137         {
5138                 // figure out which merged lightmap texture this fits into
5139                 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5140                 lightmapindex = i >> powerdxy;
5141
5142                 // choose the destination address
5143                 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5144                 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5145                 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5146                         Con_DPrintf("copying original lightmap %i (%ix%i) to %i (at %i,%i)\n", i, size, size, lightmapindex, (realindex & (mergedcolumns-1))*size, ((realindex >> powerx) & (mergedrows-1))*size);
5147
5148                 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5149                 for (j = 0;j < size;j++)
5150                 for (k = 0;k < size;k++)
5151                 {
5152                         mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5153                         mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5154                         mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5155                         mergebuf[(j*mergedwidth+k)*4+3] = 255;
5156                 }
5157
5158                 // upload texture if this was the last tile being written to the texture
5159                 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5160                 {
5161                         if (loadmodel->brushq3.deluxemapping && (i & 1))
5162                                 loadmodel->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "deluxemap%04i", lightmapindex), mergedwidth, mergedheight, mergeddeluxepixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bspdeluxemaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5163                         else
5164                         {
5165                                 if(mod_q3bsp_sRGBlightmaps.integer)
5166                                 {
5167                                         textype_t t;
5168                                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5169                                         {
5170                                                 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5171                                                 // we fix the brightness consistently via lightmapscale
5172                                         }
5173                                         else
5174                                                 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5175                                         loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%04i", lightmapindex), mergedwidth, mergedheight, mergedpixels, t, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5176                                 }
5177                                 else
5178                                 {
5179                                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5180                                                 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5181                                         loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%04i", lightmapindex), mergedwidth, mergedheight, mergedpixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5182                                 }
5183                         }
5184                 }
5185         }
5186
5187         if (mergeddeluxepixels)
5188                 Mem_Free(mergeddeluxepixels);
5189         Mem_Free(mergedpixels);
5190         if(external)
5191         {
5192                 for(i = 0; i < count; ++i)
5193                         Mem_Free(inpixels[i]);
5194         }
5195 }
5196
5197 static void Mod_Q3BSP_BuildBBoxes(const int *element3i, int num_triangles, const float *vertex3f, float **collisionbbox6f, int *collisionstride, int stride)
5198 {
5199         int j, k, cnt, tri;
5200         float *mins, *maxs;
5201         const float *vert;
5202         *collisionstride = stride;
5203         if(stride > 0)
5204         {
5205                 cnt = (num_triangles + stride - 1) / stride;
5206                 *collisionbbox6f = (float *) Mem_Alloc(loadmodel->mempool, sizeof(float[6]) * cnt);
5207                 for(j = 0; j < cnt; ++j)
5208                 {
5209                         mins = &((*collisionbbox6f)[6 * j + 0]);
5210                         maxs = &((*collisionbbox6f)[6 * j + 3]);
5211                         for(k = 0; k < stride; ++k)
5212                         {
5213                                 tri = j * stride + k;
5214                                 if(tri >= num_triangles)
5215                                         break;
5216                                 vert = &(vertex3f[element3i[3 * tri + 0] * 3]);
5217                                 if(!k || vert[0] < mins[0]) mins[0] = vert[0];
5218                                 if(!k || vert[1] < mins[1]) mins[1] = vert[1];
5219                                 if(!k || vert[2] < mins[2]) mins[2] = vert[2];
5220                                 if(!k || vert[0] > maxs[0]) maxs[0] = vert[0];
5221                                 if(!k || vert[1] > maxs[1]) maxs[1] = vert[1];
5222                                 if(!k || vert[2] > maxs[2]) maxs[2] = vert[2];
5223                                 vert = &(vertex3f[element3i[3 * tri + 1] * 3]);
5224                                 if(vert[0] < mins[0]) mins[0] = vert[0];
5225                                 if(vert[1] < mins[1]) mins[1] = vert[1];
5226                                 if(vert[2] < mins[2]) mins[2] = vert[2];
5227                                 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5228                                 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5229                                 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5230                                 vert = &(vertex3f[element3i[3 * tri + 2] * 3]);
5231                                 if(vert[0] < mins[0]) mins[0] = vert[0];
5232                                 if(vert[1] < mins[1]) mins[1] = vert[1];
5233                                 if(vert[2] < mins[2]) mins[2] = vert[2];
5234                                 if(vert[0] > maxs[0]) maxs[0] = vert[0];
5235                                 if(vert[1] > maxs[1]) maxs[1] = vert[1];
5236                                 if(vert[2] > maxs[2]) maxs[2] = vert[2];
5237                         }
5238                 }
5239         }
5240         else
5241                 *collisionbbox6f = NULL;
5242 }
5243
5244 typedef struct patchtess_s
5245 {
5246         patchinfo_t info;
5247
5248         // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5249         int surface_id;
5250         float lodgroup[6];
5251         float *originalvertex3f;
5252 } patchtess_t;
5253
5254 #define PATCHTESS_SAME_LODGROUP(a,b) \
5255         ( \
5256                 (a).lodgroup[0] == (b).lodgroup[0] && \
5257                 (a).lodgroup[1] == (b).lodgroup[1] && \
5258                 (a).lodgroup[2] == (b).lodgroup[2] && \
5259                 (a).lodgroup[3] == (b).lodgroup[3] && \
5260                 (a).lodgroup[4] == (b).lodgroup[4] && \
5261                 (a).lodgroup[5] == (b).lodgroup[5] \
5262         )
5263
5264 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5265 {
5266         q3dface_t *in, *oldin;
5267         msurface_t *out, *oldout;
5268         int i, oldi, j, n, count, invalidelements, patchsize[2], finalwidth, finalheight, xtess, ytess, finalvertices, finaltriangles, firstvertex, firstelement, type, oldnumtriangles, oldnumtriangles2, meshvertices, meshtriangles, collisionvertices, collisiontriangles, numvertices, numtriangles, cxtess, cytess;
5269         float lightmaptcbase[2], lightmaptcscale[2];
5270         //int *originalelement3i;
5271         //int *originalneighbor3i;
5272         float *originalvertex3f;
5273         //float *originalsvector3f;
5274         //float *originaltvector3f;
5275         float *originalnormal3f;
5276         float *originalcolor4f;
5277         float *originaltexcoordtexture2f;
5278         float *originaltexcoordlightmap2f;
5279         float *surfacecollisionvertex3f;
5280         int *surfacecollisionelement3i;
5281         float *v;
5282         patchtess_t *patchtess = NULL;
5283         int patchtesscount = 0;
5284         qboolean again;
5285
5286         in = (q3dface_t *)(mod_base + l->fileofs);
5287         if (l->filelen % sizeof(*in))
5288                 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5289         count = l->filelen / sizeof(*in);
5290         out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5291
5292         loadmodel->data_surfaces = out;
5293         loadmodel->num_surfaces = count;
5294
5295         if(count > 0)
5296                 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5297
5298         i = 0;
5299         oldi = i;
5300         oldin = in;
5301         oldout = out;
5302         meshvertices = 0;
5303         meshtriangles = 0;
5304         for (;i < count;i++, in++, out++)
5305         {
5306                 // check face type first
5307                 type = LittleLong(in->type);
5308                 if (type != Q3FACETYPE_FLAT
5309                  && type != Q3FACETYPE_PATCH
5310                  && type != Q3FACETYPE_MESH
5311                  && type != Q3FACETYPE_FLARE)
5312                 {
5313                         Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5314                         continue;
5315                 }
5316
5317                 n = LittleLong(in->textureindex);
5318                 if (n < 0 || n >= loadmodel->num_textures)
5319                 {
5320                         Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5321                         continue;
5322                 }
5323                 out->texture = loadmodel->data_textures + n;
5324                 n = LittleLong(in->effectindex);
5325                 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5326                 {
5327                         if (developer_extra.integer)
5328                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5329                         n = -1;
5330                 }
5331                 if (n == -1)
5332                         out->effect = NULL;
5333                 else
5334                         out->effect = loadmodel->brushq3.data_effects + n;
5335
5336                 if (cls.state != ca_dedicated)
5337                 {
5338                         out->lightmaptexture = NULL;
5339                         out->deluxemaptexture = r_texture_blanknormalmap;
5340                         n = LittleLong(in->lightmapindex);
5341                         if (n < 0)
5342                                 n = -1;
5343                         else if (n >= loadmodel->brushq3.num_originallightmaps)
5344                         {
5345                                 if(loadmodel->brushq3.num_originallightmaps != 0)
5346                                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5347                                 n = -1;
5348                         }
5349                         else
5350                         {
5351                                 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5352                                 if (loadmodel->brushq3.deluxemapping)
5353                                         out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5354                                 loadmodel->lit = true;
5355                         }
5356                 }
5357
5358                 firstvertex = LittleLong(in->firstvertex);
5359                 numvertices = LittleLong(in->numvertices);
5360                 firstelement = LittleLong(in->firstelement);
5361                 numtriangles = LittleLong(in->numelements) / 3;
5362                 if (numtriangles * 3 != LittleLong(in->numelements))
5363                 {
5364                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): numelements %i is not a multiple of 3\n", i, out->texture->name, LittleLong(in->numelements));
5365                         continue;
5366                 }
5367                 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5368                 {
5369                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid vertex range %i : %i (%i vertices)\n", i, out->texture->name, firstvertex, firstvertex + numvertices, loadmodel->brushq3.num_vertices);
5370                         continue;
5371                 }
5372                 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5373                 {
5374                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid element range %i : %i (%i elements)\n", i, out->texture->name, firstelement, firstelement + numtriangles * 3, loadmodel->brushq3.num_triangles * 3);
5375                         continue;
5376                 }
5377                 switch(type)
5378                 {
5379                 case Q3FACETYPE_FLAT:
5380                 case Q3FACETYPE_MESH:
5381                         // no processing necessary
5382                         break;
5383                 case Q3FACETYPE_PATCH:
5384                         patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5385                         patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5386                         if (numvertices != (patchsize[0] * patchsize[1]) || patchsize[0] < 3 || patchsize[1] < 3 || !(patchsize[0] & 1) || !(patchsize[1] & 1) || patchsize[0] * patchsize[1] >= min(r_subdivisions_maxvertices.integer, r_subdivisions_collision_maxvertices.integer))
5387                         {
5388                                 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5389                                 continue;
5390                         }
5391                         originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5392
5393                         // convert patch to Q3FACETYPE_MESH
5394                         xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5395                         ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5396                         // bound to user settings
5397                         xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5398                         ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5399                         // bound to sanity settings
5400                         xtess = bound(0, xtess, 1024);
5401                         ytess = bound(0, ytess, 1024);
5402
5403                         // lower quality collision patches! Same procedure as before, but different cvars
5404                         // convert patch to Q3FACETYPE_MESH
5405                         cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5406                         cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_collision_tolerance.value);
5407                         // bound to user settings
5408                         cxtess = bound(r_subdivisions_collision_mintess.integer, cxtess, r_subdivisions_collision_maxtess.integer);
5409                         cytess = bound(r_subdivisions_collision_mintess.integer, cytess, r_subdivisions_collision_maxtess.integer);
5410                         // bound to sanity settings
5411                         cxtess = bound(0, cxtess, 1024);
5412                         cytess = bound(0, cytess, 1024);
5413
5414                         // store it for the LOD grouping step
5415                         patchtess[patchtesscount].info.xsize = patchsize[0];
5416                         patchtess[patchtesscount].info.ysize = patchsize[1];
5417                         patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5418                         patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5419                         patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5420                         patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5421         
5422                         patchtess[patchtesscount].surface_id = i;
5423                         patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5424                         patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5425                         patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5426                         patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5427                         patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5428                         patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5429                         patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5430                         ++patchtesscount;
5431                         break;
5432                 case Q3FACETYPE_FLARE:
5433                         if (developer_extra.integer)
5434                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5435                         // don't render it
5436                         continue;
5437                 }
5438                 out->num_vertices = numvertices;
5439                 out->num_triangles = numtriangles;
5440                 meshvertices += out->num_vertices;
5441                 meshtriangles += out->num_triangles;
5442         }
5443
5444         // Fix patches tesselations so that they make no seams
5445         do
5446         {
5447                 again = false;
5448                 for(i = 0; i < patchtesscount; ++i)
5449                 {
5450                         for(j = i+1; j < patchtesscount; ++j)
5451                         {
5452                                 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5453                                         continue;
5454
5455                                 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5456                                         again = true;
5457                         }
5458                 }
5459         }
5460         while (again);
5461
5462         // Calculate resulting number of triangles
5463         collisionvertices = 0;
5464         collisiontriangles = 0;
5465         for(i = 0; i < patchtesscount; ++i)
5466         {
5467                 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5468                 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5469                 numvertices = finalwidth * finalheight;
5470                 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5471
5472                 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5473                 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5474                 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5475                 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5476
5477                 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5478                 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5479                 numvertices = finalwidth * finalheight;
5480                 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5481
5482                 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
5483                 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
5484                 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
5485                 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
5486         }
5487
5488         i = oldi;
5489         in = oldin;
5490         out = oldout;
5491         Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true, false);
5492         if (collisiontriangles)
5493         {
5494                 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
5495                 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
5496         }
5497         meshvertices = 0;
5498         meshtriangles = 0;
5499         collisionvertices = 0;
5500         collisiontriangles = 0;
5501         for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
5502         {
5503                 if (out->num_vertices < 3 || out->num_triangles < 1)
5504                         continue;
5505
5506                 type = LittleLong(in->type);
5507                 firstvertex = LittleLong(in->firstvertex);
5508                 firstelement = LittleLong(in->firstelement);
5509                 out->num_firstvertex = meshvertices;
5510                 out->num_firsttriangle = meshtriangles;
5511                 out->num_firstcollisiontriangle = collisiontriangles;
5512                 switch(type)
5513                 {
5514                 case Q3FACETYPE_FLAT:
5515                 case Q3FACETYPE_MESH:
5516                         // no processing necessary, except for lightmap merging
5517                         for (j = 0;j < out->num_vertices;j++)
5518                         {
5519                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
5520                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
5521                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
5522                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
5523                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
5524                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
5525                                 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
5526                                 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
5527                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
5528                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
5529                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
5530                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
5531                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
5532                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
5533                         }
5534                         for (j = 0;j < out->num_triangles*3;j++)
5535                                 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
5536                         break;
5537                 case Q3FACETYPE_PATCH:
5538                         patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5539                         patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5540                         originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5541                         originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
5542                         originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
5543                         originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
5544                         originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
5545
5546                         xtess = ytess = cxtess = cytess = -1;
5547                         for(j = 0; j < patchtesscount; ++j)
5548                                 if(patchtess[j].surface_id == i)
5549                                 {
5550                                         xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
5551                                         ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
5552                                         cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
5553                                         cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
5554                                         break;
5555                                 }
5556                         if(xtess == -1)
5557                         {
5558                                 Con_Printf("ERROR: patch %d isn't preprocessed?!?\n", i);
5559                                 xtess = ytess = cxtess = cytess = 0;
5560                         }
5561
5562                         finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
5563                         finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
5564                         finalvertices = finalwidth * finalheight;
5565                         oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5566                         type = Q3FACETYPE_MESH;
5567                         // generate geometry
5568                         // (note: normals are skipped because they get recalculated)
5569                         Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
5570                         Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
5571                         Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
5572                         Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
5573                         Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
5574                         Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
5575
5576                         out->num_triangles = Mod_RemoveDegenerateTriangles(out->num_triangles, (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), loadmodel->surfmesh.data_vertex3f);
5577
5578                         if (developer_extra.integer)
5579                         {
5580                                 if (out->num_triangles < finaltriangles)
5581                                         Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles, %i degenerate triangles removed (leaving %i)\n", patchsize[0], patchsize[1], out->num_vertices, finaltriangles, finaltriangles - out->num_triangles, out->num_triangles);
5582                                 else
5583                                         Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles\n", patchsize[0], patchsize[1], out->num_vertices, out->num_triangles);
5584                         }
5585                         // q3map does not put in collision brushes for curves... ugh
5586                         // build the lower quality collision geometry
5587                         finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
5588                         finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
5589                         finalvertices = finalwidth * finalheight;
5590                         oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5591
5592                         // legacy collision geometry implementation
5593                         out->deprecatedq3data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, sizeof(float[3]) * finalvertices);
5594                         out->deprecatedq3data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int[3]) * finaltriangles);
5595                         out->num_collisionvertices = finalvertices;
5596                         out->num_collisiontriangles = finaltriangles;
5597                         Q3PatchTesselateFloat(3, sizeof(float[3]), out->deprecatedq3data_collisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5598                         Q3PatchTriangleElements(out->deprecatedq3data_collisionelement3i, finalwidth, finalheight, 0);
5599
5600                         //Mod_SnapVertices(3, out->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), 0.25);
5601                         Mod_SnapVertices(3, finalvertices, out->deprecatedq3data_collisionvertex3f, 1);
5602
5603                         out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionelement3i, out->deprecatedq3data_collisionvertex3f);
5604
5605                         // now optimize the collision mesh by finding triangle bboxes...
5606                         Mod_Q3BSP_BuildBBoxes(out->deprecatedq3data_collisionelement3i, out->num_collisiontriangles, out->deprecatedq3data_collisionvertex3f, &out->deprecatedq3data_collisionbbox6f, &out->deprecatedq3num_collisionbboxstride, mod_q3bsp_curves_collisions_stride.integer);
5607                         Mod_Q3BSP_BuildBBoxes(loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle, out->num_triangles, loadmodel->surfmesh.data_vertex3f, &out->deprecatedq3data_bbox6f, &out->deprecatedq3num_bboxstride, mod_q3bsp_curves_stride.integer);
5608
5609                         // store collision geometry for BIH collision tree
5610                         surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
5611                         surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
5612                         Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
5613                         Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
5614                         Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
5615 #if 1
5616                         // remove this once the legacy code is removed
5617                         {
5618                                 int nc = out->num_collisiontriangles;
5619 #endif
5620                         out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
5621 #if 1
5622                                 if(nc != out->num_collisiontriangles)
5623                                 {
5624                                         Con_Printf("number of collision triangles differs between BIH and BSP. FAIL.\n");
5625                                 }
5626                         }
5627 #endif
5628
5629                         if (developer_extra.integer)
5630                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve became %i:%i vertices / %i:%i triangles (%i:%i degenerate)\n", patchsize[0], patchsize[1], out->num_vertices, out->num_collisionvertices, oldnumtriangles, oldnumtriangles2, oldnumtriangles - out->num_triangles, oldnumtriangles2 - out->num_collisiontriangles);
5631
5632                         collisionvertices += finalvertices;
5633                         collisiontriangles += out->num_collisiontriangles;
5634                         break;
5635                 default:
5636                         break;
5637                 }
5638                 meshvertices += out->num_vertices;
5639                 meshtriangles += out->num_triangles;
5640                 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
5641                         if ((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
5642                                 invalidelements++;
5643                 if (invalidelements)
5644                 {
5645                         Con_Printf("Mod_Q3BSP_LoadFaces: Warning: face #%i has %i invalid elements, type = %i, texture->name = \"%s\", texture->surfaceflags = %i, firstvertex = %i, numvertices = %i, firstelement = %i, numelements = %i, elements list:\n", i, invalidelements, type, out->texture->name, out->texture->surfaceflags, firstvertex, out->num_vertices, firstelement, out->num_triangles * 3);
5646                         for (j = 0;j < out->num_triangles * 3;j++)
5647                         {
5648                                 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
5649                                 if ((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
5650                                         (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
5651                         }
5652                         Con_Print("\n");
5653                 }
5654                 // calculate a bounding box
5655                 VectorClear(out->mins);
5656                 VectorClear(out->maxs);
5657                 if (out->num_vertices)
5658                 {
5659                         if (cls.state != ca_dedicated && out->lightmaptexture)
5660                         {
5661                                 // figure out which part of the merged lightmap this fits into
5662                                 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
5663                                 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5664                                 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
5665                                 lightmapindex &= mergewidth * mergeheight - 1;
5666                                 lightmaptcscale[0] = 1.0f / mergewidth;
5667                                 lightmaptcscale[1] = 1.0f / mergeheight;
5668                                 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
5669                                 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
5670                                 // modify the lightmap texcoords to match this region of the merged lightmap
5671                                 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
5672                                 {
5673                                         v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
5674                                         v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
5675                                 }
5676                         }
5677                         VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
5678                         VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
5679                         for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
5680                         {
5681                                 out->mins[0] = min(out->mins[0], v[0]);
5682                                 out->maxs[0] = max(out->maxs[0], v[0]);
5683                                 out->mins[1] = min(out->mins[1], v[1]);
5684                                 out->maxs[1] = max(out->maxs[1], v[1]);
5685                                 out->mins[2] = min(out->mins[2], v[2]);
5686                                 out->maxs[2] = max(out->maxs[2], v[2]);
5687                         }
5688                         out->mins[0] -= 1.0f;
5689                         out->mins[1] -= 1.0f;
5690                         out->mins[2] -= 1.0f;
5691                         out->maxs[0] += 1.0f;
5692                         out->maxs[1] += 1.0f;
5693                         out->maxs[2] += 1.0f;
5694                 }
5695                 // set lightmap styles for consistency with q1bsp
5696                 //out->lightmapinfo->styles[0] = 0;
5697                 //out->lightmapinfo->styles[1] = 255;
5698                 //out->lightmapinfo->styles[2] = 255;
5699                 //out->lightmapinfo->styles[3] = 255;
5700         }
5701
5702         i = oldi;
5703         out = oldout;
5704         for (;i < count;i++, out++)
5705         {
5706                 if(out->num_vertices && out->num_triangles)
5707                         continue;
5708                 if(out->num_vertices == 0)
5709                 {
5710                         Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5711                         if(out->num_triangles == 0)
5712                                 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
5713                 }
5714                 else if(out->num_triangles == 0)
5715                         Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s, near %f %f %f) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)",
5716                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
5717                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
5718                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
5719         }
5720
5721         // for per pixel lighting
5722         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
5723
5724         // generate ushort elements array if possible
5725         if (loadmodel->surfmesh.data_element3s)
5726                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
5727                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
5728
5729         // free the no longer needed vertex data
5730         loadmodel->brushq3.num_vertices = 0;
5731         if (loadmodel->brushq3.data_vertex3f)
5732                 Mem_Free(loadmodel->brushq3.data_vertex3f);
5733         loadmodel->brushq3.data_vertex3f = NULL;
5734         loadmodel->brushq3.data_normal3f = NULL;
5735         loadmodel->brushq3.data_texcoordtexture2f = NULL;
5736         loadmodel->brushq3.data_texcoordlightmap2f = NULL;
5737         loadmodel->brushq3.data_color4f = NULL;
5738         // free the no longer needed triangle data
5739         loadmodel->brushq3.num_triangles = 0;
5740         if (loadmodel->brushq3.data_element3i)
5741                 Mem_Free(loadmodel->brushq3.data_element3i);
5742         loadmodel->brushq3.data_element3i = NULL;
5743
5744         if(patchtess)
5745                 Mem_Free(patchtess);
5746 }
5747
5748 static void Mod_Q3BSP_LoadModels(lump_t *l)
5749 {
5750         q3dmodel_t *in;
5751         q3dmodel_t *out;
5752         int i, j, n, c, count;
5753
5754         in = (q3dmodel_t *)(mod_base + l->fileofs);
5755         if (l->filelen % sizeof(*in))
5756                 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
5757         count = l->filelen / sizeof(*in);
5758         out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5759
5760         loadmodel->brushq3.data_models = out;
5761         loadmodel->brushq3.num_models = count;
5762
5763         for (i = 0;i < count;i++, in++, out++)
5764         {
5765                 for (j = 0;j < 3;j++)
5766                 {
5767                         out->mins[j] = LittleFloat(in->mins[j]);
5768                         out->maxs[j] = LittleFloat(in->maxs[j]);
5769                 }
5770                 n = LittleLong(in->firstface);
5771                 c = LittleLong(in->numfaces);
5772                 if (n < 0 || n + c > loadmodel->num_surfaces)
5773                         Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
5774                 out->firstface = n;
5775                 out->numfaces = c;
5776                 n = LittleLong(in->firstbrush);
5777                 c = LittleLong(in->numbrushes);
5778                 if (n < 0 || n + c > loadmodel->brush.num_brushes)
5779                         Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
5780                 out->firstbrush = n;
5781                 out->numbrushes = c;
5782         }
5783 }
5784
5785 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
5786 {
5787         int *in;
5788         int *out;
5789         int i, n, count;
5790
5791         in = (int *)(mod_base + l->fileofs);
5792         if (l->filelen % sizeof(*in))
5793                 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
5794         count = l->filelen / sizeof(*in);
5795         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5796
5797         loadmodel->brush.data_leafbrushes = out;
5798         loadmodel->brush.num_leafbrushes = count;
5799
5800         for (i = 0;i < count;i++, in++, out++)
5801         {
5802                 n = LittleLong(*in);
5803                 if (n < 0 || n >= loadmodel->brush.num_brushes)
5804                         Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
5805                 *out = n;
5806         }
5807 }
5808
5809 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
5810 {
5811         int *in;
5812         int *out;
5813         int i, n, count;
5814
5815         in = (int *)(mod_base + l->fileofs);
5816         if (l->filelen % sizeof(*in))
5817                 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
5818         count = l->filelen / sizeof(*in);
5819         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5820
5821         loadmodel->brush.data_leafsurfaces = out;
5822         loadmodel->brush.num_leafsurfaces = count;
5823
5824         for (i = 0;i < count;i++, in++, out++)
5825         {
5826                 n = LittleLong(*in);
5827                 if (n < 0 || n >= loadmodel->num_surfaces)
5828                         Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
5829                 *out = n;
5830         }
5831 }
5832
5833 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
5834 {
5835         q3dleaf_t *in;
5836         mleaf_t *out;
5837         int i, j, n, c, count;
5838
5839         in = (q3dleaf_t *)(mod_base + l->fileofs);
5840         if (l->filelen % sizeof(*in))
5841                 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
5842         count = l->filelen / sizeof(*in);
5843         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5844
5845         loadmodel->brush.data_leafs = out;
5846         loadmodel->brush.num_leafs = count;
5847
5848         for (i = 0;i < count;i++, in++, out++)
5849         {
5850                 out->parent = NULL;
5851                 out->plane = NULL;
5852                 out->clusterindex = LittleLong(in->clusterindex);
5853                 out->areaindex = LittleLong(in->areaindex);
5854                 for (j = 0;j < 3;j++)
5855                 {
5856                         // yes the mins/maxs are ints
5857                         out->mins[j] = LittleLong(in->mins[j]) - 1;
5858                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5859                 }
5860                 n = LittleLong(in->firstleafface);
5861                 c = LittleLong(in->numleaffaces);
5862                 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
5863                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
5864                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
5865                 out->numleafsurfaces = c;
5866                 n = LittleLong(in->firstleafbrush);
5867                 c = LittleLong(in->numleafbrushes);
5868                 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
5869                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
5870                 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
5871                 out->numleafbrushes = c;
5872         }
5873 }
5874
5875 static void Mod_Q3BSP_LoadNodes(lump_t *l)
5876 {
5877         q3dnode_t *in;
5878         mnode_t *out;
5879         int i, j, n, count;
5880
5881         in = (q3dnode_t *)(mod_base + l->fileofs);
5882         if (l->filelen % sizeof(*in))
5883                 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
5884         count = l->filelen / sizeof(*in);
5885         if (count == 0)
5886                 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
5887         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5888
5889         loadmodel->brush.data_nodes = out;
5890         loadmodel->brush.num_nodes = count;
5891
5892         for (i = 0;i < count;i++, in++, out++)
5893         {
5894                 out->parent = NULL;
5895                 n = LittleLong(in->planeindex);
5896                 if (n < 0 || n >= loadmodel->brush.num_planes)
5897                         Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5898                 out->plane = loadmodel->brush.data_planes + n;
5899                 for (j = 0;j < 2;j++)
5900                 {
5901                         n = LittleLong(in->childrenindex[j]);
5902                         if (n >= 0)
5903                         {
5904                                 if (n >= loadmodel->brush.num_nodes)
5905                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
5906                                 out->children[j] = loadmodel->brush.data_nodes + n;
5907                         }
5908                         else
5909                         {
5910                                 n = -1 - n;
5911                                 if (n >= loadmodel->brush.num_leafs)
5912                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
5913                                 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
5914                         }
5915                 }
5916                 for (j = 0;j < 3;j++)
5917                 {
5918                         // yes the mins/maxs are ints
5919                         out->mins[j] = LittleLong(in->mins[j]) - 1;
5920                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
5921                 }
5922         }
5923
5924         // set the parent pointers
5925         Mod_Q1BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
5926 }
5927
5928 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
5929 {
5930         q3dlightgrid_t *in;
5931         q3dlightgrid_t *out;
5932         int count;
5933         int i;
5934
5935         in = (q3dlightgrid_t *)(mod_base + l->fileofs);
5936         if (l->filelen % sizeof(*in))
5937                 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
5938         loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
5939         loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
5940         loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
5941         loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5942         loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5943         loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5944         loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
5945         loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
5946         loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
5947         loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
5948         loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
5949         loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
5950         count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
5951         Matrix4x4_CreateScale3(&loadmodel->brushq3.num_lightgrid_indexfromworld, loadmodel->brushq3.num_lightgrid_scale[0], loadmodel->brushq3.num_lightgrid_scale[1], loadmodel->brushq3.num_lightgrid_scale[2]);
5952         Matrix4x4_ConcatTranslate(&loadmodel->brushq3.num_lightgrid_indexfromworld, -loadmodel->brushq3.num_lightgrid_imins[0] * loadmodel->brushq3.num_lightgrid_cellsize[0], -loadmodel->brushq3.num_lightgrid_imins[1] * loadmodel->brushq3.num_lightgrid_cellsize[1], -loadmodel->brushq3.num_lightgrid_imins[2] * loadmodel->brushq3.num_lightgrid_cellsize[2]);
5953
5954         // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
5955         if (l->filelen)
5956         {
5957                 if (l->filelen < count * (int)sizeof(*in))
5958                 {
5959                         Con_Printf("Mod_Q3BSP_LoadLightGrid: invalid lightgrid lump size %i bytes, should be %i bytes (%ix%ix%i)", l->filelen, (int)(count * sizeof(*in)), loadmodel->brushq3.num_lightgrid_isize[0], loadmodel->brushq3.num_lightgrid_isize[1], loadmodel->brushq3.num_lightgrid_isize[2]);
5960                         return; // ignore the grid if we cannot understand it
5961                 }
5962                 if (l->filelen != count * (int)sizeof(*in))
5963                         Con_Printf("Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
5964                 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5965                 loadmodel->brushq3.data_lightgrid = out;
5966                 loadmodel->brushq3.num_lightgrid = count;
5967                 // no swapping or validation necessary
5968                 memcpy(out, in, count * (int)sizeof(*out));
5969
5970                 if(mod_q3bsp_sRGBlightmaps.integer)
5971                 {
5972                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5973                         {
5974                                 // we fix the brightness consistently via lightmapscale
5975                         }
5976                         else
5977                         {
5978                                 for(i = 0; i < count; ++i)
5979                                 {
5980                                         out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
5981                                         out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
5982                                         out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
5983                                         out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
5984                                         out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
5985                                         out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
5986                                 }
5987                         }
5988                 }
5989                 else
5990                 {
5991                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5992                         {
5993                                 for(i = 0; i < count; ++i)
5994                                 {
5995                                         out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
5996                                         out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
5997                                         out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
5998                                         out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
5999                                         out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6000                                         out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6001                                 }
6002                         }
6003                         else
6004                         {
6005                                 // all is good
6006                         }
6007                 }
6008         }
6009 }
6010
6011 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6012 {
6013         q3dpvs_t *in;
6014         int totalchains;
6015
6016         if (l->filelen == 0)
6017         {
6018                 int i;
6019                 // unvised maps often have cluster indices even without pvs, so check
6020                 // leafs to find real number of clusters
6021                 loadmodel->brush.num_pvsclusters = 1;
6022                 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6023                         loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6024
6025                 // create clusters
6026                 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6027                 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6028                 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6029                 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6030                 return;
6031         }
6032
6033         in = (q3dpvs_t *)(mod_base + l->fileofs);
6034         if (l->filelen < 9)
6035                 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6036
6037         loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6038         loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6039         if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6040                 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6041         totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6042         if (l->filelen < totalchains + (int)sizeof(*in))
6043                 Host_Error("Mod_Q3BSP_LoadPVS: lump too small ((numclusters = %i) * (chainlength = %i) + sizeof(q3dpvs_t) == %i bytes, lump is %i bytes)", loadmodel->brush.num_pvsclusters, loadmodel->brush.num_pvsclusterbytes, (int)(totalchains + sizeof(*in)), l->filelen);
6044
6045         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6046         memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6047 }
6048
6049 static void Mod_Q3BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6050 {
6051         int i, j, k, index[3];
6052         float transformed[3], blend1, blend2, blend, stylescale = 1;
6053         q3dlightgrid_t *a, *s;
6054
6055         // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6056         switch(vid.renderpath)
6057         {
6058         case RENDERPATH_GL20:
6059         case RENDERPATH_D3D9:
6060         case RENDERPATH_D3D10:
6061         case RENDERPATH_D3D11:
6062         case RENDERPATH_SOFT:
6063         case RENDERPATH_GLES2:
6064                 // LordHavoc: FIXME: is this true?
6065                 stylescale = 1; // added while render
6066                 break;
6067         case RENDERPATH_GL11:
6068         case RENDERPATH_GL13:
6069         case RENDERPATH_GLES1:
6070                 stylescale = r_refdef.scene.rtlightstylevalue[0];
6071                 break;
6072         }
6073
6074         if (!model->brushq3.num_lightgrid)
6075         {
6076                 ambientcolor[0] = stylescale;
6077                 ambientcolor[1] = stylescale;
6078                 ambientcolor[2] = stylescale;
6079                 return;
6080         }
6081
6082         Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6083         //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6084         //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6085         transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6086         transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6087         transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6088         index[0] = (int)floor(transformed[0]);
6089         index[1] = (int)floor(transformed[1]);
6090         index[2] = (int)floor(transformed[2]);
6091         //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6092
6093         // now lerp the values
6094         VectorClear(diffusenormal);
6095         a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6096         for (k = 0;k < 2;k++)
6097         {
6098                 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6099                 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6100                         continue;
6101                 for (j = 0;j < 2;j++)
6102                 {
6103                         blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6104                         if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6105                                 continue;
6106                         for (i = 0;i < 2;i++)
6107                         {
6108                                 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6109                                 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6110                                         continue;
6111                                 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6112                                 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6113                                 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6114                                 // this uses the mod_md3_sin table because the values are
6115                                 // already in the 0-255 range, the 64+ bias fetches a cosine
6116                                 // instead of a sine value
6117                                 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6118                                 diffusenormal[1] += blend * (mod_md3_sin[     s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6119                                 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6120                                 //Con_Printf("blend %f: ambient %i %i %i, diffuse %i %i %i, diffusepitch %i diffuseyaw %i (%f %f, normal %f %f %f)\n", blend, s->ambientrgb[0], s->ambientrgb[1], s->ambientrgb[2], s->diffusergb[0], s->diffusergb[1], s->diffusergb[2], s->diffusepitch, s->diffuseyaw, pitch, yaw, (cos(yaw) * cospitch), (sin(yaw) * cospitch), (-sin(pitch)));
6121                         }
6122                 }
6123         }
6124
6125         // normalize the light direction before turning
6126         VectorNormalize(diffusenormal);
6127         //Con_Printf("result: ambient %f %f %f diffuse %f %f %f diffusenormal %f %f %f\n", ambientcolor[0], ambientcolor[1], ambientcolor[2], diffusecolor[0], diffusecolor[1], diffusecolor[2], diffusenormal[0], diffusenormal[1], diffusenormal[2]);
6128 }
6129
6130 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3])
6131 {
6132         double t1, t2;
6133         double midf, mid[3];
6134         int ret, side;
6135
6136         // check for empty
6137         while (node->plane)
6138         {
6139                 // find the point distances
6140                 mplane_t *plane = node->plane;
6141                 if (plane->type < 3)
6142                 {
6143                         t1 = p1[plane->type] - plane->dist;
6144                         t2 = p2[plane->type] - plane->dist;
6145                 }
6146                 else
6147                 {
6148                         t1 = DotProduct (plane->normal, p1) - plane->dist;
6149                         t2 = DotProduct (plane->normal, p2) - plane->dist;
6150                 }
6151
6152                 if (t1 < 0)
6153                 {
6154                         if (t2 < 0)
6155                         {
6156                                 node = node->children[1];
6157                                 continue;
6158                         }
6159                         side = 1;
6160                 }
6161                 else
6162                 {
6163                         if (t2 >= 0)
6164                         {
6165                                 node = node->children[0];
6166                                 continue;
6167                         }
6168                         side = 0;
6169                 }
6170
6171                 midf = t1 / (t1 - t2);
6172                 VectorLerp(p1, midf, p2, mid);
6173
6174                 // recurse both sides, front side first
6175                 // return 2 if empty is followed by solid (hit something)
6176                 // do not return 2 if both are solid or both empty,
6177                 // or if start is solid and end is empty
6178                 // as these degenerate cases usually indicate the eye is in solid and
6179                 // should see the target point anyway
6180                 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side    ], p1, mid);
6181                 if (ret != 0)
6182                         return ret;
6183                 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2);
6184                 if (ret != 1)
6185                         return ret;
6186                 return 2;
6187         }
6188         return ((mleaf_t *)node)->clusterindex < 0;
6189 }
6190
6191 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
6192 {
6193         if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6194         {
6195                 trace_t trace;
6196                 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK);
6197                 return trace.fraction == 1;
6198         }
6199         else
6200         {
6201                 double tracestart[3], traceend[3];
6202                 VectorCopy(start, tracestart);
6203                 VectorCopy(end, traceend);
6204                 return !Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend);
6205         }
6206 }
6207
6208 void Mod_CollisionBIH_TracePoint(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask)
6209 {
6210         const bih_t *bih;
6211         const bih_leaf_t *leaf;
6212         const bih_node_t *node;
6213         const colbrushf_t *brush;
6214         int axis;
6215         int nodenum;
6216         int nodestackpos = 0;
6217         int nodestack[1024];
6218
6219         memset(trace, 0, sizeof(*trace));
6220         trace->fraction = 1;
6221         trace->realfraction = 1;
6222         trace->hitsupercontentsmask = hitsupercontentsmask;
6223
6224         bih = &model->collision_bih;
6225         if(!bih->nodes)
6226                 return;
6227
6228         nodenum = bih->rootnode;
6229         nodestack[nodestackpos++] = nodenum;
6230         while (nodestackpos)
6231         {
6232                 nodenum = nodestack[--nodestackpos];
6233                 node = bih->nodes + nodenum;
6234 #if 1
6235                 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6236                         continue;
6237 #endif
6238                 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6239                 {
6240                         axis = node->type - BIH_SPLITX;
6241                         if (start[axis] >= node->frontmin)
6242                                 nodestack[nodestackpos++] = node->front;
6243                         if (start[axis] <= node->backmax)
6244                                 nodestack[nodestackpos++] = node->back;
6245                 }
6246                 else if (node->type == BIH_UNORDERED)
6247                 {
6248                         for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6249                         {
6250                                 leaf = bih->leafs + node->children[axis];
6251 #if 1
6252                                 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6253                                         continue;
6254 #endif
6255                                 switch(leaf->type)
6256                                 {
6257                                 case BIH_BRUSH:
6258                                         brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6259                                         Collision_TracePointBrushFloat(trace, start, brush);
6260                                         break;
6261                                 case BIH_COLLISIONTRIANGLE:
6262                                         // collision triangle - skipped because they have no volume
6263                                         break;
6264                                 case BIH_RENDERTRIANGLE:
6265                                         // render triangle - skipped because they have no volume
6266                                         break;
6267                                 }
6268                         }
6269                 }
6270         }
6271 }
6272
6273 static void Mod_CollisionBIH_TraceLineShared(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, const bih_t *bih)
6274 {
6275         const bih_leaf_t *leaf;
6276         const bih_node_t *node;
6277         const colbrushf_t *brush;
6278         const int *e;
6279         const texture_t *texture;
6280         vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6281         vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6282         int axis, nodenum, nodestackpos = 0, nodestack[1024];
6283
6284         if(!bih->nodes)
6285                 return;
6286
6287         if (VectorCompare(start, end))
6288         {
6289                 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6290                 return;
6291         }
6292
6293         nodenum = bih->rootnode;
6294
6295         memset(trace, 0, sizeof(*trace));
6296         trace->fraction = 1;
6297         trace->realfraction = 1;
6298         trace->hitsupercontentsmask = hitsupercontentsmask;
6299
6300         // push first node
6301         nodestackline[nodestackpos][0] = start[0];
6302         nodestackline[nodestackpos][1] = start[1];
6303         nodestackline[nodestackpos][2] = start[2];
6304         nodestackline[nodestackpos][3] = end[0];
6305         nodestackline[nodestackpos][4] = end[1];
6306         nodestackline[nodestackpos][5] = end[2];
6307         nodestack[nodestackpos++] = nodenum;
6308         while (nodestackpos)
6309         {
6310                 nodenum = nodestack[--nodestackpos];
6311                 node = bih->nodes + nodenum;
6312                 VectorCopy(nodestackline[nodestackpos], nodestart);
6313                 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6314                 sweepnodemins[0] = min(nodestart[0], nodeend[0]); sweepnodemins[1] = min(nodestart[1], nodeend[1]); sweepnodemins[2] = min(nodestart[2], nodeend[2]); sweepnodemaxs[0] = max(nodestart[0], nodeend[0]); sweepnodemaxs[1] = max(nodestart[1], nodeend[1]); sweepnodemaxs[2] = max(nodestart[2], nodeend[2]);
6315                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6316                         continue;
6317                 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6318                 {
6319                         // recurse children of the split
6320                         axis = node->type - BIH_SPLITX;
6321                         d1 = node->backmax - nodestart[axis];
6322                         d2 = node->backmax - nodeend[axis];
6323                         d3 = nodestart[axis] - node->frontmin;
6324                         d4 = nodeend[axis] - node->frontmin;
6325                         switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6326                         {
6327                         case  0: /* >>>> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6328                         case  1: /* <>>> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6329                         case  2: /* ><>> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6330                         case  3: /* <<>> */                                                                                                                                                                                                                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6331                         case  4: /* >><> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6332                         case  5: /* <><> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6333                         case  6: /* ><<> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6334                         case  7: /* <<<> */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6335                         case  8: /* >>>< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6336                         case  9: /* <>>< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6337                         case 10: /* ><>< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6338                         case 11: /* <<>< */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6339                         case 12: /* >><< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6340                         case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6341                         case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6342                         case 15: /* <<<< */                                                                                                                                                                                                                                                                                                                                                                                                   break;
6343                         }
6344                 }
6345                 else if (node->type == BIH_UNORDERED)
6346                 {
6347                         // calculate sweep bounds for this node
6348                         // copy node bounds into local variables
6349                         VectorCopy(node->mins, nodebigmins);
6350                         VectorCopy(node->maxs, nodebigmaxs);
6351                         // clip line to this node bounds
6352                         axis = 0; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6353                         axis = 1; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6354                         axis = 2; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6355                         // some of the line intersected the enlarged node box
6356                         // calculate sweep bounds for this node
6357                         sweepnodemins[0] = min(nodestart[0], nodeend[0]); sweepnodemins[1] = min(nodestart[1], nodeend[1]); sweepnodemins[2] = min(nodestart[2], nodeend[2]); sweepnodemaxs[0] = max(nodestart[0], nodeend[0]); sweepnodemaxs[1] = max(nodestart[1], nodeend[1]); sweepnodemaxs[2] = max(nodestart[2], nodeend[2]);
6358                         for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6359                         {
6360                                 leaf = bih->leafs + node->children[axis];
6361                                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6362                                         continue;
6363                                 switch(leaf->type)
6364                                 {
6365                                 case BIH_BRUSH:
6366                                         brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6367                                         Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6368                                         break;
6369                                 case BIH_COLLISIONTRIANGLE:
6370                                         if (!mod_q3bsp_curves_collisions.integer)
6371                                                 continue;
6372                                         e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6373                                         texture = model->data_textures + leaf->textureindex;
6374                                         Collision_TraceLineTriangleFloat(trace, start, end, model->brush.data_collisionvertex3f + e[0] * 3, model->brush.data_collisionvertex3f + e[1] * 3, model->brush.data_collisionvertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6375                                         break;
6376                                 case BIH_RENDERTRIANGLE:
6377                                         e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6378                                         texture = model->data_textures + leaf->textureindex;
6379                                         Collision_TraceLineTriangleFloat(trace, start, end, model->surfmesh.data_vertex3f + e[0] * 3, model->surfmesh.data_vertex3f + e[1] * 3, model->surfmesh.data_vertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6380                                         break;
6381                                 }
6382                         }
6383                 }
6384         }
6385 }
6386
6387 void Mod_CollisionBIH_TraceLine(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
6388 {
6389         if (VectorCompare(start, end))
6390         {
6391                 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6392                 return;
6393         }
6394         Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->collision_bih);
6395 }
6396
6397 void Mod_CollisionBIH_TraceBrush(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, colbrushf_t *thisbrush_start, colbrushf_t *thisbrush_end, int hitsupercontentsmask)
6398 {
6399         const bih_t *bih;
6400         const bih_leaf_t *leaf;
6401         const bih_node_t *node;
6402         const colbrushf_t *brush;
6403         const int *e;
6404         const texture_t *texture;
6405         vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6406         vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6407         vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6408         int axis, nodenum, nodestackpos = 0, nodestack[1024];
6409
6410         if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6411         {
6412                 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6413                         Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask);
6414                 else
6415                         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask);
6416                 return;
6417         }
6418
6419         bih = &model->collision_bih;
6420         if(!bih->nodes)
6421                 return;
6422         nodenum = bih->rootnode;
6423
6424         // box trace, performed as brush trace
6425         memset(trace, 0, sizeof(*trace));
6426         trace->fraction = 1;
6427         trace->realfraction = 1;
6428         trace->hitsupercontentsmask = hitsupercontentsmask;
6429
6430         // calculate tracebox-like parameters for efficient culling
6431         VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
6432         VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
6433         VectorSubtract(thisbrush_start->mins, start, startmins);
6434         VectorSubtract(thisbrush_start->maxs, start, startmaxs);
6435         VectorSubtract(thisbrush_end->mins, end, endmins);
6436         VectorSubtract(thisbrush_end->maxs, end, endmaxs);
6437         mins[0] = min(startmins[0], endmins[0]);
6438         mins[1] = min(startmins[1], endmins[1]);
6439         mins[2] = min(startmins[2], endmins[2]);
6440         maxs[0] = max(startmaxs[0], endmaxs[0]);
6441         maxs[1] = max(startmaxs[1], endmaxs[1]);
6442         maxs[2] = max(startmaxs[2], endmaxs[2]);
6443
6444         // push first node
6445         nodestackline[nodestackpos][0] = start[0];
6446         nodestackline[nodestackpos][1] = start[1];
6447         nodestackline[nodestackpos][2] = start[2];
6448         nodestackline[nodestackpos][3] = end[0];
6449         nodestackline[nodestackpos][4] = end[1];
6450         nodestackline[nodestackpos][5] = end[2];
6451         nodestack[nodestackpos++] = nodenum;
6452         while (nodestackpos)
6453         {
6454                 nodenum = nodestack[--nodestackpos];
6455                 node = bih->nodes + nodenum;
6456                 VectorCopy(nodestackline[nodestackpos], nodestart);
6457                 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6458                 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0]; sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1]; sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2]; sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0]; sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1]; sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2];
6459                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
6460                         continue;
6461                 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6462                 {
6463                         // recurse children of the split
6464                         axis = node->type - BIH_SPLITX;
6465                         d1 = node->backmax - nodestart[axis] - mins[axis];
6466                         d2 = node->backmax - nodeend[axis] - mins[axis];
6467                         d3 = nodestart[axis] - node->frontmin + maxs[axis];
6468                         d4 = nodeend[axis] - node->frontmin + maxs[axis];
6469                         switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6470                         {
6471                         case  0: /* >>>> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6472                         case  1: /* <>>> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6473                         case  2: /* ><>> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6474                         case  3: /* <<>> */                                                                                                                                                                                                                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6475                         case  4: /* >><> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6476                         case  5: /* <><> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6477                         case  6: /* ><<> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6478                         case  7: /* <<<> */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6479                         case  8: /* >>>< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6480                         case  9: /* <>>< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6481                         case 10: /* ><>< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6482                         case 11: /* <<>< */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6483                         case 12: /* >><< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6484                         case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6485                         case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6486                         case 15: /* <<<< */                                                                                                                                                                                                                                                                                                                                                                                                   break;
6487                         }
6488                 }
6489                 else if (node->type == BIH_UNORDERED)
6490                 {
6491                         // calculate sweep bounds for this node
6492                         // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
6493                         VectorSubtract(node->mins, maxs, nodebigmins);
6494                         VectorSubtract(node->maxs, mins, nodebigmaxs);
6495                         // clip line to this node bounds
6496                         axis = 0; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6497                         axis = 1; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6498                         axis = 2; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6499                         // some of the line intersected the enlarged node box
6500                         // calculate sweep bounds for this node
6501                         sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0]; sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1]; sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2]; sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0]; sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1]; sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2];
6502                         for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6503                         {
6504                                 leaf = bih->leafs + node->children[axis];
6505                                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6506                                         continue;
6507                                 switch(leaf->type)
6508                                 {
6509                                 case BIH_BRUSH:
6510                                         brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6511                                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6512                                         break;
6513                                 case BIH_COLLISIONTRIANGLE:
6514                                         if (!mod_q3bsp_curves_collisions.integer)
6515                                                 continue;
6516                                         e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6517                                         texture = model->data_textures + leaf->textureindex;
6518                                         Collision_TraceBrushTriangleFloat(trace, thisbrush_start, thisbrush_end, model->brush.data_collisionvertex3f + e[0] * 3, model->brush.data_collisionvertex3f + e[1] * 3, model->brush.data_collisionvertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6519                                         break;
6520                                 case BIH_RENDERTRIANGLE:
6521                                         e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6522                                         texture = model->data_textures + leaf->textureindex;
6523                                         Collision_TraceBrushTriangleFloat(trace, thisbrush_start, thisbrush_end, model->surfmesh.data_vertex3f + e[0] * 3, model->surfmesh.data_vertex3f + e[1] * 3, model->surfmesh.data_vertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6524                                         break;
6525                                 }
6526                         }
6527                 }
6528         }
6529 }
6530
6531 void Mod_CollisionBIH_TraceBox(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask)
6532 {
6533         colboxbrushf_t thisbrush_start, thisbrush_end;
6534         vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6535
6536         // box trace, performed as brush trace
6537         VectorAdd(start, boxmins, boxstartmins);
6538         VectorAdd(start, boxmaxs, boxstartmaxs);
6539         VectorAdd(end, boxmins, boxendmins);
6540         VectorAdd(end, boxmaxs, boxendmaxs);
6541         Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6542         Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6543         Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6544 }
6545
6546
6547 static int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6548 {
6549         trace_t trace;
6550         Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0);
6551         return trace.startsupercontents;
6552 }
6553
6554 void Mod_CollisionBIH_TracePoint_Mesh(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask)
6555 {
6556 #if 0
6557         // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6558         vec3_t end;
6559         int hitsupercontents;
6560         VectorSet(end, start[0], start[1], model->normalmins[2]);
6561 #endif
6562         memset(trace, 0, sizeof(*trace));
6563         trace->fraction = 1;
6564         trace->realfraction = 1;
6565         trace->hitsupercontentsmask = hitsupercontentsmask;
6566 #if 0
6567         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6568         hitsupercontents = trace->hitsupercontents;
6569         memset(trace, 0, sizeof(*trace));
6570         trace->fraction = 1;
6571         trace->realfraction = 1;
6572         trace->hitsupercontentsmask = hitsupercontentsmask;
6573         trace->startsupercontents = hitsupercontents;
6574 #endif
6575 }
6576
6577 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
6578 {
6579 #if 0
6580         // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
6581         trace_t trace;
6582         vec3_t end;
6583         VectorSet(end, start[0], start[1], model->normalmins[2]);
6584         memset(&trace, 0, sizeof(trace));
6585         trace.fraction = 1;
6586         trace.realfraction = 1;
6587         trace.hitsupercontentsmask = 0;
6588         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6589         return trace.hitsupercontents;
6590 #else
6591         return 0;
6592 #endif
6593 }
6594
6595 static void Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t point, int markframe)
6596 {
6597         int i;
6598         mleaf_t *leaf;
6599         colbrushf_t *brush;
6600         // find which leaf the point is in
6601         while (node->plane)
6602                 node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6603         // point trace the brushes
6604         leaf = (mleaf_t *)node;
6605         for (i = 0;i < leaf->numleafbrushes;i++)
6606         {
6607                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6608                 if (brush && brush->markframe != markframe && BoxesOverlap(point, point, brush->mins, brush->maxs))
6609                 {
6610                         brush->markframe = markframe;
6611                         Collision_TracePointBrushFloat(trace, point, brush);
6612                 }
6613         }
6614         // can't do point traces on curves (they have no thickness)
6615 }
6616
6617 static void Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const vec3_t start, const vec3_t end, vec_t startfrac, vec_t endfrac, const vec3_t linestart, const vec3_t lineend, int markframe, const vec3_t segmentmins, const vec3_t segmentmaxs)
6618 {
6619         int i, startside, endside;
6620         float dist1, dist2, midfrac, mid[3], nodesegmentmins[3], nodesegmentmaxs[3];
6621         mleaf_t *leaf;
6622         msurface_t *surface;
6623         mplane_t *plane;
6624         colbrushf_t *brush;
6625         // walk the tree until we hit a leaf, recursing for any split cases
6626         while (node->plane)
6627         {
6628 #if 0
6629                 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6630                         return;
6631                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[0], start, end, startfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6632                 node = node->children[1];
6633 #else
6634                 // abort if this part of the bsp tree can not be hit by this trace
6635 //              if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6636 //                      return;
6637                 plane = node->plane;
6638                 // axial planes are much more common than non-axial, so an optimized
6639                 // axial case pays off here
6640                 if (plane->type < 3)
6641                 {
6642                         dist1 = start[plane->type] - plane->dist;
6643                         dist2 = end[plane->type] - plane->dist;
6644                 }
6645                 else
6646                 {
6647                         dist1 = DotProduct(start, plane->normal) - plane->dist;
6648                         dist2 = DotProduct(end, plane->normal) - plane->dist;
6649                 }
6650                 startside = dist1 < 0;
6651                 endside = dist2 < 0;
6652                 if (startside == endside)
6653                 {
6654                         // most of the time the line fragment is on one side of the plane
6655                         node = node->children[startside];
6656                 }
6657                 else
6658                 {
6659                         // line crosses node plane, split the line
6660                         dist1 = PlaneDiff(linestart, plane);
6661                         dist2 = PlaneDiff(lineend, plane);
6662                         midfrac = dist1 / (dist1 - dist2);
6663                         VectorLerp(linestart, midfrac, lineend, mid);
6664                         // take the near side first
6665                         Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[startside], start, mid, startfrac, midfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6666                         // if we found an impact on the front side, don't waste time
6667                         // exploring the far side
6668                         if (midfrac <= trace->realfraction)
6669                                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, node->children[endside], mid, end, midfrac, endfrac, linestart, lineend, markframe, segmentmins, segmentmaxs);
6670                         return;
6671                 }
6672 #endif
6673         }
6674         // abort if this part of the bsp tree can not be hit by this trace
6675 //      if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6676 //              return;
6677         // hit a leaf
6678         nodesegmentmins[0] = min(start[0], end[0]) - 1;
6679         nodesegmentmins[1] = min(start[1], end[1]) - 1;
6680         nodesegmentmins[2] = min(start[2], end[2]) - 1;
6681         nodesegmentmaxs[0] = max(start[0], end[0]) + 1;
6682         nodesegmentmaxs[1] = max(start[1], end[1]) + 1;
6683         nodesegmentmaxs[2] = max(start[2], end[2]) + 1;
6684         // line trace the brushes
6685         leaf = (mleaf_t *)node;
6686 #if 0
6687         if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6688                 return;
6689 #endif
6690         for (i = 0;i < leaf->numleafbrushes;i++)
6691         {
6692                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6693                 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6694                 {
6695                         brush->markframe = markframe;
6696                         Collision_TraceLineBrushFloat(trace, linestart, lineend, brush, brush);
6697                 }
6698         }
6699         // can't do point traces on curves (they have no thickness)
6700         if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer && !VectorCompare(start, end))
6701         {
6702                 // line trace the curves
6703                 for (i = 0;i < leaf->numleafsurfaces;i++)
6704                 {
6705                         surface = model->data_surfaces + leaf->firstleafsurface[i];
6706                         if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6707                         {
6708                                 surface->deprecatedq3collisionmarkframe = markframe;
6709                                 Collision_TraceLineTriangleMeshFloat(trace, linestart, lineend, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
6710                         }
6711                 }
6712         }
6713 }
6714
6715 static void Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace_t *trace, dp_model_t *model, mnode_t *node, const colbrushf_t *thisbrush_start, const colbrushf_t *thisbrush_end, int markframe, const vec3_t segmentmins, const vec3_t segmentmaxs)
6716 {
6717         int i;
6718         int sides;
6719         mleaf_t *leaf;
6720         colbrushf_t *brush;
6721         msurface_t *surface;
6722         mplane_t *plane;
6723         float nodesegmentmins[3], nodesegmentmaxs[3];
6724         // walk the tree until we hit a leaf, recursing for any split cases
6725         while (node->plane)
6726         {
6727 #if 0
6728                 if (!BoxesOverlap(segmentmins, segmentmaxs, node->mins, node->maxs))
6729                         return;
6730                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6731                 node = node->children[1];
6732 #else
6733                 // abort if this part of the bsp tree can not be hit by this trace
6734 //              if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6735 //                      return;
6736                 plane = node->plane;
6737                 // axial planes are much more common than non-axial, so an optimized
6738                 // axial case pays off here
6739                 if (plane->type < 3)
6740                 {
6741                         // this is an axial plane, compare bounding box directly to it and
6742                         // recurse sides accordingly
6743                         // recurse down node sides
6744                         // use an inlined axial BoxOnPlaneSide to slightly reduce overhead
6745                         //sides = BoxOnPlaneSide(nodesegmentmins, nodesegmentmaxs, plane);
6746                         //sides = ((segmentmaxs[plane->type] >= plane->dist) | ((segmentmins[plane->type] < plane->dist) << 1));
6747                         sides = ((segmentmaxs[plane->type] >= plane->dist) + ((segmentmins[plane->type] < plane->dist) * 2));
6748                 }
6749                 else
6750                 {
6751                         // this is a non-axial plane, so check if the start and end boxes
6752                         // are both on one side of the plane to handle 'diagonal' cases
6753                         sides = BoxOnPlaneSide(thisbrush_start->mins, thisbrush_start->maxs, plane) | BoxOnPlaneSide(thisbrush_end->mins, thisbrush_end->maxs, plane);
6754                 }
6755                 if (sides == 3)
6756                 {
6757                         // segment crosses plane
6758                         Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, node->children[0], thisbrush_start, thisbrush_end, markframe, segmentmins, segmentmaxs);
6759                         sides = 2;
6760                 }
6761                 // if sides == 0 then the trace itself is bogus (Not A Number values),
6762                 // in this case we simply pretend the trace hit nothing
6763                 if (sides == 0)
6764                         return; // ERROR: NAN bounding box!
6765                 // take whichever side the segment box is on
6766                 node = node->children[sides - 1];
6767 #endif
6768         }
6769         // abort if this part of the bsp tree can not be hit by this trace
6770 //      if (!(node->combinedsupercontents & trace->hitsupercontentsmask))
6771 //              return;
6772         nodesegmentmins[0] = max(segmentmins[0], node->mins[0] - 1);
6773         nodesegmentmins[1] = max(segmentmins[1], node->mins[1] - 1);
6774         nodesegmentmins[2] = max(segmentmins[2], node->mins[2] - 1);
6775         nodesegmentmaxs[0] = min(segmentmaxs[0], node->maxs[0] + 1);
6776         nodesegmentmaxs[1] = min(segmentmaxs[1], node->maxs[1] + 1);
6777         nodesegmentmaxs[2] = min(segmentmaxs[2], node->maxs[2] + 1);
6778         // hit a leaf
6779         leaf = (mleaf_t *)node;
6780 #if 0
6781         if (!BoxesOverlap(segmentmins, segmentmaxs, leaf->mins, leaf->maxs))
6782                 return;
6783 #endif
6784         for (i = 0;i < leaf->numleafbrushes;i++)
6785         {
6786                 brush = model->brush.data_brushes[leaf->firstleafbrush[i]].colbrushf;
6787                 if (brush && brush->markframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, brush->mins, brush->maxs))
6788                 {
6789                         brush->markframe = markframe;
6790                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
6791                 }
6792         }
6793         if (leaf->containscollisionsurfaces && mod_q3bsp_curves_collisions.integer)
6794         {
6795                 for (i = 0;i < leaf->numleafsurfaces;i++)
6796                 {
6797                         surface = model->data_surfaces + leaf->firstleafsurface[i];
6798                         if (surface->num_collisiontriangles && surface->deprecatedq3collisionmarkframe != markframe && BoxesOverlap(nodesegmentmins, nodesegmentmaxs, surface->mins, surface->maxs))
6799                         {
6800                                 surface->deprecatedq3collisionmarkframe = markframe;
6801                                 Collision_TraceBrushTriangleMeshFloat(trace, thisbrush_start, thisbrush_end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
6802                         }
6803                 }
6804         }
6805 }
6806
6807
6808 static int markframe = 0;
6809
6810 static void Mod_Q3BSP_TracePoint(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask)
6811 {
6812         int i;
6813         q3mbrush_t *brush;
6814         memset(trace, 0, sizeof(*trace));
6815         trace->fraction = 1;
6816         trace->realfraction = 1;
6817         trace->hitsupercontentsmask = hitsupercontentsmask;
6818         if (mod_collision_bih.integer)
6819                 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6820         else if (model->brush.submodel)
6821         {
6822                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6823                         if (brush->colbrushf)
6824                                 Collision_TracePointBrushFloat(trace, start, brush->colbrushf);
6825         }
6826         else
6827                 Mod_Q3BSP_TracePoint_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, ++markframe);
6828 }
6829
6830 static void Mod_Q3BSP_TraceLine(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
6831 {
6832         int i;
6833         float segmentmins[3], segmentmaxs[3];
6834         msurface_t *surface;
6835         q3mbrush_t *brush;
6836
6837         if (VectorCompare(start, end))
6838         {
6839                 Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask);
6840                 return;
6841         }
6842
6843         memset(trace, 0, sizeof(*trace));
6844         trace->fraction = 1;
6845         trace->realfraction = 1;
6846         trace->hitsupercontentsmask = hitsupercontentsmask;
6847         segmentmins[0] = min(start[0], end[0]) - 1;
6848         segmentmins[1] = min(start[1], end[1]) - 1;
6849         segmentmins[2] = min(start[2], end[2]) - 1;
6850         segmentmaxs[0] = max(start[0], end[0]) + 1;
6851         segmentmaxs[1] = max(start[1], end[1]) + 1;
6852         segmentmaxs[2] = max(start[2], end[2]) + 1;
6853         if (mod_collision_bih.integer)
6854                 Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6855         else if (model->brush.submodel)
6856         {
6857                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6858                         if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6859                                 Collision_TraceLineBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6860                 if (mod_q3bsp_curves_collisions.integer)
6861                         for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6862                                 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6863                                         Collision_TraceLineTriangleMeshFloat(trace, start, end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
6864         }
6865         else
6866                 Mod_Q3BSP_TraceLine_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, 0, 1, start, end, ++markframe, segmentmins, segmentmaxs);
6867 }
6868
6869 static void Mod_Q3BSP_TraceBrush(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, colbrushf_t *start, colbrushf_t *end, int hitsupercontentsmask)
6870 {
6871         float segmentmins[3], segmentmaxs[3];
6872         int i;
6873         msurface_t *surface;
6874         q3mbrush_t *brush;
6875
6876         if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(start->mins, start->maxs) && VectorCompare(end->mins, end->maxs))
6877         {
6878                 if (VectorCompare(start->mins, end->mins))
6879                         Mod_Q3BSP_TracePoint(model, frameblend, skeleton, trace, start->mins, hitsupercontentsmask);
6880                 else
6881                         Mod_Q3BSP_TraceLine(model, frameblend, skeleton, trace, start->mins, end->mins, hitsupercontentsmask);
6882                 return;
6883         }
6884
6885         // box trace, performed as brush trace
6886         memset(trace, 0, sizeof(*trace));
6887         trace->fraction = 1;
6888         trace->realfraction = 1;
6889         trace->hitsupercontentsmask = hitsupercontentsmask;
6890         segmentmins[0] = min(start->mins[0], end->mins[0]);
6891         segmentmins[1] = min(start->mins[1], end->mins[1]);
6892         segmentmins[2] = min(start->mins[2], end->mins[2]);
6893         segmentmaxs[0] = max(start->maxs[0], end->maxs[0]);
6894         segmentmaxs[1] = max(start->maxs[1], end->maxs[1]);
6895         segmentmaxs[2] = max(start->maxs[2], end->maxs[2]);
6896         if (mod_collision_bih.integer)
6897                 Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask);
6898         else if (model->brush.submodel)
6899         {
6900                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6901                         if (brush->colbrushf && BoxesOverlap(segmentmins, segmentmaxs, brush->colbrushf->mins, brush->colbrushf->maxs))
6902                                 Collision_TraceBrushBrushFloat(trace, start, end, brush->colbrushf, brush->colbrushf);
6903                 if (mod_q3bsp_curves_collisions.integer)
6904                         for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
6905                                 if (surface->num_collisiontriangles && BoxesOverlap(segmentmins, segmentmaxs, surface->mins, surface->maxs))
6906                                         Collision_TraceBrushTriangleMeshFloat(trace, start, end, surface->num_collisiontriangles, surface->deprecatedq3data_collisionelement3i, surface->deprecatedq3data_collisionvertex3f, surface->deprecatedq3num_collisionbboxstride, surface->deprecatedq3data_collisionbbox6f, surface->texture->supercontents, surface->texture->surfaceflags, surface->texture, segmentmins, segmentmaxs);
6907         }
6908         else
6909                 Mod_Q3BSP_TraceBrush_RecursiveBSPNode(trace, model, model->brush.data_nodes, start, end, ++markframe, segmentmins, segmentmaxs);
6910 }
6911
6912 static void Mod_Q3BSP_TraceBox(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t boxmins, const vec3_t boxmaxs, const vec3_t end, int hitsupercontentsmask)
6913 {
6914         colboxbrushf_t thisbrush_start, thisbrush_end;
6915         vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
6916
6917         // box trace, performed as brush trace
6918         VectorAdd(start, boxmins, boxstartmins);
6919         VectorAdd(start, boxmaxs, boxstartmaxs);
6920         VectorAdd(end, boxmins, boxendmins);
6921         VectorAdd(end, boxmaxs, boxendmaxs);
6922         Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
6923         Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
6924         Mod_Q3BSP_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask);
6925 }
6926
6927 static int Mod_Q3BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
6928 {
6929         int i;
6930         int supercontents = 0;
6931         q3mbrush_t *brush;
6932         if (mod_collision_bih.integer)
6933         {
6934                 supercontents = Mod_CollisionBIH_PointSuperContents(model, frame, point);
6935         }
6936         // test if the point is inside each brush
6937         else if (model->brush.submodel)
6938         {
6939                 // submodels are effectively one leaf
6940                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
6941                         if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6942                                 supercontents |= brush->colbrushf->supercontents;
6943         }
6944         else
6945         {
6946                 mnode_t *node = model->brush.data_nodes;
6947                 mleaf_t *leaf;
6948                 // find which leaf the point is in
6949                 while (node->plane)
6950                         node = node->children[(node->plane->type < 3 ? point[node->plane->type] : DotProduct(point, node->plane->normal)) < node->plane->dist];
6951                 leaf = (mleaf_t *)node;
6952                 // now check the brushes in the leaf
6953                 for (i = 0;i < leaf->numleafbrushes;i++)
6954                 {
6955                         brush = model->brush.data_brushes + leaf->firstleafbrush[i];
6956                         if (brush->colbrushf && Collision_PointInsideBrushFloat(point, brush->colbrushf))
6957                                 supercontents |= brush->colbrushf->supercontents;
6958                 }
6959         }
6960         return supercontents;
6961 }
6962
6963 void Mod_CollisionBIH_TraceLineAgainstSurfaces(dp_model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask)
6964 {
6965         Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, &model->render_bih);
6966 }
6967
6968
6969 bih_t *Mod_MakeCollisionBIH(dp_model_t *model, qboolean userendersurfaces, bih_t *out)
6970 {
6971         int j;
6972         int bihnumleafs;
6973         int bihmaxnodes;
6974         int brushindex;
6975         int triangleindex;
6976         int bihleafindex;
6977         int nummodelbrushes = model->nummodelbrushes;
6978         int nummodelsurfaces = model->nummodelsurfaces;
6979         const int *e;
6980         const int *collisionelement3i;
6981         const float *collisionvertex3f;
6982         const int *renderelement3i;
6983         const float *rendervertex3f;
6984         bih_leaf_t *bihleafs;
6985         bih_node_t *bihnodes;
6986         int *temp_leafsort;
6987         int *temp_leafsortscratch;
6988         const msurface_t *surface;
6989         const q3mbrush_t *brush;
6990
6991         // find out how many BIH leaf nodes we need
6992         bihnumleafs = 0;
6993         if (userendersurfaces)
6994         {
6995                 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
6996                         bihnumleafs += surface->num_triangles;
6997         }
6998         else
6999         {
7000                 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7001                         if (brush->colbrushf)
7002                                 bihnumleafs++;
7003                 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7004                 {
7005                         if (surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7006                                 bihnumleafs += surface->num_triangles + surface->num_collisiontriangles;
7007                         else
7008                                 bihnumleafs += surface->num_collisiontriangles;
7009                 }
7010         }
7011
7012         if (!bihnumleafs)
7013                 return NULL;
7014
7015         // allocate the memory for the BIH leaf nodes
7016         bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7017
7018         // now populate the BIH leaf nodes
7019         bihleafindex = 0;
7020
7021         // add render surfaces
7022         renderelement3i = model->surfmesh.data_element3i;
7023         rendervertex3f = model->surfmesh.data_vertex3f;
7024         for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7025         {
7026                 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7027                 {
7028                         if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7029                                 continue;
7030                         bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7031                         bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7032                         bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7033                         bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7034                         bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7035                         bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7036                         bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7037                         bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7038                         bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7039                         bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7040                         bihleafindex++;
7041                 }
7042         }
7043
7044         if (!userendersurfaces)
7045         {
7046                 // add collision brushes
7047                 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7048                 {
7049                         if (!brush->colbrushf)
7050                                 continue;
7051                         bihleafs[bihleafindex].type = BIH_BRUSH;
7052                         bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7053                         bihleafs[bihleafindex].surfaceindex = -1;
7054                         bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7055                         VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7056                         VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7057                         bihleafindex++;
7058                 }
7059
7060                 // add collision surfaces
7061                 collisionelement3i = model->brush.data_collisionelement3i;
7062                 collisionvertex3f = model->brush.data_collisionvertex3f;
7063                 for (j = 0, surface = model->data_surfaces + model->firstmodelsurface;j < nummodelsurfaces;j++, surface++)
7064                 {
7065                         for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7066                         {
7067                                 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7068                                 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7069                                 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7070                                 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7071                                 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7072                                 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7073                                 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7074                                 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7075                                 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7076                                 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7077                                 bihleafindex++;
7078                         }
7079                 }
7080         }
7081
7082         // allocate buffers for the produced and temporary data
7083         bihmaxnodes = bihnumleafs + 1;
7084         bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7085         temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7086         temp_leafsortscratch = temp_leafsort + bihnumleafs;
7087
7088         // now build it
7089         BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7090
7091         // we're done with the temporary data
7092         Mem_Free(temp_leafsort);
7093
7094         // resize the BIH nodes array if it over-allocated
7095         if (out->maxnodes > out->numnodes)
7096         {
7097                 out->maxnodes = out->numnodes;
7098                 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7099         }
7100
7101         return out;
7102 }
7103
7104 static int Mod_Q3BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
7105 {
7106         int supercontents = 0;
7107         if (nativecontents & CONTENTSQ3_SOLID)
7108                 supercontents |= SUPERCONTENTS_SOLID;
7109         if (nativecontents & CONTENTSQ3_WATER)
7110                 supercontents |= SUPERCONTENTS_WATER;
7111         if (nativecontents & CONTENTSQ3_SLIME)
7112                 supercontents |= SUPERCONTENTS_SLIME;
7113         if (nativecontents & CONTENTSQ3_LAVA)
7114                 supercontents |= SUPERCONTENTS_LAVA;
7115         if (nativecontents & CONTENTSQ3_BODY)
7116                 supercontents |= SUPERCONTENTS_BODY;
7117         if (nativecontents & CONTENTSQ3_CORPSE)
7118                 supercontents |= SUPERCONTENTS_CORPSE;
7119         if (nativecontents & CONTENTSQ3_NODROP)
7120                 supercontents |= SUPERCONTENTS_NODROP;
7121         if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7122                 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7123         if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7124                 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7125         if (nativecontents & CONTENTSQ3_DONOTENTER)
7126                 supercontents |= SUPERCONTENTS_DONOTENTER;
7127         if (nativecontents & CONTENTSQ3_BOTCLIP)
7128                 supercontents |= SUPERCONTENTS_BOTCLIP;
7129         if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7130                 supercontents |= SUPERCONTENTS_OPAQUE;
7131         return supercontents;
7132 }
7133
7134 static int Mod_Q3BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
7135 {
7136         int nativecontents = 0;
7137         if (supercontents & SUPERCONTENTS_SOLID)
7138                 nativecontents |= CONTENTSQ3_SOLID;
7139         if (supercontents & SUPERCONTENTS_WATER)
7140                 nativecontents |= CONTENTSQ3_WATER;
7141         if (supercontents & SUPERCONTENTS_SLIME)
7142                 nativecontents |= CONTENTSQ3_SLIME;
7143         if (supercontents & SUPERCONTENTS_LAVA)
7144                 nativecontents |= CONTENTSQ3_LAVA;
7145         if (supercontents & SUPERCONTENTS_BODY)
7146                 nativecontents |= CONTENTSQ3_BODY;
7147         if (supercontents & SUPERCONTENTS_CORPSE)
7148                 nativecontents |= CONTENTSQ3_CORPSE;
7149         if (supercontents & SUPERCONTENTS_NODROP)
7150                 nativecontents |= CONTENTSQ3_NODROP;
7151         if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7152                 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7153         if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7154                 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7155         if (supercontents & SUPERCONTENTS_DONOTENTER)
7156                 nativecontents |= CONTENTSQ3_DONOTENTER;
7157         if (supercontents & SUPERCONTENTS_BOTCLIP)
7158                 nativecontents |= CONTENTSQ3_BOTCLIP;
7159         if (!(supercontents & SUPERCONTENTS_OPAQUE))
7160                 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7161         return nativecontents;
7162 }
7163
7164 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7165 {
7166         int numleafs;
7167         while (node->plane)
7168         {
7169                 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7170                 node = node->children[1];
7171         }
7172         numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7173         if (loadmodel->brush.num_leafs < numleafs)
7174                 loadmodel->brush.num_leafs = numleafs;
7175 }
7176
7177 static void Mod_Q3BSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7178 {
7179         int i, j, lumps;
7180         q3dheader_t *header;
7181         float corner[3], yawradius, modelradius;
7182
7183         mod->modeldatatypestring = "Q3BSP";
7184
7185         mod->type = mod_brushq3;
7186         mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7187         mod->numskins = 1;
7188
7189         header = (q3dheader_t *)buffer;
7190         if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7191                 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7192
7193         i = LittleLong(header->version);
7194         if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7195                 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7196
7197         mod->soundfromcenter = true;
7198         mod->TraceBox = Mod_Q3BSP_TraceBox;
7199         mod->TraceBrush = Mod_Q3BSP_TraceBrush;
7200         mod->TraceLine = Mod_Q3BSP_TraceLine;
7201         mod->TracePoint = Mod_Q3BSP_TracePoint;
7202         mod->PointSuperContents = Mod_Q3BSP_PointSuperContents;
7203         mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7204         mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7205         mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7206         mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7207         mod->brush.GetPVS = Mod_Q1BSP_GetPVS;
7208         mod->brush.FatPVS = Mod_Q1BSP_FatPVS;
7209         mod->brush.BoxTouchingPVS = Mod_Q1BSP_BoxTouchingPVS;
7210         mod->brush.BoxTouchingLeafPVS = Mod_Q1BSP_BoxTouchingLeafPVS;
7211         mod->brush.BoxTouchingVisibleLeafs = Mod_Q1BSP_BoxTouchingVisibleLeafs;
7212         mod->brush.FindBoxClusters = Mod_Q1BSP_FindBoxClusters;
7213         mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7214         mod->brush.FindNonSolidLocation = Mod_Q1BSP_FindNonSolidLocation;
7215         mod->brush.AmbientSoundLevelsForPoint = NULL;
7216         mod->brush.RoundUpToHullSize = NULL;
7217         mod->brush.PointInLeaf = Mod_Q1BSP_PointInLeaf;
7218         mod->Draw = R_Q1BSP_Draw;
7219         mod->DrawDepth = R_Q1BSP_DrawDepth;
7220         mod->DrawDebug = R_Q1BSP_DrawDebug;
7221         mod->DrawPrepass = R_Q1BSP_DrawPrepass;
7222         mod->GetLightInfo = R_Q1BSP_GetLightInfo;
7223         mod->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7224         mod->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7225         mod->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7226         mod->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7227         mod->DrawLight = R_Q1BSP_DrawLight;
7228
7229         mod_base = (unsigned char *)header;
7230
7231         // swap all the lumps
7232         header->ident = LittleLong(header->ident);
7233         header->version = LittleLong(header->version);
7234         lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7235         for (i = 0;i < lumps;i++)
7236         {
7237                 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7238                 if((char *) bufferend < (char *) buffer + j)
7239                         Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7240                 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7241                 if((char *) bufferend < (char *) buffer + j)
7242                         Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7243         }
7244         /*
7245          * NO, do NOT clear them!
7246          * they contain actual data referenced by other stuff.
7247          * Instead, before using the advertisements lump, check header->versio
7248          * again!
7249          * Sorry, but otherwise it breaks memory of the first lump.
7250         for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7251         {
7252                 header->lumps[i].fileofs = 0;
7253                 header->lumps[i].filelen = 0;
7254         }
7255         */
7256
7257         mod->brush.qw_md4sum = 0;
7258         mod->brush.qw_md4sum2 = 0;
7259         for (i = 0;i < lumps;i++)
7260         {
7261                 if (i == Q3LUMP_ENTITIES)
7262                         continue;
7263                 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7264                 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7265                         continue;
7266                 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7267
7268                 // all this checksumming can take a while, so let's send keepalives here too
7269                 CL_KeepaliveMessage(false);
7270         }
7271
7272         Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7273         Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7274         Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7275         if (header->version == Q3BSPVERSION_IG)
7276                 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7277         else
7278                 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7279         Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7280         Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7281         Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7282         Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7283         Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7284         Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7285         Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7286         Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7287         Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7288         Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7289         Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7290         Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7291         Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7292         loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7293
7294         // the MakePortals code works fine on the q3bsp data as well
7295         if (mod_bsp_portalize.integer)
7296                 Mod_Q1BSP_MakePortals();
7297
7298         // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7299         loadmodel->brush.supportwateralpha = true;
7300
7301         // make a single combined shadow mesh to allow optimized shadow volume creation
7302         Mod_Q1BSP_CreateShadowMesh(loadmodel);
7303
7304         loadmodel->brush.num_leafs = 0;
7305         Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7306
7307         if (loadmodel->brush.numsubmodels)
7308                 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7309
7310         mod = loadmodel;
7311         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7312         {
7313                 if (i > 0)
7314                 {
7315                         char name[10];
7316                         // duplicate the basic information
7317                         dpsnprintf(name, sizeof(name), "*%i", i);
7318                         mod = Mod_FindName(name, loadmodel->name);
7319                         // copy the base model to this one
7320                         *mod = *loadmodel;
7321                         // rename the clone back to its proper name
7322                         strlcpy(mod->name, name, sizeof(mod->name));
7323                         mod->brush.parentmodel = loadmodel;
7324                         // textures and memory belong to the main model
7325                         mod->texturepool = NULL;
7326                         mod->mempool = NULL;
7327                         mod->brush.GetPVS = NULL;
7328                         mod->brush.FatPVS = NULL;
7329                         mod->brush.BoxTouchingPVS = NULL;
7330                         mod->brush.BoxTouchingLeafPVS = NULL;
7331                         mod->brush.BoxTouchingVisibleLeafs = NULL;
7332                         mod->brush.FindBoxClusters = NULL;
7333                         mod->brush.LightPoint = NULL;
7334                         mod->brush.AmbientSoundLevelsForPoint = NULL;
7335                 }
7336                 mod->brush.submodel = i;
7337                 if (loadmodel->brush.submodels)
7338                         loadmodel->brush.submodels[i] = mod;
7339
7340                 // make the model surface list (used by shadowing/lighting)
7341                 mod->firstmodelsurface = mod->brushq3.data_models[i].firstface;
7342                 mod->nummodelsurfaces = mod->brushq3.data_models[i].numfaces;
7343                 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7344                 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7345                 mod->sortedmodelsurfaces = (int *)Mem_Alloc(loadmodel->mempool, mod->nummodelsurfaces * sizeof(*mod->sortedmodelsurfaces));
7346                 Mod_MakeSortedSurfaces(mod);
7347
7348                 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7349                 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7350                 // enlarge the bounding box to enclose all geometry of this model,
7351                 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7352                 // which can in turn mess up the farclip (as well as culling when
7353                 // outside the level - an unimportant concern)
7354
7355                 //printf("Editing model %d... BEFORE re-bounding: %f %f %f - %f %f %f\n", i, mod->normalmins[0], mod->normalmins[1], mod->normalmins[2], mod->normalmaxs[0], mod->normalmaxs[1], mod->normalmaxs[2]);
7356                 for (j = 0;j < mod->nummodelsurfaces;j++)
7357                 {
7358                         const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
7359                         const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7360                         int k;
7361                         if (!surface->num_vertices)
7362                                 continue;
7363                         for (k = 0;k < surface->num_vertices;k++, v += 3)
7364                         {
7365                                 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7366                                 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7367                                 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7368                                 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7369                                 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7370                                 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7371                         }
7372                 }
7373                 //printf("Editing model %d... AFTER re-bounding: %f %f %f - %f %f %f\n", i, mod->normalmins[0], mod->normalmins[1], mod->normalmins[2], mod->normalmaxs[0], mod->normalmaxs[1], mod->normalmaxs[2]);
7374                 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7375                 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7376                 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7377                 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7378                 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7379                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7380                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7381                 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7382                 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7383                 mod->yawmins[2] = mod->normalmins[2];
7384                 mod->yawmaxs[2] = mod->normalmaxs[2];
7385                 mod->radius = modelradius;
7386                 mod->radius2 = modelradius * modelradius;
7387
7388                 // this gets altered below if sky or water is used
7389                 mod->DrawSky = NULL;
7390                 mod->DrawAddWaterPlanes = NULL;
7391
7392                 for (j = 0;j < mod->nummodelsurfaces;j++)
7393                         if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
7394                                 break;
7395                 if (j < mod->nummodelsurfaces)
7396                         mod->DrawSky = R_Q1BSP_DrawSky;
7397
7398                 for (j = 0;j < mod->nummodelsurfaces;j++)
7399                         if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
7400                                 break;
7401                 if (j < mod->nummodelsurfaces)
7402                         mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
7403
7404                 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7405                 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7406
7407                 // generate VBOs and other shared data before cloning submodels
7408                 if (i == 0)
7409                         Mod_BuildVBOs();
7410         }
7411
7412         if (mod_q3bsp_sRGBlightmaps.integer)
7413         {
7414                 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
7415                 {
7416                         // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
7417                         // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
7418                         // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
7419                         // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
7420                         //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
7421                 }
7422                 else // if this is NOT set, regular rendering looks right by this requirement anyway
7423                 {
7424                         /*
7425                         // we want color 1 to do the same as without sRGB
7426                         // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
7427                         loadmodel->lightmapscale *= 2.476923f; // fixes max level
7428                         */
7429
7430                         // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
7431                         // we need to undo that
7432                         loadmodel->lightmapscale *= 2.336f; // fixes neutral level
7433                 }
7434         }
7435
7436         Con_DPrintf("Stats for q3bsp model \"%s\": %i faces, %i nodes, %i leafs, %i clusters, %i clusterportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
7437 }
7438
7439 void Mod_IBSP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7440 {
7441         int i = LittleLong(((int *)buffer)[1]);
7442         if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7443                 Mod_Q3BSP_Load(mod,buffer, bufferend);
7444         else if (i == Q2BSPVERSION)
7445                 Mod_Q2BSP_Load(mod,buffer, bufferend);
7446         else
7447                 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7448 }
7449
7450 void Mod_MAP_Load(dp_model_t *mod, void *buffer, void *bufferend)
7451 {
7452         Host_Error("Mod_MAP_Load: not yet implemented");
7453 }
7454
7455 typedef struct objvertex_s
7456 {
7457         int nextindex;
7458         int submodelindex;
7459         int textureindex;
7460         float v[3];
7461         float vt[2];
7462         float vn[3];
7463 }
7464 objvertex_t;
7465
7466 static unsigned char nobsp_pvs[1] = {1};
7467
7468 void Mod_OBJ_Load(dp_model_t *mod, void *buffer, void *bufferend)
7469 {
7470         const char *textbase = (char *)buffer, *text = textbase;
7471         char *s;
7472         char *argv[512];
7473         char line[1024];
7474         char materialname[MAX_QPATH];
7475         int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
7476         int index1, index2, index3;
7477         objvertex_t vfirst, vprev, vcurrent;
7478         int argc;
7479         int linelen;
7480         int numtriangles = 0;
7481         int maxtriangles = 0;
7482         objvertex_t *vertices = NULL;
7483         int linenumber = 0;
7484         int maxtextures = 0, numtextures = 0, textureindex = 0;
7485         int maxv = 0, numv = 1;
7486         int maxvt = 0, numvt = 1;
7487         int maxvn = 0, numvn = 1;
7488         char *texturenames = NULL;
7489         float dist, modelradius, modelyawradius, yawradius;
7490         float *v = NULL;
7491         float *vt = NULL;
7492         float *vn = NULL;
7493         float mins[3];
7494         float maxs[3];
7495         float corner[3];
7496         objvertex_t *thisvertex = NULL;
7497         int vertexhashindex;
7498         int *vertexhashtable = NULL;
7499         objvertex_t *vertexhashdata = NULL;
7500         objvertex_t *vdata = NULL;
7501         int vertexhashsize = 0;
7502         int vertexhashcount = 0;
7503         skinfile_t *skinfiles = NULL;
7504         unsigned char *data = NULL;
7505         int *submodelfirstsurface;
7506         msurface_t *surface;
7507         msurface_t *tempsurfaces;
7508
7509         memset(&vfirst, 0, sizeof(vfirst));
7510         memset(&vprev, 0, sizeof(vprev));
7511         memset(&vcurrent, 0, sizeof(vcurrent));
7512
7513         dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
7514
7515         loadmodel->modeldatatypestring = "OBJ";
7516
7517         loadmodel->type = mod_obj;
7518         loadmodel->soundfromcenter = true;
7519         loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
7520         loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
7521         loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
7522         loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
7523         loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7524         loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
7525         loadmodel->brush.TraceLineOfSight = NULL;
7526         loadmodel->brush.SuperContentsFromNativeContents = NULL;
7527         loadmodel->brush.NativeContentsFromSuperContents = NULL;
7528         loadmodel->brush.GetPVS = NULL;
7529         loadmodel->brush.FatPVS = NULL;
7530         loadmodel->brush.BoxTouchingPVS = NULL;
7531         loadmodel->brush.BoxTouchingLeafPVS = NULL;
7532         loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
7533         loadmodel->brush.FindBoxClusters = NULL;
7534         loadmodel->brush.LightPoint = NULL;
7535         loadmodel->brush.FindNonSolidLocation = NULL;
7536         loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
7537         loadmodel->brush.RoundUpToHullSize = NULL;
7538         loadmodel->brush.PointInLeaf = NULL;
7539         loadmodel->Draw = R_Q1BSP_Draw;
7540         loadmodel->DrawDepth = R_Q1BSP_DrawDepth;
7541         loadmodel->DrawDebug = R_Q1BSP_DrawDebug;
7542         loadmodel->DrawPrepass = R_Q1BSP_DrawPrepass;
7543         loadmodel->GetLightInfo = R_Q1BSP_GetLightInfo;
7544         loadmodel->CompileShadowMap = R_Q1BSP_CompileShadowMap;
7545         loadmodel->DrawShadowMap = R_Q1BSP_DrawShadowMap;
7546         loadmodel->CompileShadowVolume = R_Q1BSP_CompileShadowVolume;
7547         loadmodel->DrawShadowVolume = R_Q1BSP_DrawShadowVolume;
7548         loadmodel->DrawLight = R_Q1BSP_DrawLight;
7549
7550         skinfiles = Mod_LoadSkinFiles();
7551         if (loadmodel->numskins < 1)
7552                 loadmodel->numskins = 1;
7553
7554         // make skinscenes for the skins (no groups)
7555         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
7556         for (i = 0;i < loadmodel->numskins;i++)
7557         {
7558                 loadmodel->skinscenes[i].firstframe = i;
7559                 loadmodel->skinscenes[i].framecount = 1;
7560                 loadmodel->skinscenes[i].loop = true;
7561                 loadmodel->skinscenes[i].framerate = 10;
7562         }
7563
7564         VectorClear(mins);
7565         VectorClear(maxs);
7566
7567         // we always have model 0, i.e. the first "submodel"
7568         loadmodel->brush.numsubmodels = 1;
7569
7570         // parse the OBJ text now
7571         for(;;)
7572         {
7573                 static char emptyarg[1] = "";
7574                 if (!*text)
7575                         break;
7576                 linenumber++;
7577                 linelen = 0;
7578                 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
7579                         line[linelen] = text[linelen];
7580                 line[linelen] = 0;
7581                 for (argc = 0;argc < 4;argc++)
7582                         argv[argc] = emptyarg;
7583                 argc = 0;
7584                 s = line;
7585                 while (*s == ' ' || *s == '\t')
7586                         s++;
7587                 while (*s)
7588                 {
7589                         argv[argc++] = s;
7590                         while (*s > ' ')
7591                                 s++;
7592                         if (!*s)
7593                                 break;
7594                         *s++ = 0;
7595                         while (*s == ' ' || *s == '\t')
7596                                 s++;
7597                 }
7598                 text += linelen;
7599                 if (*text == '\r')
7600                         text++;
7601                 if (*text == '\n')
7602                         text++;
7603                 if (!argc)
7604                         continue;
7605                 if (argv[0][0] == '#')
7606                         continue;
7607                 if (!strcmp(argv[0], "v"))
7608                 {
7609                         if (maxv <= numv)
7610                         {
7611                                 maxv = max(maxv * 2, 1024);
7612                                 v = (float *)Mem_Realloc(tempmempool, v, maxv * sizeof(float[3]));
7613                         }
7614                         if(mod_obj_orientation.integer)
7615                         {
7616                                 v[numv*3+0] = atof(argv[1]);
7617                                 v[numv*3+2] = atof(argv[2]);
7618                                 v[numv*3+1] = atof(argv[3]);
7619                         }
7620                         else
7621                         {
7622                                 v[numv*3+0] = atof(argv[1]);
7623                                 v[numv*3+1] = atof(argv[2]);
7624                                 v[numv*3+2] = atof(argv[3]);
7625                         }
7626                         numv++;
7627                 }
7628                 else if (!strcmp(argv[0], "vt"))
7629                 {
7630                         if (maxvt <= numvt)
7631                         {
7632                                 maxvt = max(maxvt * 2, 1024);
7633                                 vt = (float *)Mem_Realloc(tempmempool, vt, maxvt * sizeof(float[2]));
7634                         }
7635                         vt[numvt*2+0] = atof(argv[1]);
7636                         vt[numvt*2+1] = 1-atof(argv[2]);
7637                         numvt++;
7638                 }
7639                 else if (!strcmp(argv[0], "vn"))
7640                 {
7641                         if (maxvn <= numvn)
7642                         {
7643                                 maxvn = max(maxvn * 2, 1024);
7644                                 vn = (float *)Mem_Realloc(tempmempool, vn, maxvn * sizeof(float[3]));
7645                         }
7646                         if(mod_obj_orientation.integer)
7647                         {
7648                                 vn[numvn*3+0] = atof(argv[1]);
7649                                 vn[numvn*3+2] = atof(argv[2]);
7650                                 vn[numvn*3+1] = atof(argv[3]);
7651                         }
7652                         else
7653                         {
7654                                 vn[numvn*3+0] = atof(argv[1]);
7655                                 vn[numvn*3+1] = atof(argv[2]);
7656                                 vn[numvn*3+2] = atof(argv[3]);
7657                         }
7658                         numvn++;
7659                 }
7660                 else if (!strcmp(argv[0], "f"))
7661                 {
7662                         if (!numtextures)
7663                         {
7664                                 if (maxtextures <= numtextures)
7665                                 {
7666                                         maxtextures = max(maxtextures * 2, 256);
7667                                         texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7668                                 }
7669                                 textureindex = numtextures++;
7670                                 strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
7671                         }
7672                         for (j = 1;j < argc;j++)
7673                         {
7674                                 index1 = atoi(argv[j]);
7675                                 while(argv[j][0] && argv[j][0] != '/')
7676                                         argv[j]++;
7677                                 if (argv[j][0])
7678                                         argv[j]++;
7679                                 index2 = atoi(argv[j]);
7680                                 while(argv[j][0] && argv[j][0] != '/')
7681                                         argv[j]++;
7682                                 if (argv[j][0])
7683                                         argv[j]++;
7684                                 index3 = atoi(argv[j]);
7685                                 // negative refers to a recent vertex
7686                                 // zero means not specified
7687                                 // positive means an absolute vertex index
7688                                 if (index1 < 0)
7689                                         index1 = numv - index1;
7690                                 if (index2 < 0)
7691                                         index2 = numvt - index2;
7692                                 if (index3 < 0)
7693                                         index3 = numvn - index3;
7694                                 vcurrent.nextindex = -1;
7695                                 vcurrent.textureindex = textureindex;
7696                                 vcurrent.submodelindex = submodelindex;
7697                                 if (v && index1 >= 0 && index1 < numv)
7698                                         VectorCopy(v + 3*index1, vcurrent.v);
7699                                 if (vt && index2 >= 0 && index2 < numvt)
7700                                         Vector2Copy(vt + 2*index2, vcurrent.vt);
7701                                 if (vn && index3 >= 0 && index3 < numvn)
7702                                         VectorCopy(vn + 3*index3, vcurrent.vn);
7703                                 if (numtriangles == 0)
7704                                 {
7705                                         VectorCopy(vcurrent.v, mins);
7706                                         VectorCopy(vcurrent.v, maxs);
7707                                 }
7708                                 else
7709                                 {
7710                                         mins[0] = min(mins[0], vcurrent.v[0]);
7711                                         mins[1] = min(mins[1], vcurrent.v[1]);
7712                                         mins[2] = min(mins[2], vcurrent.v[2]);
7713                                         maxs[0] = max(maxs[0], vcurrent.v[0]);
7714                                         maxs[1] = max(maxs[1], vcurrent.v[1]);
7715                                         maxs[2] = max(maxs[2], vcurrent.v[2]);
7716                                 }
7717                                 if (j == 1)
7718                                         vfirst = vcurrent;
7719                                 else if (j >= 3)
7720                                 {
7721                                         if (maxtriangles <= numtriangles)
7722                                         {
7723                                                 maxtriangles = max(maxtriangles * 2, 32768);
7724                                                 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
7725                                         }
7726                                         if(mod_obj_orientation.integer)
7727                                         {
7728                                                 vertices[numtriangles*3+0] = vfirst;
7729                                                 vertices[numtriangles*3+1] = vprev;
7730                                                 vertices[numtriangles*3+2] = vcurrent;
7731                                         }
7732                                         else
7733                                         {
7734                                                 vertices[numtriangles*3+0] = vfirst;
7735                                                 vertices[numtriangles*3+2] = vprev;
7736                                                 vertices[numtriangles*3+1] = vcurrent;
7737                                         }
7738                                         numtriangles++;
7739                                 }
7740                                 vprev = vcurrent;
7741                         }
7742                 }
7743                 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
7744                 {
7745                         submodelindex = atof(argv[1]);
7746                         loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
7747                 }
7748                 else if (!strcmp(argv[0], "usemtl"))
7749                 {
7750                         for (i = 0;i < numtextures;i++)
7751                                 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
7752                                         break;
7753                         if (i < numtextures)
7754                                 textureindex = i;
7755                         else
7756                         {
7757                                 if (maxtextures <= numtextures)
7758                                 {
7759                                         maxtextures = max(maxtextures * 2, 256);
7760                                         texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
7761                                 }
7762                                 textureindex = numtextures++;
7763                                 strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
7764                         }
7765                 }
7766         }
7767
7768         // now that we have the OBJ data loaded as-is, we can convert it
7769
7770         // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
7771         VectorCopy(mins, loadmodel->normalmins);
7772         VectorCopy(maxs, loadmodel->normalmaxs);
7773         dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
7774         modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
7775         modelyawradius = dist*dist+modelyawradius*modelyawradius;
7776         modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
7777         modelradius = modelyawradius + modelradius * modelradius;
7778         modelyawradius = sqrt(modelyawradius);
7779         modelradius = sqrt(modelradius);
7780         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
7781         loadmodel->yawmins[2] = loadmodel->normalmins[2];
7782         loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] =  modelyawradius;
7783         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
7784         loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
7785         loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] =  modelradius;
7786         loadmodel->radius = modelradius;
7787         loadmodel->radius2 = modelradius * modelradius;
7788
7789         // allocate storage for triangles
7790         loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
7791         // allocate vertex hash structures to build an optimal vertex subset
7792         vertexhashsize = numtriangles*2;
7793         vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
7794         memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
7795         vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
7796         vertexhashcount = 0;
7797
7798         // gather surface stats for assigning vertex/triangle ranges
7799         firstvertex = 0;
7800         firsttriangle = 0;
7801         elementindex = 0;
7802         loadmodel->num_surfaces = 0;
7803         // allocate storage for the worst case number of surfaces, later we resize
7804         tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
7805         submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
7806         surface = tempsurfaces;
7807         for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
7808         {
7809                 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7810                 for (textureindex = 0;textureindex < numtextures;textureindex++)
7811                 {
7812                         for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
7813                         {
7814                                 thisvertex = vertices + vertexindex;
7815                                 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
7816                                         break;
7817                         }
7818                         // skip the surface creation if there are no triangles for it
7819                         if (vertexindex == numtriangles*3)
7820                                 continue;
7821                         // create a surface for these vertices
7822                         surfacevertices = 0;
7823                         surfaceelements = 0;
7824                         // we hack in a texture index in the surface to be fixed up later...
7825                         surface->texture = (texture_t *)((size_t)textureindex);
7826                         // calculate bounds as we go
7827                         VectorCopy(thisvertex->v, surface->mins);
7828                         VectorCopy(thisvertex->v, surface->maxs);
7829                         for (;vertexindex < numtriangles*3;vertexindex++)
7830                         {
7831                                 thisvertex = vertices + vertexindex;
7832                                 if (thisvertex->submodelindex != submodelindex)
7833                                         continue;
7834                                 if (thisvertex->textureindex != textureindex)
7835                                         continue;
7836                                 // add vertex to surface bounds
7837                                 surface->mins[0] = min(surface->mins[0], thisvertex->v[0]);
7838                                 surface->mins[1] = min(surface->mins[1], thisvertex->v[1]);
7839                                 surface->mins[2] = min(surface->mins[2], thisvertex->v[2]);
7840                                 surface->maxs[0] = max(surface->maxs[0], thisvertex->v[0]);
7841                                 surface->maxs[1] = max(surface->maxs[1], thisvertex->v[1]);
7842                                 surface->maxs[2] = max(surface->maxs[2], thisvertex->v[2]);
7843                                 // add the vertex if it is not found in the merged set, and
7844                                 // get its index (triangle element) for the surface
7845                                 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
7846                                 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
7847                                 {
7848                                         vdata = vertexhashdata + i;
7849                                         if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
7850                                                 break;
7851                                 }
7852                                 if (i < 0)
7853                                 {
7854                                         i = vertexhashcount++;
7855                                         vdata = vertexhashdata + i;
7856                                         *vdata = *thisvertex;
7857                                         vdata->nextindex = vertexhashtable[vertexhashindex];
7858                                         vertexhashtable[vertexhashindex] = i;
7859                                         surfacevertices++;
7860                                 }
7861                                 loadmodel->surfmesh.data_element3i[elementindex++] = i;
7862                                 surfaceelements++;
7863                         }
7864                         surfacetriangles = surfaceelements / 3;
7865                         surface->num_vertices = surfacevertices;
7866                         surface->num_triangles = surfacetriangles;
7867                         surface->num_firstvertex = firstvertex;
7868                         surface->num_firsttriangle = firsttriangle;
7869                         firstvertex += surface->num_vertices;
7870                         firsttriangle += surface->num_triangles;
7871                         surface++;
7872                         loadmodel->num_surfaces++;
7873                 }
7874         }
7875         submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
7876         numvertices = firstvertex;
7877         loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
7878         tempsurfaces = NULL;
7879
7880         // allocate storage for final mesh data
7881         loadmodel->num_textures = numtextures * loadmodel->numskins;
7882         loadmodel->num_texturesperskin = numtextures;
7883         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + numtriangles * sizeof(int[3]) + (numvertices <= 65536 ? numtriangles * sizeof(unsigned short[3]) : 0) + (r_enableshadowvolumes.integer ? numtriangles * sizeof(int[3]) : 0) + numvertices * sizeof(float[14]) + loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7884         loadmodel->brush.submodels = (dp_model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(dp_model_t *);
7885         loadmodel->sortedmodelsurfaces = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
7886         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
7887         loadmodel->surfmesh.num_vertices = numvertices;
7888         loadmodel->surfmesh.num_triangles = numtriangles;
7889         if (r_enableshadowvolumes.integer)
7890                 loadmodel->surfmesh.data_neighbor3i = (int *)data;data += numtriangles * sizeof(int[3]);
7891         loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
7892         loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
7893         loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
7894         loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
7895         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
7896         if (loadmodel->surfmesh.num_vertices <= 65536)
7897                 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
7898
7899         for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
7900         {
7901                 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
7902                 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
7903                 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
7904         }
7905
7906         // load the textures
7907         for (textureindex = 0;textureindex < numtextures;textureindex++)
7908                 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
7909         Mod_FreeSkinFiles(skinfiles);
7910
7911         // set the surface textures to their real values now that we loaded them...
7912         for (i = 0;i < loadmodel->num_surfaces;i++)
7913                 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
7914
7915         // free data
7916         Mem_Free(vertices);
7917         Mem_Free(texturenames);
7918         Mem_Free(v);
7919         Mem_Free(vt);
7920         Mem_Free(vn);
7921         Mem_Free(vertexhashtable);
7922         Mem_Free(vertexhashdata);
7923
7924         // make a single combined shadow mesh to allow optimized shadow volume creation
7925         Mod_Q1BSP_CreateShadowMesh(loadmodel);
7926
7927         // compute all the mesh information that was not loaded from the file
7928         if (loadmodel->surfmesh.data_element3s)
7929                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
7930                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
7931         Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
7932         // generate normals if the file did not have them
7933         if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
7934                 Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, r_smoothnormals_areaweighting.integer != 0);
7935         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
7936         if (loadmodel->surfmesh.data_neighbor3i)
7937                 Mod_BuildTriangleNeighbors(loadmodel->surfmesh.data_neighbor3i, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.num_triangles);
7938
7939         // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
7940         loadmodel->brush.num_visleafs = 1;
7941         loadmodel->brush.num_leafs = 1;
7942         loadmodel->brush.num_nodes = 0;
7943         loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
7944         loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
7945         loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
7946         loadmodel->brush.num_pvsclusters = 1;
7947         loadmodel->brush.num_pvsclusterbytes = 1;
7948         loadmodel->brush.data_pvsclusters = nobsp_pvs;
7949         //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
7950         //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
7951         loadmodel->brush.data_leafsurfaces = loadmodel->sortedmodelsurfaces;
7952         VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
7953         VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
7954         loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
7955         loadmodel->brush.data_leafs->clusterindex = 0;
7956         loadmodel->brush.data_leafs->areaindex = 0;
7957         loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
7958         loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
7959         loadmodel->brush.data_leafs->numleafbrushes = 0;
7960         loadmodel->brush.data_leafs->firstleafbrush = NULL;
7961         loadmodel->brush.supportwateralpha = true;
7962
7963         if (loadmodel->brush.numsubmodels)
7964                 loadmodel->brush.submodels = (dp_model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(dp_model_t *));
7965
7966         mod = loadmodel;
7967         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7968         {
7969                 if (i > 0)
7970                 {
7971                         char name[10];
7972                         // duplicate the basic information
7973                         dpsnprintf(name, sizeof(name), "*%i", i);
7974                         mod = Mod_FindName(name, loadmodel->name);
7975                         // copy the base model to this one
7976                         *mod = *loadmodel;
7977                         // rename the clone back to its proper name
7978                         strlcpy(mod->name, name, sizeof(mod->name));
7979                         mod->brush.parentmodel = loadmodel;
7980                         // textures and memory belong to the main model
7981                         mod->texturepool = NULL;
7982                         mod->mempool = NULL;
7983                         mod->brush.GetPVS = NULL;
7984                         mod->brush.FatPVS = NULL;
7985                         mod->brush.BoxTouchingPVS = NULL;
7986                         mod->brush.BoxTouchingLeafPVS = NULL;
7987                         mod->brush.BoxTouchingVisibleLeafs = NULL;
7988                         mod->brush.FindBoxClusters = NULL;
7989                         mod->brush.LightPoint = NULL;
7990                         mod->brush.AmbientSoundLevelsForPoint = NULL;
7991                 }
7992                 mod->brush.submodel = i;
7993                 if (loadmodel->brush.submodels)
7994                         loadmodel->brush.submodels[i] = mod;
7995
7996                 // make the model surface list (used by shadowing/lighting)
7997                 mod->firstmodelsurface = submodelfirstsurface[i];
7998                 mod->nummodelsurfaces = submodelfirstsurface[i+1] - submodelfirstsurface[i];
7999                 mod->firstmodelbrush = 0;
8000                 mod->nummodelbrushes = 0;
8001                 mod->sortedmodelsurfaces = loadmodel->sortedmodelsurfaces + mod->firstmodelsurface;
8002                 Mod_MakeSortedSurfaces(mod);
8003
8004                 VectorClear(mod->normalmins);
8005                 VectorClear(mod->normalmaxs);
8006                 l = false;
8007                 for (j = 0;j < mod->nummodelsurfaces;j++)
8008                 {
8009                         const msurface_t *surface = mod->data_surfaces + j + mod->firstmodelsurface;
8010                         const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8011                         int k;
8012                         if (!surface->num_vertices)
8013                                 continue;
8014                         if (!l)
8015                         {
8016                                 l = true;
8017                                 VectorCopy(v, mod->normalmins);
8018                                 VectorCopy(v, mod->normalmaxs);
8019                         }
8020                         for (k = 0;k < surface->num_vertices;k++, v += 3)
8021                         {
8022                                 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
8023                                 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
8024                                 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
8025                                 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
8026                                 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
8027                                 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
8028                         }
8029                 }
8030                 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8031                 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8032                 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8033                 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8034                 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8035                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8036                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8037                 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8038                 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8039                 mod->yawmins[2] = mod->normalmins[2];
8040                 mod->yawmaxs[2] = mod->normalmaxs[2];
8041                 mod->radius = modelradius;
8042                 mod->radius2 = modelradius * modelradius;
8043
8044                 // this gets altered below if sky or water is used
8045                 mod->DrawSky = NULL;
8046                 mod->DrawAddWaterPlanes = NULL;
8047
8048                 for (j = 0;j < mod->nummodelsurfaces;j++)
8049                         if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & MATERIALFLAG_SKY)
8050                                 break;
8051                 if (j < mod->nummodelsurfaces)
8052                         mod->DrawSky = R_Q1BSP_DrawSky;
8053
8054                 for (j = 0;j < mod->nummodelsurfaces;j++)
8055                         if (mod->data_surfaces[j + mod->firstmodelsurface].texture->basematerialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA))
8056                                 break;
8057                 if (j < mod->nummodelsurfaces)
8058                         mod->DrawAddWaterPlanes = R_Q1BSP_DrawAddWaterPlanes;
8059
8060                 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8061                 mod->render_bih = mod->collision_bih;
8062
8063                 // generate VBOs and other shared data before cloning submodels
8064                 if (i == 0)
8065                         Mod_BuildVBOs();
8066         }
8067         mod = loadmodel;
8068         Mem_Free(submodelfirstsurface);
8069
8070         Con_DPrintf("Stats for obj model \"%s\": %i faces, %i nodes, %i leafs, %i clusters, %i clusterportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
8071 }