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