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