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