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