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