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