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