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