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