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