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