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