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