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