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