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