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