Fix a couple warnings for unused variables in listdirectory on WIN32.
[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_q2bsp_littransparentsurfaces = {0, "mod_q2bsp_littransparentsurfaces", "0", "allows lighting on rain in 3v3gloom3 and other cases of transparent surfaces that have lightmaps that were ignored by quake2"};
46 cvar_t mod_q3bsp_curves_collisions = {0, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
47 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)"};
48 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)"};
49 cvar_t mod_q3bsp_optimizedtraceline = {0, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
50 cvar_t mod_q3bsp_debugtracebrush = {0, "mod_q3bsp_debugtracebrush", "0", "selects different tracebrush bsp recursion algorithms (for debugging purposes only)"};
51 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, ..."};
52 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)"};
53 cvar_t mod_q3bsp_tracelineofsight_brushes = {0, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
54 cvar_t mod_q3bsp_sRGBlightmaps = {0, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
55 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"};
56 cvar_t mod_q3shader_default_offsetmapping_scale = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
57 cvar_t mod_q3shader_default_offsetmapping_bias = {CVAR_SAVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
58 cvar_t mod_q3shader_default_polygonfactor = {0, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
59 cvar_t mod_q3shader_default_polygonoffset = {0, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
60 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"};
61 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"};
62
63 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)"};
64 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"};
65 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"};
66
67 static texture_t mod_q1bsp_texture_solid;
68 static texture_t mod_q1bsp_texture_sky;
69 static texture_t mod_q1bsp_texture_lava;
70 static texture_t mod_q1bsp_texture_slime;
71 static texture_t mod_q1bsp_texture_water;
72
73 static qboolean Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end);
74
75 void Mod_BrushInit(void)
76 {
77 //      Cvar_RegisterVariable(&r_subdivide_size);
78         Cvar_RegisterVariable(&mod_bsp_portalize);
79         Cvar_RegisterVariable(&r_novis);
80         Cvar_RegisterVariable(&r_nosurftextures);
81         Cvar_RegisterVariable(&r_subdivisions_tolerance);
82         Cvar_RegisterVariable(&r_subdivisions_mintess);
83         Cvar_RegisterVariable(&r_subdivisions_maxtess);
84         Cvar_RegisterVariable(&r_subdivisions_maxvertices);
85         Cvar_RegisterVariable(&r_subdivisions_collision_tolerance);
86         Cvar_RegisterVariable(&r_subdivisions_collision_mintess);
87         Cvar_RegisterVariable(&r_subdivisions_collision_maxtess);
88         Cvar_RegisterVariable(&r_subdivisions_collision_maxvertices);
89         Cvar_RegisterVariable(&r_trippy);
90         Cvar_RegisterVariable(&r_fxaa);
91         Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
92         Cvar_RegisterVariable(&mod_obj_orientation);
93         Cvar_RegisterVariable(&mod_q2bsp_littransparentsurfaces);
94         Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
95         Cvar_RegisterVariable(&mod_q3bsp_curves_collisions_stride);
96         Cvar_RegisterVariable(&mod_q3bsp_curves_stride);
97         Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
98         Cvar_RegisterVariable(&mod_q3bsp_debugtracebrush);
99         Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
100         Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
101         Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
102         Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
103         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
104         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
105         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
106         Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
107         Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
108         Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
109         Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
110         Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
111         Cvar_RegisterVariable(&mod_collision_bih);
112         Cvar_RegisterVariable(&mod_recalculatenodeboxes);
113
114         // these games were made for older DP engines and are no longer
115         // maintained; use this hack to show their textures properly
116         if(gamemode == GAME_NEXUIZ)
117                 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
118
119         memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
120         strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
121         mod_q1bsp_texture_solid.surfaceflags = 0;
122         mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
123
124         mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
125         strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
126         mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
127         mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
128
129         mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
130         strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
131         mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
132         mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
133
134         mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
135         strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
136         mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
137         mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
138
139         mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
140         strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
141         mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
142         mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
143 }
144
145 static mleaf_t *Mod_Q1BSP_PointInLeaf(dp_model_t *model, const vec3_t p)
146 {
147         mnode_t *node;
148
149         if (model == NULL)
150                 return NULL;
151
152         // LordHavoc: modified to start at first clip node,
153         // in other words: first node of the (sub)model
154         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
155         while (node->plane)
156                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
157
158         return (mleaf_t *)node;
159 }
160
161 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(dp_model_t *model, const vec3_t p, unsigned char *out, int outsize)
162 {
163         int i;
164         mleaf_t *leaf;
165         leaf = Mod_Q1BSP_PointInLeaf(model, p);
166         if (leaf)
167         {
168                 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
169                 if (i)
170                 {
171                         memcpy(out, leaf->ambient_sound_level, i);
172                         out += i;
173                         outsize -= i;
174                 }
175         }
176         if (outsize)
177                 memset(out, 0, outsize);
178 }
179
180 static int Mod_Q1BSP_FindBoxClusters(dp_model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
181 {
182         int numclusters = 0;
183         int nodestackindex = 0;
184         mnode_t *node, *nodestack[1024];
185         if (!model->brush.num_pvsclusters)
186                 return -1;
187         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
188         for (;;)
189         {
190 #if 1
191                 if (node->plane)
192                 {
193                         // node - recurse down the BSP tree
194                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
195                         if (sides < 3)
196                         {
197                                 if (sides == 0)
198                                         return -1; // ERROR: NAN bounding box!
199                                 // box is on one side of plane, take that path
200                                 node = node->children[sides-1];
201                         }
202                         else
203                         {
204                                 // box crosses plane, take one path and remember the other
205                                 if (nodestackindex < 1024)
206                                         nodestack[nodestackindex++] = node->children[0];
207                                 node = node->children[1];
208                         }
209                         continue;
210                 }
211                 else
212                 {
213                         // leaf - add clusterindex to list
214                         if (numclusters < maxclusters)
215                                 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
216                         numclusters++;
217                 }
218 #else
219                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
220                 {
221                         if (node->plane)
222                         {
223                                 if (nodestackindex < 1024)
224                                         nodestack[nodestackindex++] = node->children[0];
225                                 node = node->children[1];
226                                 continue;
227                         }
228                         else
229                         {
230                                 // leaf - add clusterindex to list
231                                 if (numclusters < maxclusters)
232                                         clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
233                                 numclusters++;
234                         }
235                 }
236 #endif
237                 // try another path we didn't take earlier
238                 if (nodestackindex == 0)
239                         break;
240                 node = nodestack[--nodestackindex];
241         }
242         // return number of clusters found (even if more than the maxclusters)
243         return numclusters;
244 }
245
246 static int Mod_Q1BSP_BoxTouchingPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
247 {
248         int nodestackindex = 0;
249         mnode_t *node, *nodestack[1024];
250         if (!model->brush.num_pvsclusters)
251                 return true;
252         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
253         for (;;)
254         {
255 #if 1
256                 if (node->plane)
257                 {
258                         // node - recurse down the BSP tree
259                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
260                         if (sides < 3)
261                         {
262                                 if (sides == 0)
263                                         return -1; // ERROR: NAN bounding box!
264                                 // box is on one side of plane, take that path
265                                 node = node->children[sides-1];
266                         }
267                         else
268                         {
269                                 // box crosses plane, take one path and remember the other
270                                 if (nodestackindex < 1024)
271                                         nodestack[nodestackindex++] = node->children[0];
272                                 node = node->children[1];
273                         }
274                         continue;
275                 }
276                 else
277                 {
278                         // leaf - check cluster bit
279                         int clusterindex = ((mleaf_t *)node)->clusterindex;
280                         if (CHECKPVSBIT(pvs, clusterindex))
281                         {
282                                 // it is visible, return immediately with the news
283                                 return true;
284                         }
285                 }
286 #else
287                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
288                 {
289                         if (node->plane)
290                         {
291                                 if (nodestackindex < 1024)
292                                         nodestack[nodestackindex++] = node->children[0];
293                                 node = node->children[1];
294                                 continue;
295                         }
296                         else
297                         {
298                                 // leaf - check cluster bit
299                                 int clusterindex = ((mleaf_t *)node)->clusterindex;
300                                 if (CHECKPVSBIT(pvs, clusterindex))
301                                 {
302                                         // it is visible, return immediately with the news
303                                         return true;
304                                 }
305                         }
306                 }
307 #endif
308                 // nothing to see here, try another path we didn't take earlier
309                 if (nodestackindex == 0)
310                         break;
311                 node = nodestack[--nodestackindex];
312         }
313         // it is not visible
314         return false;
315 }
316
317 static int Mod_Q1BSP_BoxTouchingLeafPVS(dp_model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
318 {
319         int nodestackindex = 0;
320         mnode_t *node, *nodestack[1024];
321         if (!model->brush.num_leafs)
322                 return true;
323         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
324         for (;;)
325         {
326 #if 1
327                 if (node->plane)
328                 {
329                         // node - recurse down the BSP tree
330                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
331                         if (sides < 3)
332                         {
333                                 if (sides == 0)
334                                         return -1; // ERROR: NAN bounding box!
335                                 // box is on one side of plane, take that path
336                                 node = node->children[sides-1];
337                         }
338                         else
339                         {
340                                 // box crosses plane, take one path and remember the other
341                                 if (nodestackindex < 1024)
342                                         nodestack[nodestackindex++] = node->children[0];
343                                 node = node->children[1];
344                         }
345                         continue;
346                 }
347                 else
348                 {
349                         // leaf - check cluster bit
350                         int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
351                         if (CHECKPVSBIT(pvs, clusterindex))
352                         {
353                                 // it is visible, return immediately with the news
354                                 return true;
355                         }
356                 }
357 #else
358                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
359                 {
360                         if (node->plane)
361                         {
362                                 if (nodestackindex < 1024)
363                                         nodestack[nodestackindex++] = node->children[0];
364                                 node = node->children[1];
365                                 continue;
366                         }
367                         else
368                         {
369                                 // leaf - check cluster bit
370                                 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
371                                 if (CHECKPVSBIT(pvs, clusterindex))
372                                 {
373                                         // it is visible, return immediately with the news
374                                         return true;
375                                 }
376                         }
377                 }
378 #endif
379                 // nothing to see here, try another path we didn't take earlier
380                 if (nodestackindex == 0)
381                         break;
382                 node = nodestack[--nodestackindex];
383         }
384         // it is not visible
385         return false;
386 }
387
388 static int Mod_Q1BSP_BoxTouchingVisibleLeafs(dp_model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
389 {
390         int nodestackindex = 0;
391         mnode_t *node, *nodestack[1024];
392         if (!model->brush.num_leafs)
393                 return true;
394         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
395         for (;;)
396         {
397 #if 1
398                 if (node->plane)
399                 {
400                         // node - recurse down the BSP tree
401                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
402                         if (sides < 3)
403                         {
404                                 if (sides == 0)
405                                         return -1; // ERROR: NAN bounding box!
406                                 // box is on one side of plane, take that path
407                                 node = node->children[sides-1];
408                         }
409                         else
410                         {
411                                 // box crosses plane, take one path and remember the other
412                                 if (nodestackindex < 1024)
413                                         nodestack[nodestackindex++] = node->children[0];
414                                 node = node->children[1];
415                         }
416                         continue;
417                 }
418                 else
419                 {
420                         // leaf - check if it is visible
421                         if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
422                         {
423                                 // it is visible, return immediately with the news
424                                 return true;
425                         }
426                 }
427 #else
428                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
429                 {
430                         if (node->plane)
431                         {
432                                 if (nodestackindex < 1024)
433                                         nodestack[nodestackindex++] = node->children[0];
434                                 node = node->children[1];
435                                 continue;
436                         }
437                         else
438                         {
439                                 // leaf - check if it is visible
440                                 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
441                                 {
442                                         // it is visible, return immediately with the news
443                                         return true;
444                                 }
445                         }
446                 }
447 #endif
448                 // nothing to see here, try another path we didn't take earlier
449                 if (nodestackindex == 0)
450                         break;
451                 node = nodestack[--nodestackindex];
452         }
453         // it is not visible
454         return false;
455 }
456
457 typedef struct findnonsolidlocationinfo_s
458 {
459         vec3_t center;
460         vec3_t absmin, absmax;
461         vec_t radius;
462         vec3_t nudge;
463         vec_t bestdist;
464         dp_model_t *model;
465 }
466 findnonsolidlocationinfo_t;
467
468 static void Mod_Q1BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
469 {
470         int i, *tri;
471         float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
472
473         tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
474         VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
475         VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
476         VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
477         VectorSubtract(vert[1], vert[0], edge[0]);
478         VectorSubtract(vert[2], vert[1], edge[1]);
479         CrossProduct(edge[1], edge[0], facenormal);
480         if (facenormal[0] || facenormal[1] || facenormal[2])
481         {
482                 VectorNormalize(facenormal);
483                 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
484                 if (f <= info->bestdist && f >= -info->bestdist)
485                 {
486                         VectorSubtract(vert[0], vert[2], edge[2]);
487                         VectorNormalize(edge[0]);
488                         VectorNormalize(edge[1]);
489                         VectorNormalize(edge[2]);
490                         CrossProduct(facenormal, edge[0], edgenormal[0]);
491                         CrossProduct(facenormal, edge[1], edgenormal[1]);
492                         CrossProduct(facenormal, edge[2], edgenormal[2]);
493                         // face distance
494                         if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
495                                         && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
496                                         && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
497                         {
498                                 // we got lucky, the center is within the face
499                                 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
500                                 if (dist < 0)
501                                 {
502                                         dist = -dist;
503                                         if (info->bestdist > dist)
504                                         {
505                                                 info->bestdist = dist;
506                                                 VectorScale(facenormal, (info->radius - -dist), info->nudge);
507                                         }
508                                 }
509                                 else
510                                 {
511                                         if (info->bestdist > dist)
512                                         {
513                                                 info->bestdist = dist;
514                                                 VectorScale(facenormal, (info->radius - dist), info->nudge);
515                                         }
516                                 }
517                         }
518                         else
519                         {
520                                 // check which edge or vertex the center is nearest
521                                 for (i = 0;i < 3;i++)
522                                 {
523                                         f = DotProduct(info->center, edge[i]);
524                                         if (f >= DotProduct(vert[0], edge[i])
525                                                         && f <= DotProduct(vert[1], edge[i]))
526                                         {
527                                                 // on edge
528                                                 VectorMA(info->center, -f, edge[i], point);
529                                                 dist = sqrt(DotProduct(point, point));
530                                                 if (info->bestdist > dist)
531                                                 {
532                                                         info->bestdist = dist;
533                                                         VectorScale(point, (info->radius / dist), info->nudge);
534                                                 }
535                                                 // skip both vertex checks
536                                                 // (both are further away than this edge)
537                                                 i++;
538                                         }
539                                         else
540                                         {
541                                                 // not on edge, check first vertex of edge
542                                                 VectorSubtract(info->center, vert[i], point);
543                                                 dist = sqrt(DotProduct(point, point));
544                                                 if (info->bestdist > dist)
545                                                 {
546                                                         info->bestdist = dist;
547                                                         VectorScale(point, (info->radius / dist), info->nudge);
548                                                 }
549                                         }
550                                 }
551                         }
552                 }
553         }
554 }
555
556 static void Mod_Q1BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
557 {
558         int surfacenum, k, *mark;
559         msurface_t *surface;
560         for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
561         {
562                 surface = info->model->data_surfaces + *mark;
563                 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
564                 {
565                         if(surface->deprecatedq3num_bboxstride > 0)
566                         {
567                                 int i, cnt, tri;
568                                 cnt = (surface->num_triangles + surface->deprecatedq3num_bboxstride - 1) / surface->deprecatedq3num_bboxstride;
569                                 for(i = 0; i < cnt; ++i)
570                                 {
571                                         if(BoxesOverlap(surface->deprecatedq3data_bbox6f + i * 6, surface->deprecatedq3data_bbox6f + i * 6 + 3, info->absmin, info->absmax))
572                                         {
573                                                 for(k = 0; k < surface->deprecatedq3num_bboxstride; ++k)
574                                                 {
575                                                         tri = i * surface->deprecatedq3num_bboxstride + k;
576                                                         if(tri >= surface->num_triangles)
577                                                                 break;
578                                                         Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, tri);
579                                                 }
580                                         }
581                                 }
582                         }
583                         else
584                         {
585                                 for (k = 0;k < surface->num_triangles;k++)
586                                 {
587                                         Mod_Q1BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
588                                 }
589                         }
590                 }
591         }
592 }
593
594 static void Mod_Q1BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
595 {
596         if (node->plane)
597         {
598                 float f = PlaneDiff(info->center, node->plane);
599                 if (f >= -info->bestdist)
600                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[0]);
601                 if (f <= info->bestdist)
602                         Mod_Q1BSP_FindNonSolidLocation_r(info, node->children[1]);
603         }
604         else
605         {
606                 if (((mleaf_t *)node)->numleafsurfaces)
607                         Mod_Q1BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
608         }
609 }
610
611 static void Mod_Q1BSP_FindNonSolidLocation(dp_model_t *model, const vec3_t in, vec3_t out, float radius)
612 {
613         int i;
614         findnonsolidlocationinfo_t info;
615         if (model == NULL)
616         {
617                 VectorCopy(in, out);
618                 return;
619         }
620         VectorCopy(in, info.center);
621         info.radius = radius;
622         info.model = model;
623         i = 0;
624         do
625         {
626                 VectorClear(info.nudge);
627                 info.bestdist = radius;
628                 VectorCopy(info.center, info.absmin);
629                 VectorCopy(info.center, info.absmax);
630                 info.absmin[0] -= info.radius + 1;
631                 info.absmin[1] -= info.radius + 1;
632                 info.absmin[2] -= info.radius + 1;
633                 info.absmax[0] += info.radius + 1;
634                 info.absmax[1] += info.radius + 1;
635                 info.absmax[2] += info.radius + 1;
636                 Mod_Q1BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
637                 VectorAdd(info.center, info.nudge, info.center);
638         }
639         while (info.bestdist < radius && ++i < 10);
640         VectorCopy(info.center, out);
641 }
642
643 int Mod_Q1BSP_SuperContentsFromNativeContents(dp_model_t *model, int nativecontents)
644 {
645         switch(nativecontents)
646         {
647                 case CONTENTS_EMPTY:
648                         return 0;
649                 case CONTENTS_SOLID:
650                         return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
651                 case CONTENTS_WATER:
652                         return SUPERCONTENTS_WATER;
653                 case CONTENTS_SLIME:
654                         return SUPERCONTENTS_SLIME;
655                 case CONTENTS_LAVA:
656                         return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
657                 case CONTENTS_SKY:
658                         return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
659         }
660         return 0;
661 }
662
663 int Mod_Q1BSP_NativeContentsFromSuperContents(dp_model_t *model, int supercontents)
664 {
665         if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
666                 return CONTENTS_SOLID;
667         if (supercontents & SUPERCONTENTS_SKY)
668                 return CONTENTS_SKY;
669         if (supercontents & SUPERCONTENTS_LAVA)
670                 return CONTENTS_LAVA;
671         if (supercontents & SUPERCONTENTS_SLIME)
672                 return CONTENTS_SLIME;
673         if (supercontents & SUPERCONTENTS_WATER)
674                 return CONTENTS_WATER;
675         return CONTENTS_EMPTY;
676 }
677
678 typedef struct RecursiveHullCheckTraceInfo_s
679 {
680         // the hull we're tracing through
681         const hull_t *hull;
682
683         // the trace structure to fill in
684         trace_t *trace;
685
686         // start, end, and end - start (in model space)
687         double start[3];
688         double end[3];
689         double dist[3];
690 }
691 RecursiveHullCheckTraceInfo_t;
692
693 // 1/32 epsilon to keep floating point happy
694 #define DIST_EPSILON (0.03125)
695
696 #define HULLCHECKSTATE_EMPTY 0
697 #define HULLCHECKSTATE_SOLID 1
698 #define HULLCHECKSTATE_DONE 2
699
700 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
701 {
702         // status variables, these don't need to be saved on the stack when
703         // recursing...  but are because this should be thread-safe
704         // (note: tracing against a bbox is not thread-safe, yet)
705         int ret;
706         mplane_t *plane;
707         double t1, t2;
708
709         // variables that need to be stored on the stack when recursing
710         mclipnode_t *node;
711         int p1side, p2side;
712         double midf, mid[3];
713
714         // keep looping until we hit a leaf
715         while (num >= 0)
716         {
717                 // find the point distances
718                 node = t->hull->clipnodes + num;
719                 plane = t->hull->planes + node->planenum;
720
721                 // axial planes can be calculated more quickly without the DotProduct
722                 if (plane->type < 3)
723                 {
724                         t1 = p1[plane->type] - plane->dist;
725                         t2 = p2[plane->type] - plane->dist;
726                 }
727                 else
728                 {
729                         t1 = DotProduct (plane->normal, p1) - plane->dist;
730                         t2 = DotProduct (plane->normal, p2) - plane->dist;
731                 }
732
733                 // negative plane distances indicate children[1] (behind plane)
734                 p1side = t1 < 0;
735                 p2side = t2 < 0;
736
737                 // if the line starts and ends on the same side of the plane, recurse
738                 // into that child instantly
739                 if (p1side == p2side)
740                 {
741 #if COLLISIONPARANOID >= 3
742                         if (p1side)
743                                 Con_Print("<");
744                         else
745                                 Con_Print(">");
746 #endif
747                         // loop back and process the start child
748                         num = node->children[p1side];
749                 }
750                 else
751                 {
752                         // find the midpoint where the line crosses the plane, use the
753                         // original line for best accuracy
754 #if COLLISIONPARANOID >= 3
755                         Con_Print("M");
756 #endif
757                         if (plane->type < 3)
758                         {
759                                 t1 = t->start[plane->type] - plane->dist;
760                                 t2 = t->end[plane->type] - plane->dist;
761                         }
762                         else
763                         {
764                                 t1 = DotProduct (plane->normal, t->start) - plane->dist;
765                                 t2 = DotProduct (plane->normal, t->end) - plane->dist;
766                         }
767                         midf = t1 / (t1 - t2);
768                         midf = bound(p1f, midf, p2f);
769                         VectorMA(t->start, midf, t->dist, mid);
770
771                         // we now have a mid point, essentially splitting the line into
772                         // the segments in the near child and the far child, we can now
773                         // recurse those in order and get their results
774
775                         // recurse both sides, front side first
776                         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p1side], p1f, midf, p1, mid);
777                         // if this side is not empty, return what it is (solid or done)
778                         if (ret != HULLCHECKSTATE_EMPTY)
779                                 return ret;
780
781                         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p2side], midf, p2f, mid, p2);
782                         // if other side is not solid, return what it is (empty or done)
783                         if (ret != HULLCHECKSTATE_SOLID)
784                                 return ret;
785
786                         // front is air and back is solid, this is the impact point...
787
788                         // copy the plane information, flipping it if needed
789                         if (p1side)
790                         {
791                                 t->trace->plane.dist = -plane->dist;
792                                 VectorNegate (plane->normal, t->trace->plane.normal);
793                         }
794                         else
795                         {
796                                 t->trace->plane.dist = plane->dist;
797                                 VectorCopy (plane->normal, t->trace->plane.normal);
798                         }
799
800                         // calculate the return fraction which is nudged off the surface a bit
801                         t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
802                         t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
803                         midf = (t1 - collision_impactnudge.value) / (t1 - t2);
804                         t->trace->fraction = bound(0, midf, 1);
805
806 #if COLLISIONPARANOID >= 3
807                         Con_Print("D");
808 #endif
809                         return HULLCHECKSTATE_DONE;
810                 }
811         }
812
813         // we reached a leaf contents
814
815         // check for empty
816         num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
817         if (!t->trace->startfound)
818         {
819                 t->trace->startfound = true;
820                 t->trace->startsupercontents |= num;
821         }
822         if (num & SUPERCONTENTS_LIQUIDSMASK)
823                 t->trace->inwater = true;
824         if (num == 0)
825                 t->trace->inopen = true;
826         if (num & SUPERCONTENTS_SOLID)
827                 t->trace->hittexture = &mod_q1bsp_texture_solid;
828         else if (num & SUPERCONTENTS_SKY)
829                 t->trace->hittexture = &mod_q1bsp_texture_sky;
830         else if (num & SUPERCONTENTS_LAVA)
831                 t->trace->hittexture = &mod_q1bsp_texture_lava;
832         else if (num & SUPERCONTENTS_SLIME)
833                 t->trace->hittexture = &mod_q1bsp_texture_slime;
834         else
835                 t->trace->hittexture = &mod_q1bsp_texture_water;
836         t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
837         t->trace->hitsupercontents = num;
838         if (num & t->trace->hitsupercontentsmask)
839         {
840                 // if the first leaf is solid, set startsolid
841                 if (t->trace->allsolid)
842                         t->trace->startsolid = true;
843 #if COLLISIONPARANOID >= 3
844                 Con_Print("S");
845 #endif
846                 return HULLCHECKSTATE_SOLID;
847         }
848         else
849         {
850                 t->trace->allsolid = false;
851 #if COLLISIONPARANOID >= 3
852                 Con_Print("E");
853 #endif
854                 return HULLCHECKSTATE_EMPTY;
855         }
856 }
857
858 //#if COLLISIONPARANOID < 2
859 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
860 {
861         mplane_t *plane;
862         mclipnode_t *nodes = t->hull->clipnodes;
863         mplane_t *planes = t->hull->planes;
864         vec3_t point;
865         VectorCopy(t->start, point);
866         while (num >= 0)
867         {
868                 plane = planes + nodes[num].planenum;
869                 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
870         }
871         num = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
872         t->trace->startsupercontents |= num;
873         if (num & SUPERCONTENTS_LIQUIDSMASK)
874                 t->trace->inwater = true;
875         if (num == 0)
876                 t->trace->inopen = true;
877         if (num & t->trace->hitsupercontentsmask)
878         {
879                 t->trace->allsolid = t->trace->startsolid = true;
880                 return HULLCHECKSTATE_SOLID;
881         }
882         else
883         {
884                 t->trace->allsolid = t->trace->startsolid = false;
885                 return HULLCHECKSTATE_EMPTY;
886         }
887 }
888 //#endif
889
890 static void Mod_Q1BSP_TracePoint(struct model_s *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask)
891 {
892         RecursiveHullCheckTraceInfo_t rhc;
893
894         memset(&rhc, 0, sizeof(rhc));
895         memset(trace, 0, sizeof(trace_t));
896         rhc.trace = trace;
897         rhc.trace->fraction = 1;
898         rhc.trace->allsolid = true;
899         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
900         VectorCopy(start, rhc.start);
901         VectorCopy(start, rhc.end);
902         Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
903 }
904
905 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, int skipsupercontentsmask);
906
907 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, int skipsupercontentsmask)
908 {
909         RecursiveHullCheckTraceInfo_t rhc;
910
911         if (VectorCompare(start, end))
912         {
913                 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
914                 return;
915         }
916
917         // 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...
918         if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
919         {
920                 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
921                 return;
922         }
923
924         memset(&rhc, 0, sizeof(rhc));
925         memset(trace, 0, sizeof(trace_t));
926         rhc.trace = trace;
927         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
928         rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
929         rhc.trace->fraction = 1;
930         rhc.trace->allsolid = true;
931         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
932         VectorCopy(start, rhc.start);
933         VectorCopy(end, rhc.end);
934         VectorSubtract(rhc.end, rhc.start, rhc.dist);
935 #if COLLISIONPARANOID >= 2
936         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]);
937         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
938         {
939
940                 double test[3];
941                 trace_t testtrace;
942                 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
943                 memset(&testtrace, 0, sizeof(trace_t));
944                 rhc.trace = &testtrace;
945                 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
946                 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
947                 rhc.trace->fraction = 1;
948                 rhc.trace->allsolid = true;
949                 VectorCopy(test, rhc.start);
950                 VectorCopy(test, rhc.end);
951                 VectorClear(rhc.dist);
952                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
953                 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
954                 if (!trace->startsolid && testtrace.startsolid)
955                         Con_Printf(" - ended in solid!\n");
956         }
957         Con_Print("\n");
958 #else
959         if (VectorLength2(rhc.dist))
960                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
961         else
962                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
963 #endif
964 }
965
966 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, int skipsupercontentsmask)
967 {
968         // this function currently only supports same size start and end
969         double boxsize[3];
970         RecursiveHullCheckTraceInfo_t rhc;
971
972         if (VectorCompare(boxmins, boxmaxs))
973         {
974                 if (VectorCompare(start, end))
975                         Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask);
976                 else
977                         Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask);
978                 return;
979         }
980
981         memset(&rhc, 0, sizeof(rhc));
982         memset(trace, 0, sizeof(trace_t));
983         rhc.trace = trace;
984         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
985         rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
986         rhc.trace->fraction = 1;
987         rhc.trace->allsolid = true;
988         VectorSubtract(boxmaxs, boxmins, boxsize);
989         if (boxsize[0] < 3)
990                 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
991         else if (model->brush.ishlbsp)
992         {
993                 // LordHavoc: this has to have a minor tolerance (the .1) because of
994                 // minor float precision errors from the box being transformed around
995                 if (boxsize[0] < 32.1)
996                 {
997                         if (boxsize[2] < 54) // pick the nearest of 36 or 72
998                                 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
999                         else
1000                                 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
1001                 }
1002                 else
1003                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
1004         }
1005         else
1006         {
1007                 // LordHavoc: this has to have a minor tolerance (the .1) because of
1008                 // minor float precision errors from the box being transformed around
1009                 if (boxsize[0] < 32.1)
1010                         rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
1011                 else
1012                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1013         }
1014         VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1015         VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1016         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1017 #if COLLISIONPARANOID >= 2
1018         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]);
1019         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1020         {
1021
1022                 double test[3];
1023                 trace_t testtrace;
1024                 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1025                 memset(&testtrace, 0, sizeof(trace_t));
1026                 rhc.trace = &testtrace;
1027                 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1028                 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1029                 rhc.trace->fraction = 1;
1030                 rhc.trace->allsolid = true;
1031                 VectorCopy(test, rhc.start);
1032                 VectorCopy(test, rhc.end);
1033                 VectorClear(rhc.dist);
1034                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1035                 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1036                 if (!trace->startsolid && testtrace.startsolid)
1037                         Con_Printf(" - ended in solid!\n");
1038         }
1039         Con_Print("\n");
1040 #else
1041         if (VectorLength2(rhc.dist))
1042                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1043         else
1044                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1045 #endif
1046 }
1047
1048 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1049 {
1050         int num = model->brushq1.hulls[0].firstclipnode;
1051         mplane_t *plane;
1052         mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1053         mplane_t *planes = model->brushq1.hulls[0].planes;
1054         while (num >= 0)
1055         {
1056                 plane = planes + nodes[num].planenum;
1057                 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1058         }
1059         return Mod_Q1BSP_SuperContentsFromNativeContents(NULL, num);
1060 }
1061
1062 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 skipsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1063 {
1064 #if 1
1065         colbrushf_t cbox;
1066         colplanef_t cbox_planes[6];
1067         cbox.isaabb = true;
1068         cbox.hasaabbplanes = true;
1069         cbox.supercontents = boxsupercontents;
1070         cbox.numplanes = 6;
1071         cbox.numpoints = 0;
1072         cbox.numtriangles = 0;
1073         cbox.planes = cbox_planes;
1074         cbox.points = NULL;
1075         cbox.elements = NULL;
1076         cbox.markframe = 0;
1077         cbox.mins[0] = 0;
1078         cbox.mins[1] = 0;
1079         cbox.mins[2] = 0;
1080         cbox.maxs[0] = 0;
1081         cbox.maxs[1] = 0;
1082         cbox.maxs[2] = 0;
1083         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];
1084         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];
1085         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];
1086         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];
1087         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];
1088         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];
1089         cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1090         cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1091         cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1092         cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1093         cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1094         cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1095         memset(trace, 0, sizeof(trace_t));
1096         trace->hitsupercontentsmask = hitsupercontentsmask;
1097         trace->skipsupercontentsmask = skipsupercontentsmask;
1098         trace->fraction = 1;
1099         Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1100 #else
1101         RecursiveHullCheckTraceInfo_t rhc;
1102         static hull_t box_hull;
1103         static mclipnode_t box_clipnodes[6];
1104         static mplane_t box_planes[6];
1105         // fill in a default trace
1106         memset(&rhc, 0, sizeof(rhc));
1107         memset(trace, 0, sizeof(trace_t));
1108         //To keep everything totally uniform, bounding boxes are turned into small
1109         //BSP trees instead of being compared directly.
1110         // create a temp hull from bounding box sizes
1111         box_planes[0].dist = cmaxs[0] - mins[0];
1112         box_planes[1].dist = cmins[0] - maxs[0];
1113         box_planes[2].dist = cmaxs[1] - mins[1];
1114         box_planes[3].dist = cmins[1] - maxs[1];
1115         box_planes[4].dist = cmaxs[2] - mins[2];
1116         box_planes[5].dist = cmins[2] - maxs[2];
1117 #if COLLISIONPARANOID >= 3
1118         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]);
1119 #endif
1120
1121         if (box_hull.clipnodes == NULL)
1122         {
1123                 int i, side;
1124
1125                 //Set up the planes and clipnodes so that the six floats of a bounding box
1126                 //can just be stored out and get a proper hull_t structure.
1127
1128                 box_hull.clipnodes = box_clipnodes;
1129                 box_hull.planes = box_planes;
1130                 box_hull.firstclipnode = 0;
1131                 box_hull.lastclipnode = 5;
1132
1133                 for (i = 0;i < 6;i++)
1134                 {
1135                         box_clipnodes[i].planenum = i;
1136
1137                         side = i&1;
1138
1139                         box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1140                         if (i != 5)
1141                                 box_clipnodes[i].children[side^1] = i + 1;
1142                         else
1143                                 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1144
1145                         box_planes[i].type = i>>1;
1146                         box_planes[i].normal[i>>1] = 1;
1147                 }
1148         }
1149
1150         // trace a line through the generated clipping hull
1151         //rhc.boxsupercontents = boxsupercontents;
1152         rhc.hull = &box_hull;
1153         rhc.trace = trace;
1154         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1155         rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1156         rhc.trace->fraction = 1;
1157         rhc.trace->allsolid = true;
1158         VectorCopy(start, rhc.start);
1159         VectorCopy(end, rhc.end);
1160         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1161         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1162         //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1163         if (rhc.trace->startsupercontents)
1164                 rhc.trace->startsupercontents = boxsupercontents;
1165 #endif
1166 }
1167
1168 void Collision_ClipTrace_Point(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1169 {
1170         memset(trace, 0, sizeof(trace_t));
1171         trace->fraction = 1;
1172         trace->hitsupercontentsmask = hitsupercontentsmask;
1173         trace->skipsupercontentsmask = skipsupercontentsmask;
1174         if (BoxesOverlap(start, start, cmins, cmaxs))
1175         {
1176                 trace->startsupercontents |= boxsupercontents;
1177                 if ((hitsupercontentsmask & boxsupercontents) && !(skipsupercontentsmask & boxsupercontents))
1178                 {
1179                         trace->startsolid = true;
1180                         trace->allsolid = true;
1181                 }
1182         }
1183 }
1184
1185 static qboolean Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end)
1186 {
1187         trace_t trace;
1188         Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0);
1189         return trace.fraction == 1;
1190 }
1191
1192 static int Mod_Q1BSP_LightPoint_RecursiveBSPNode(dp_model_t *model, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const mnode_t *node, float x, float y, float startz, float endz)
1193 {
1194         int side;
1195         float front, back;
1196         float mid, distz = endz - startz;
1197
1198         while (node->plane)
1199         {
1200                 switch (node->plane->type)
1201                 {
1202                 case PLANE_X:
1203                         node = node->children[x < node->plane->dist];
1204                         continue; // loop back and process the new node
1205                 case PLANE_Y:
1206                         node = node->children[y < node->plane->dist];
1207                         continue; // loop back and process the new node
1208                 case PLANE_Z:
1209                         side = startz < node->plane->dist;
1210                         if ((endz < node->plane->dist) == side)
1211                         {
1212                                 node = node->children[side];
1213                                 continue; // loop back and process the new node
1214                         }
1215                         // found an intersection
1216                         mid = node->plane->dist;
1217                         break;
1218                 default:
1219                         back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1220                         front += startz * node->plane->normal[2];
1221                         back += endz * node->plane->normal[2];
1222                         side = front < node->plane->dist;
1223                         if ((back < node->plane->dist) == side)
1224                         {
1225                                 node = node->children[side];
1226                                 continue; // loop back and process the new node
1227                         }
1228                         // found an intersection
1229                         mid = startz + distz * (front - node->plane->dist) / (front - back);
1230                         break;
1231                 }
1232
1233                 // go down front side
1234                 if (node->children[side]->plane && Mod_Q1BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1235                         return true;    // hit something
1236
1237                 // check for impact on this node
1238                 if (node->numsurfaces)
1239                 {
1240                         unsigned int i;
1241                         int dsi, dti, lmwidth, lmheight;
1242                         float ds, dt;
1243                         msurface_t *surface;
1244                         unsigned char *lightmap;
1245                         int maps, line3, size3;
1246                         float dsfrac;
1247                         float dtfrac;
1248                         float scale, w, w00, w01, w10, w11;
1249
1250                         surface = model->data_surfaces + node->firstsurface;
1251                         for (i = 0;i < node->numsurfaces;i++, surface++)
1252                         {
1253                                 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1254                                         continue;       // no lightmaps
1255
1256                                 // location we want to sample in the lightmap
1257                                 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;
1258                                 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;
1259
1260                                 // check the bounds
1261                                 // thanks to jitspoe for pointing out that this int cast was
1262                                 // rounding toward zero, so we floor it
1263                                 dsi = (int)floor(ds);
1264                                 dti = (int)floor(dt);
1265                                 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1266                                 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1267
1268                                 // is it in bounds?
1269                                 // we have to tolerate a position of lmwidth-1 for some rare
1270                                 // cases - in which case the sampling position still gets
1271                                 // clamped but the color gets interpolated to that edge.
1272                                 if (dsi >= 0 && dsi < lmwidth && dti >= 0 && dti < lmheight)
1273                                 {
1274                                         // in the rare cases where we're sampling slightly off
1275                                         // the polygon, clamp the sampling position (we can still
1276                                         // interpolate outside it, where it becomes extrapolation)
1277                                         if (dsi < 0)
1278                                                 dsi = 0;
1279                                         if (dti < 0)
1280                                                 dti = 0;
1281                                         if (dsi > lmwidth-2)
1282                                                 dsi = lmwidth-2;
1283                                         if (dti > lmheight-2)
1284                                                 dti = lmheight-2;
1285                                         
1286                                         // calculate bilinear interpolation factors
1287                                         // and also multiply by fixedpoint conversion factors to
1288                                         // compensate for lightmaps being 0-255 (as 0-2), we use
1289                                         // r_refdef.scene.rtlightstylevalue here which is already
1290                                         // 0.000-2.148 range
1291                                         // (if we used r_refdef.scene.lightstylevalue this
1292                                         //  divisor would be 32768 rather than 128)
1293                                         dsfrac = ds - dsi;
1294                                         dtfrac = dt - dti;
1295                                         w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1296                                         w01 = (    dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1297                                         w10 = (1 - dsfrac) * (    dtfrac) * (1.0f / 128.0f);
1298                                         w11 = (    dsfrac) * (    dtfrac) * (1.0f / 128.0f);
1299
1300                                         // values for pointer math
1301                                         line3 = lmwidth * 3; // LordHavoc: *3 for colored lighting
1302                                         size3 = lmwidth * lmheight * 3; // LordHavoc: *3 for colored lighting
1303
1304                                         // look up the pixel
1305                                         lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LordHavoc: *3 for colored lighting
1306
1307                                         // bilinear filter each lightmap style, and sum them
1308                                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1309                                         {
1310                                                 scale = r_refdef.scene.rtlightstylevalue[surface->lightmapinfo->styles[maps]];
1311                                                 w = w00 * scale;VectorMA(ambientcolor, w, lightmap            , ambientcolor);
1312                                                 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3        , ambientcolor);
1313                                                 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3    , ambientcolor);
1314                                                 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1315                                                 lightmap += size3;
1316                                         }
1317
1318                                         return true; // success
1319                                 }
1320                         }
1321                 }
1322
1323                 // go down back side
1324                 node = node->children[side ^ 1];
1325                 startz = mid;
1326                 distz = endz - startz;
1327                 // loop back and process the new node
1328         }
1329
1330         // did not hit anything
1331         return false;
1332 }
1333
1334 static void Mod_Q1BSP_LightPoint(dp_model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1335 {
1336         // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1337         VectorSet(diffusenormal, 0, 0, 1);
1338
1339         if (!model->brushq1.lightdata)
1340         {
1341                 VectorSet(ambientcolor, 1, 1, 1);
1342                 VectorSet(diffusecolor, 0, 0, 0);
1343                 return;
1344         }
1345
1346         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);
1347 }
1348
1349 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const dp_model_t *model, const mnode_t *node, double mid[3])
1350 {
1351         unsigned int i;
1352         int j;
1353         int k;
1354         const msurface_t *surface;
1355         float normal[3];
1356         float v0[3];
1357         float v1[3];
1358         float edgedir[3];
1359         float edgenormal[3];
1360         float p[4];
1361         float midf;
1362         float t1;
1363         float t2;
1364         VectorCopy(mid, p);
1365         p[3] = 1;
1366         surface = model->data_surfaces + node->firstsurface;
1367         for (i = 0;i < node->numsurfaces;i++, surface++)
1368         {
1369                 // skip surfaces whose bounding box does not include the point
1370 //              if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1371 //                      continue;
1372                 // skip faces with contents we don't care about
1373                 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1374                         continue;
1375                 // ignore surfaces matching the skipsupercontentsmask (this is rare)
1376                 if (t->trace->skipsupercontentsmask & surface->texture->supercontents)
1377                         continue;
1378                 // get the surface normal - since it is flat we know any vertex normal will suffice
1379                 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1380                 // skip backfaces
1381                 if (DotProduct(t->dist, normal) > 0)
1382                         continue;
1383                 // iterate edges and see if the point is outside one of them
1384                 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1385                 {
1386                         VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1387                         VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1388                         VectorSubtract(v0, v1, edgedir);
1389                         CrossProduct(edgedir, normal, edgenormal);
1390                         if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1391                                 break;
1392                 }
1393                 // if the point is outside one of the edges, it is not within the surface
1394                 if (j < surface->num_vertices)
1395                         continue;
1396
1397                 // we hit a surface, this is the impact point...
1398                 VectorCopy(normal, t->trace->plane.normal);
1399                 t->trace->plane.dist = DotProduct(normal, p);
1400
1401                 // calculate the return fraction which is nudged off the surface a bit
1402                 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1403                 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1404                 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
1405                 t->trace->fraction = bound(0, midf, 1);
1406
1407                 t->trace->hittexture = surface->texture->currentframe;
1408                 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1409                 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1410                 return surface->texture->currentframe;
1411         }
1412         return NULL;
1413 }
1414
1415 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])
1416 {
1417         const mplane_t *plane;
1418         double t1, t2;
1419         int side;
1420         double midf, mid[3];
1421         const mleaf_t *leaf;
1422
1423         while (node->plane)
1424         {
1425                 plane = node->plane;
1426                 if (plane->type < 3)
1427                 {
1428                         t1 = p1[plane->type] - plane->dist;
1429                         t2 = p2[plane->type] - plane->dist;
1430                 }
1431                 else
1432                 {
1433                         t1 = DotProduct (plane->normal, p1) - plane->dist;
1434                         t2 = DotProduct (plane->normal, p2) - plane->dist;
1435                 }
1436                 if (t1 < 0)
1437                 {
1438                         if (t2 < 0)
1439                         {
1440                                 node = node->children[1];
1441                                 continue;
1442                         }
1443                         side = 1;
1444                 }
1445                 else
1446                 {
1447                         if (t2 >= 0)
1448                         {
1449                                 node = node->children[0];
1450                                 continue;
1451                         }
1452                         side = 0;
1453                 }
1454
1455                 // the line intersects, find intersection point
1456                 // LordHavoc: this uses the original trace for maximum accuracy
1457                 if (plane->type < 3)
1458                 {
1459                         t1 = t->start[plane->type] - plane->dist;
1460                         t2 = t->end[plane->type] - plane->dist;
1461                 }
1462                 else
1463                 {
1464                         t1 = DotProduct (plane->normal, t->start) - plane->dist;
1465                         t2 = DotProduct (plane->normal, t->end) - plane->dist;
1466                 }
1467         
1468                 midf = t1 / (t1 - t2);
1469                 VectorMA(t->start, midf, t->dist, mid);
1470
1471                 // recurse both sides, front side first, return if we hit a surface
1472                 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1473                         return HULLCHECKSTATE_DONE;
1474
1475                 // test each surface on the node
1476                 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1477                 if (t->trace->hittexture)
1478                         return HULLCHECKSTATE_DONE;
1479
1480                 // recurse back side
1481                 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1482         }
1483         leaf = (const mleaf_t *)node;
1484         side = Mod_Q1BSP_SuperContentsFromNativeContents(NULL, leaf->contents);
1485         if (!t->trace->startfound)
1486         {
1487                 t->trace->startfound = true;
1488                 t->trace->startsupercontents |= side;
1489         }
1490         if (side & SUPERCONTENTS_LIQUIDSMASK)
1491                 t->trace->inwater = true;
1492         if (side == 0)
1493                 t->trace->inopen = true;
1494         if (side & t->trace->hitsupercontentsmask)
1495         {
1496                 // if the first leaf is solid, set startsolid
1497                 if (t->trace->allsolid)
1498                         t->trace->startsolid = true;
1499                 return HULLCHECKSTATE_SOLID;
1500         }
1501         else
1502         {
1503                 t->trace->allsolid = false;
1504                 return HULLCHECKSTATE_EMPTY;
1505         }
1506 }
1507
1508 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, int skipsupercontentsmask)
1509 {
1510         RecursiveHullCheckTraceInfo_t rhc;
1511
1512         memset(&rhc, 0, sizeof(rhc));
1513         memset(trace, 0, sizeof(trace_t));
1514         rhc.trace = trace;
1515         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1516         rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1517         rhc.trace->fraction = 1;
1518         rhc.trace->allsolid = true;
1519         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1520         VectorCopy(start, rhc.start);
1521         VectorCopy(end, rhc.end);
1522         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1523         Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1524         VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1525 }
1526
1527 static void Mod_Q1BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1528 {
1529         int c;
1530         unsigned char *outstart = out;
1531         while (out < outend)
1532         {
1533                 if (in == inend)
1534                 {
1535                         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));
1536                         return;
1537                 }
1538                 c = *in++;
1539                 if (c)
1540                         *out++ = c;
1541                 else
1542                 {
1543                         if (in == inend)
1544                         {
1545                                 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));
1546                                 return;
1547                         }
1548                         for (c = *in++;c > 0;c--)
1549                         {
1550                                 if (out == outend)
1551                                 {
1552                                         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));
1553                                         return;
1554                                 }
1555                                 *out++ = 0;
1556                         }
1557                 }
1558         }
1559 }
1560
1561 /*
1562 =============
1563 R_Q1BSP_LoadSplitSky
1564
1565 A sky texture is 256*128, with the right side being a masked overlay
1566 ==============
1567 */
1568 static void R_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1569 {
1570         int x, y;
1571         int w = width/2;
1572         int h = height;
1573         unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1574         unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1575
1576         // allocate a texture pool if we need it
1577         if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1578                 loadmodel->texturepool = R_AllocTexturePool();
1579
1580         if (bytesperpixel == 4)
1581         {
1582                 for (y = 0;y < h;y++)
1583                 {
1584                         for (x = 0;x < w;x++)
1585                         {
1586                                 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1587                                 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1588                         }
1589                 }
1590         }
1591         else
1592         {
1593                 // make an average value for the back to avoid
1594                 // a fringe on the top level
1595                 int p, r, g, b;
1596                 union
1597                 {
1598                         unsigned int i;
1599                         unsigned char b[4];
1600                 }
1601                 bgra;
1602                 r = g = b = 0;
1603                 for (y = 0;y < h;y++)
1604                 {
1605                         for (x = 0;x < w;x++)
1606                         {
1607                                 p = src[x*width+y+w];
1608                                 r += palette_rgb[p][0];
1609                                 g += palette_rgb[p][1];
1610                                 b += palette_rgb[p][2];
1611                         }
1612                 }
1613                 bgra.b[2] = r/(w*h);
1614                 bgra.b[1] = g/(w*h);
1615                 bgra.b[0] = b/(w*h);
1616                 bgra.b[3] = 0;
1617                 for (y = 0;y < h;y++)
1618                 {
1619                         for (x = 0;x < w;x++)
1620                         {
1621                                 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1622                                 p = src[y*width+x];
1623                                 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1624                         }
1625                 }
1626         }
1627
1628         loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0         , (unsigned char *) solidpixels, w, h, vid.sRGB3D);
1629         loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, vid.sRGB3D);
1630         Mem_Free(solidpixels);
1631         Mem_Free(alphapixels);
1632 }
1633
1634 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1635 {
1636         int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0;
1637         skinframe_t *skinframemissing;
1638         texture_t *tx, *tx2, *anims[10], *altanims[10];
1639         texture_t backuptex;
1640         unsigned char *data, *mtdata;
1641         const char *s;
1642         char mapname[MAX_QPATH], name[MAX_QPATH];
1643         unsigned char zeroopaque[4], zerotrans[4];
1644         sizebuf_t miptexsb;
1645         char vabuf[1024];
1646         Vector4Set(zeroopaque, 0, 0, 0, 255);
1647         Vector4Set(zerotrans, 0, 0, 0, 128);
1648
1649         loadmodel->data_textures = NULL;
1650
1651         // add two slots for notexture walls and notexture liquids
1652         if (sb->cursize)
1653         {
1654                 nummiptex = MSG_ReadLittleLong(sb);
1655                 loadmodel->num_textures = nummiptex + 2;
1656                 loadmodel->num_texturesperskin = loadmodel->num_textures;
1657         }
1658         else
1659         {
1660                 loadmodel->num_textures = 2;
1661                 loadmodel->num_texturesperskin = loadmodel->num_textures;
1662         }
1663
1664         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1665
1666         // fill out all slots with notexture
1667         skinframemissing = R_SkinFrame_LoadMissing();
1668         for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1669         {
1670                 strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1671                 tx->width = 16;
1672                 tx->height = 16;
1673                 tx->basealpha = 1.0f;
1674                 tx->materialshaderpass = tx->shaderpasses[0] = Mod_CreateShaderPass(skinframemissing);
1675                 tx->materialshaderpass->skinframes[0] = skinframemissing;
1676                 tx->currentskinframe = skinframemissing;
1677                 tx->basematerialflags = MATERIALFLAG_WALL;
1678                 if (i == loadmodel->num_textures - 1)
1679                 {
1680                         tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1681                         tx->supercontents = mod_q1bsp_texture_water.supercontents;
1682                         tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1683                 }
1684                 else
1685                 {
1686                         tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1687                         tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1688                 }
1689                 tx->currentframe = tx;
1690
1691                 // clear water settings
1692                 tx->reflectmin = 0;
1693                 tx->reflectmax = 1;
1694                 tx->refractfactor = 1;
1695                 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1696                 tx->reflectfactor = 1;
1697                 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1698                 tx->r_water_wateralpha = 1;
1699                 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1700                 tx->offsetscale = 1;
1701                 tx->offsetbias = 0;
1702                 tx->specularscalemod = 1;
1703                 tx->specularpowermod = 1;
1704                 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1705                 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1706                 // JUST GREP FOR "specularscalemod = 1".
1707         }
1708
1709         if (!sb->cursize)
1710         {
1711                 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1712                 return;
1713         }
1714
1715         s = loadmodel->name;
1716         if (!strncasecmp(s, "maps/", 5))
1717                 s += 5;
1718         FS_StripExtension(s, mapname, sizeof(mapname));
1719
1720         // just to work around bounds checking when debugging with it (array index out of bounds error thing)
1721         // LordHavoc: mostly rewritten map texture loader
1722         for (i = 0;i < nummiptex;i++)
1723         {
1724                 doffset = MSG_ReadLittleLong(sb);
1725                 if (r_nosurftextures.integer)
1726                         continue;
1727                 if (doffset == -1)
1728                 {
1729                         Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1730                         continue;
1731                 }
1732
1733                 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1734
1735                 // copy name, but only up to 16 characters
1736                 // (the output buffer can hold more than this, but the input buffer is
1737                 //  only 16)
1738                 for (j = 0;j < 16;j++)
1739                         name[j] = MSG_ReadByte(&miptexsb);
1740                 name[j] = 0;
1741                 // pretty up the buffer (replacing any trailing garbage with 0)
1742                 for (j = (int)strlen(name);j < 16;j++)
1743                         name[j] = 0;
1744
1745                 if (!name[0])
1746                 {
1747                         dpsnprintf(name, sizeof(name), "unnamed%i", i);
1748                         Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1749                 }
1750
1751                 mtwidth = MSG_ReadLittleLong(&miptexsb);
1752                 mtheight = MSG_ReadLittleLong(&miptexsb);
1753                 mtdata = NULL;
1754                 j = MSG_ReadLittleLong(&miptexsb);
1755                 if (j)
1756                 {
1757                         // texture included
1758                         if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1759                         {
1760                                 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1761                                 continue;
1762                         }
1763                         mtdata = miptexsb.data + j;
1764                 }
1765
1766                 if ((mtwidth & 15) || (mtheight & 15))
1767                         Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1768
1769                 // LordHavoc: force all names to lowercase
1770                 for (j = 0;name[j];j++)
1771                         if (name[j] >= 'A' && name[j] <= 'Z')
1772                                 name[j] += 'a' - 'A';
1773
1774                 // LordHavoc: backup the texture_t because q3 shader loading overwrites it
1775                 backuptex = loadmodel->data_textures[i];
1776                 if (name[0] && Mod_LoadTextureFromQ3Shader(loadmodel->data_textures + i, name, false, false, 0))
1777                         continue;
1778                 loadmodel->data_textures[i] = backuptex;
1779
1780                 tx = loadmodel->data_textures + i;
1781                 strlcpy(tx->name, name, sizeof(tx->name));
1782                 tx->width = mtwidth;
1783                 tx->height = mtheight;
1784                 tx->basealpha = 1.0f;
1785
1786                 // start out with no animation
1787                 tx->currentframe = tx;
1788                 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
1789
1790                 if (tx->name[0] == '*')
1791                 {
1792                         if (!strncmp(tx->name, "*lava", 5))
1793                         {
1794                                 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1795                                 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1796                         }
1797                         else if (!strncmp(tx->name, "*slime", 6))
1798                         {
1799                                 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1800                                 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1801                         }
1802                         else
1803                         {
1804                                 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1805                                 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1806                         }
1807                 }
1808                 else if (!strncmp(tx->name, "sky", 3))
1809                 {
1810                         tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1811                         tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1812                         // for the surface traceline we need to hit this surface as a solid...
1813                         tx->supercontents |= SUPERCONTENTS_SOLID;
1814                 }
1815                 else
1816                 {
1817                         tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1818                         tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1819                 }
1820
1821                 if (cls.state != ca_dedicated)
1822                 {
1823                         // LordHavoc: HL sky textures are entirely different than quake
1824                         if (!loadmodel->brush.ishlbsp && !strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1825                         {
1826                                 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1827                                 if (!data)
1828                                         data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1829                                 if (data && image_width == image_height * 2)
1830                                 {
1831                                         R_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1832                                         Mem_Free(data);
1833                                 }
1834                                 else if (mtdata != NULL)
1835                                         R_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1836                         }
1837                         else
1838                         {
1839                                 skinframe_t *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);
1840                                 if (!skinframe)
1841                                         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);
1842                                 if (skinframe)
1843                                         tx->offsetmapping = OFFSETMAPPING_DEFAULT; // allow offsetmapping on external textures without a q3 shader
1844                                 if (!skinframe)
1845                                 {
1846                                         // did not find external texture, load it from the bsp or wad3
1847                                         if (loadmodel->brush.ishlbsp)
1848                                         {
1849                                                 // internal texture overrides wad
1850                                                 unsigned char *pixels, *freepixels;
1851                                                 pixels = freepixels = NULL;
1852                                                 if (mtdata)
1853                                                         pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1854                                                 if (pixels == NULL)
1855                                                         pixels = freepixels = W_GetTextureBGRA(tx->name);
1856                                                 if (pixels != NULL)
1857                                                 {
1858                                                         tx->width = image_width;
1859                                                         tx->height = image_height;
1860                                                         skinframe = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, true);
1861                                                 }
1862                                                 if (freepixels)
1863                                                         Mem_Free(freepixels);
1864                                         }
1865                                         else if (mtdata) // texture included
1866                                                 skinframe = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1867                                 }
1868                                 // if skinframe is still NULL the "missing" texture has already been assigned to this
1869                                 if (skinframe)
1870                                         tx->materialshaderpass->skinframes[0] = skinframe;
1871                         }
1872                         // LordHavoc: some Tenebrae textures get replaced by black
1873                         if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1874                                 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, false);
1875                         else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1876                                 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, false);
1877                         tx->currentskinframe = tx->materialshaderpass->skinframes[0];
1878                 }
1879
1880                 tx->basematerialflags = MATERIALFLAG_WALL;
1881                 if (tx->name[0] == '*')
1882                 {
1883                         // LordHavoc: some turbulent textures should not be affected by wateralpha
1884                         if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1885                                 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1886                         else if (!strncmp(tx->name,"*lava",5)
1887                          || !strncmp(tx->name,"*teleport",9)
1888                          || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1889                                 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1890                         else
1891                                 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1892                         if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1893                                 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1894                 }
1895                 else if (tx->name[0] == '{') // fence textures
1896                 {
1897                         tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
1898                 }
1899                 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1900                 {
1901                         // replace the texture with black
1902                         tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1903                 }
1904                 else if (!strncmp(tx->name, "sky", 3))
1905                         tx->basematerialflags = MATERIALFLAG_SKY | MATERIALFLAG_NOSHADOW;
1906                 else if (!strcmp(tx->name, "caulk"))
1907                         tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1908                 else if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1909                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1910                 tx->currentmaterialflags = tx->basematerialflags;
1911         }
1912
1913         // sequence the animations
1914         for (i = 0;i < nummiptex;i++)
1915         {
1916                 tx = loadmodel->data_textures + i;
1917                 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1918                         continue;
1919                 num = tx->name[1];
1920                 if ((num < '0' || num > '9') && (num < 'a' || num > 'j'))
1921                 {
1922                         Con_Printf("Bad animating texture %s\n", tx->name);
1923                         continue;
1924                 }
1925                 if (tx->anim_total[0] || tx->anim_total[1])
1926                         continue;       // already sequenced
1927
1928                 // find the number of frames in the animation
1929                 memset(anims, 0, sizeof(anims));
1930                 memset(altanims, 0, sizeof(altanims));
1931
1932                 for (j = i;j < nummiptex;j++)
1933                 {
1934                         tx2 = loadmodel->data_textures + j;
1935                         if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1936                                 continue;
1937
1938                         num = tx2->name[1];
1939                         if (num >= '0' && num <= '9')
1940                                 anims[num - '0'] = tx2;
1941                         else if (num >= 'a' && num <= 'j')
1942                                 altanims[num - 'a'] = tx2;
1943                         // No need to warn otherwise - we already did above.
1944                 }
1945
1946                 max = altmax = 0;
1947                 for (j = 0;j < 10;j++)
1948                 {
1949                         if (anims[j])
1950                                 max = j + 1;
1951                         if (altanims[j])
1952                                 altmax = j + 1;
1953                 }
1954                 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
1955
1956                 incomplete = false;
1957                 for (j = 0;j < max;j++)
1958                 {
1959                         if (!anims[j])
1960                         {
1961                                 Con_Printf("Missing frame %i of %s\n", j, tx->name);
1962                                 incomplete = true;
1963                         }
1964                 }
1965                 for (j = 0;j < altmax;j++)
1966                 {
1967                         if (!altanims[j])
1968                         {
1969                                 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
1970                                 incomplete = true;
1971                         }
1972                 }
1973                 if (incomplete)
1974                         continue;
1975
1976                 // If we have exactly one frame, something's wrong.
1977                 if (max + altmax <= 1)
1978                 {
1979                         Con_Printf("Texture %s is animated (leading +) but has only one frame\n", tx->name);
1980                 }
1981
1982                 if (altmax < 1)
1983                 {
1984                         // if there is no alternate animation, duplicate the primary
1985                         // animation into the alternate
1986                         altmax = max;
1987                         for (k = 0;k < 10;k++)
1988                                 altanims[k] = anims[k];
1989                 }
1990
1991                 if (max < 1)
1992                 {
1993                         // Warn.
1994                         Con_Printf("Missing frame 0 of %s\n", tx->name);
1995
1996                         // however, we can handle this by duplicating the alternate animation into the primary
1997                         max = altmax;
1998                         for (k = 0;k < 10;k++)
1999                                 anims[k] = altanims[k];
2000                 }
2001
2002
2003                 // link together the primary animation
2004                 for (j = 0;j < max;j++)
2005                 {
2006                         tx2 = anims[j];
2007                         tx2->animated = 1; // q1bsp
2008                         tx2->anim_total[0] = max;
2009                         tx2->anim_total[1] = altmax;
2010                         for (k = 0;k < 10;k++)
2011                         {
2012                                 tx2->anim_frames[0][k] = anims[k];
2013                                 tx2->anim_frames[1][k] = altanims[k];
2014                         }
2015                 }
2016
2017                 // if there really is an alternate anim...
2018                 if (anims[0] != altanims[0])
2019                 {
2020                         // link together the alternate animation
2021                         for (j = 0;j < altmax;j++)
2022                         {
2023                                 tx2 = altanims[j];
2024                                 tx2->animated = 1; // q1bsp
2025                                 // the primary/alternate are reversed here
2026                                 tx2->anim_total[0] = altmax;
2027                                 tx2->anim_total[1] = max;
2028                                 for (k = 0;k < 10;k++)
2029                                 {
2030                                         tx2->anim_frames[0][k] = altanims[k];
2031                                         tx2->anim_frames[1][k] = anims[k];
2032                                 }
2033                         }
2034                 }
2035         }
2036 }
2037
2038 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2039 {
2040         int i;
2041         unsigned char *in, *out, *data, d;
2042         char litfilename[MAX_QPATH];
2043         char dlitfilename[MAX_QPATH];
2044         fs_offset_t filesize;
2045         if (loadmodel->brush.ishlbsp) // LordHavoc: load the colored lighting data straight
2046         {
2047                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2048                 for (i = 0;i < sb->cursize;i++)
2049                         loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2050         }
2051         else // LordHavoc: bsp version 29 (normal white lighting)
2052         {
2053                 // LordHavoc: hope is not lost yet, check for a .lit file to load
2054                 strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2055                 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2056                 strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2057                 strlcat (litfilename, ".lit", sizeof (litfilename));
2058                 strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2059                 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2060                 if (data)
2061                 {
2062                         if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2063                         {
2064                                 i = LittleLong(((int *)data)[1]);
2065                                 if (i == 1)
2066                                 {
2067                                         if (developer_loading.integer)
2068                                                 Con_Printf("loaded %s\n", litfilename);
2069                                         loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2070                                         memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2071                                         Mem_Free(data);
2072                                         data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2073                                         if (data)
2074                                         {
2075                                                 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2076                                                 {
2077                                                         i = LittleLong(((int *)data)[1]);
2078                                                         if (i == 1)
2079                                                         {
2080                                                                 if (developer_loading.integer)
2081                                                                         Con_Printf("loaded %s\n", dlitfilename);
2082                                                                 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2083                                                                 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2084                                                                 loadmodel->brushq3.deluxemapping_modelspace = false;
2085                                                                 loadmodel->brushq3.deluxemapping = true;
2086                                                         }
2087                                                 }
2088                                                 Mem_Free(data);
2089                                                 data = NULL;
2090                                         }
2091                                         return;
2092                                 }
2093                                 else
2094                                         Con_Printf("Unknown .lit file version (%d)\n", i);
2095                         }
2096                         else if (filesize == 8)
2097                                 Con_Print("Empty .lit file, ignoring\n");
2098                         else
2099                                 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2100                         if (data)
2101                         {
2102                                 Mem_Free(data);
2103                                 data = NULL;
2104                         }
2105                 }
2106                 // LordHavoc: oh well, expand the white lighting data
2107                 if (!sb->cursize)
2108                         return;
2109                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2110                 in = sb->data;
2111                 out = loadmodel->brushq1.lightdata;
2112                 for (i = 0;i < sb->cursize;i++)
2113                 {
2114                         d = *in++;
2115                         *out++ = d;
2116                         *out++ = d;
2117                         *out++ = d;
2118                 }
2119         }
2120 }
2121
2122 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2123 {
2124         loadmodel->brushq1.num_compressedpvs = 0;
2125         loadmodel->brushq1.data_compressedpvs = NULL;
2126         if (!sb->cursize)
2127                 return;
2128         loadmodel->brushq1.num_compressedpvs = sb->cursize;
2129         loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2130         MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2131 }
2132
2133 // used only for HalfLife maps
2134 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2135 {
2136         char key[128], value[4096];
2137         int i, j, k;
2138         if (!data)
2139                 return;
2140         if (!COM_ParseToken_Simple(&data, false, false, true))
2141                 return; // error
2142         if (com_token[0] != '{')
2143                 return; // error
2144         while (1)
2145         {
2146                 if (!COM_ParseToken_Simple(&data, false, false, true))
2147                         return; // error
2148                 if (com_token[0] == '}')
2149                         break; // end of worldspawn
2150                 if (com_token[0] == '_')
2151                         strlcpy(key, com_token + 1, sizeof(key));
2152                 else
2153                         strlcpy(key, com_token, sizeof(key));
2154                 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2155                         key[strlen(key)-1] = 0;
2156                 if (!COM_ParseToken_Simple(&data, false, false, true))
2157                         return; // error
2158                 dpsnprintf(value, sizeof(value), "%s", com_token);
2159                 if (!strcmp("wad", key)) // for HalfLife maps
2160                 {
2161                         if (loadmodel->brush.ishlbsp)
2162                         {
2163                                 j = 0;
2164                                 for (i = 0;i < (int)sizeof(value);i++)
2165                                         if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2166                                                 break;
2167                                 if (i < (int)sizeof(value) && value[i])
2168                                 {
2169                                         for (;i < (int)sizeof(value);i++)
2170                                         {
2171                                                 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2172                                                 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2173                                                         j = i+1;
2174                                                 else if (value[i] == ';' || value[i] == 0)
2175                                                 {
2176                                                         k = value[i];
2177                                                         value[i] = 0;
2178                                                         W_LoadTextureWadFile(&value[j], false);
2179                                                         j = i+1;
2180                                                         if (!k)
2181                                                                 break;
2182                                                 }
2183                                         }
2184                                 }
2185                         }
2186                 }
2187         }
2188 }
2189
2190 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2191 {
2192         loadmodel->brush.entities = NULL;
2193         if (!sb->cursize)
2194                 return;
2195         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2196         MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2197         loadmodel->brush.entities[sb->cursize] = 0;
2198         if (loadmodel->brush.ishlbsp)
2199                 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2200 }
2201
2202
2203 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2204 {
2205         mvertex_t       *out;
2206         int                     i, count;
2207         int                     structsize = 12;
2208
2209         if (sb->cursize % structsize)
2210                 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2211         count = sb->cursize / structsize;
2212         out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2213
2214         loadmodel->brushq1.vertexes = out;
2215         loadmodel->brushq1.numvertexes = count;
2216
2217         for ( i=0 ; i<count ; i++, out++)
2218         {
2219                 out->position[0] = MSG_ReadLittleFloat(sb);
2220                 out->position[1] = MSG_ReadLittleFloat(sb);
2221                 out->position[2] = MSG_ReadLittleFloat(sb);
2222         }
2223 }
2224
2225 static void Mod_Q1BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2226 {
2227         mmodel_t        *out;
2228         int                     i, j, count;
2229         int                     structsize = (48+4*hullinfo->filehulls);
2230
2231         if (sb->cursize % structsize)
2232                 Host_Error ("Mod_Q1BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2233
2234         count = sb->cursize / structsize;
2235         out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2236
2237         loadmodel->brushq1.submodels = out;
2238         loadmodel->brush.numsubmodels = count;
2239
2240         for (i = 0; i < count; i++, out++)
2241         {
2242         // spread out the mins / maxs by a pixel
2243                 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2244                 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2245                 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2246                 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2247                 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2248                 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2249                 out->origin[0] = MSG_ReadLittleFloat(sb);
2250                 out->origin[1] = MSG_ReadLittleFloat(sb);
2251                 out->origin[2] = MSG_ReadLittleFloat(sb);
2252                 for (j = 0; j < hullinfo->filehulls; j++)
2253                         out->headnode[j] = MSG_ReadLittleLong(sb);
2254                 out->visleafs  = MSG_ReadLittleLong(sb);
2255                 out->firstface = MSG_ReadLittleLong(sb);
2256                 out->numfaces  = MSG_ReadLittleLong(sb);
2257         }
2258 }
2259
2260 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2261 {
2262         medge_t *out;
2263         int     i, count;
2264         int             structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2265
2266         if (sb->cursize % structsize)
2267                 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2268         count = sb->cursize / structsize;
2269         out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2270
2271         loadmodel->brushq1.edges = out;
2272         loadmodel->brushq1.numedges = count;
2273
2274         for ( i=0 ; i<count ; i++, out++)
2275         {
2276                 if (loadmodel->brush.isbsp2)
2277                 {
2278                         out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2279                         out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2280                 }
2281                 else
2282                 {
2283                         out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2284                         out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2285                 }
2286                 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2287                 {
2288                         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);
2289                         if(!loadmodel->brushq1.numvertexes)
2290                                 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2291                                 
2292                         out->v[0] = 0;
2293                         out->v[1] = 0;
2294                 }
2295         }
2296 }
2297
2298 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2299 {
2300         mtexinfo_t *out;
2301         int i, j, k, count, miptex;
2302         int structsize = 40;
2303
2304         if (sb->cursize % structsize)
2305                 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2306         count = sb->cursize / structsize;
2307         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2308
2309         loadmodel->brushq1.texinfo = out;
2310         loadmodel->brushq1.numtexinfo = count;
2311
2312         for (i = 0;i < count;i++, out++)
2313         {
2314                 for (k = 0;k < 2;k++)
2315                         for (j = 0;j < 4;j++)
2316                                 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2317
2318                 miptex = MSG_ReadLittleLong(sb);
2319                 out->q1flags = MSG_ReadLittleLong(sb);
2320
2321                 if (out->q1flags & TEX_SPECIAL)
2322                 {
2323                         // if texture chosen is NULL or the shader needs a lightmap,
2324                         // force to notexture water shader
2325                         out->textureindex = loadmodel->num_textures - 1;
2326                 }
2327                 else
2328                 {
2329                         // if texture chosen is NULL, force to notexture
2330                         out->textureindex = loadmodel->num_textures - 2;
2331                 }
2332                 // see if the specified miptex is valid and try to use it instead
2333                 if (loadmodel->data_textures)
2334                 {
2335                         if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2336                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2337                         else
2338                                 out->textureindex = miptex;
2339                 }
2340         }
2341 }
2342
2343 #if 0
2344 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2345 {
2346         int             i, j;
2347         float   *v;
2348
2349         mins[0] = mins[1] = mins[2] = 9999;
2350         maxs[0] = maxs[1] = maxs[2] = -9999;
2351         v = verts;
2352         for (i = 0;i < numverts;i++)
2353         {
2354                 for (j = 0;j < 3;j++, v++)
2355                 {
2356                         if (*v < mins[j])
2357                                 mins[j] = *v;
2358                         if (*v > maxs[j])
2359                                 maxs[j] = *v;
2360                 }
2361         }
2362 }
2363
2364 #define MAX_SUBDIVPOLYTRIANGLES 4096
2365 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2366
2367 static int subdivpolyverts, subdivpolytriangles;
2368 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2369 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2370
2371 static int subdivpolylookupvert(vec3_t v)
2372 {
2373         int i;
2374         for (i = 0;i < subdivpolyverts;i++)
2375                 if (subdivpolyvert[i][0] == v[0]
2376                  && subdivpolyvert[i][1] == v[1]
2377                  && subdivpolyvert[i][2] == v[2])
2378                         return i;
2379         if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2380                 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2381         VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2382         return subdivpolyverts++;
2383 }
2384
2385 static void SubdividePolygon(int numverts, float *verts)
2386 {
2387         int             i, i1, i2, i3, f, b, c, p;
2388         vec3_t  mins, maxs, front[256], back[256];
2389         float   m, *pv, *cv, dist[256], frac;
2390
2391         if (numverts > 250)
2392                 Host_Error("SubdividePolygon: ran out of verts in buffer");
2393
2394         BoundPoly(numverts, verts, mins, maxs);
2395
2396         for (i = 0;i < 3;i++)
2397         {
2398                 m = (mins[i] + maxs[i]) * 0.5;
2399                 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2400                 if (maxs[i] - m < 8)
2401                         continue;
2402                 if (m - mins[i] < 8)
2403                         continue;
2404
2405                 // cut it
2406                 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2407                         dist[c] = cv[i] - m;
2408
2409                 f = b = 0;
2410                 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2411                 {
2412                         if (dist[p] >= 0)
2413                         {
2414                                 VectorCopy(pv, front[f]);
2415                                 f++;
2416                         }
2417                         if (dist[p] <= 0)
2418                         {
2419                                 VectorCopy(pv, back[b]);
2420                                 b++;
2421                         }
2422                         if (dist[p] == 0 || dist[c] == 0)
2423                                 continue;
2424                         if ((dist[p] > 0) != (dist[c] > 0) )
2425                         {
2426                                 // clip point
2427                                 frac = dist[p] / (dist[p] - dist[c]);
2428                                 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2429                                 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2430                                 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2431                                 f++;
2432                                 b++;
2433                         }
2434                 }
2435
2436                 SubdividePolygon(f, front[0]);
2437                 SubdividePolygon(b, back[0]);
2438                 return;
2439         }
2440
2441         i1 = subdivpolylookupvert(verts);
2442         i2 = subdivpolylookupvert(verts + 3);
2443         for (i = 2;i < numverts;i++)
2444         {
2445                 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2446                 {
2447                         Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2448                         return;
2449                 }
2450
2451                 i3 = subdivpolylookupvert(verts + i * 3);
2452                 subdivpolyindex[subdivpolytriangles][0] = i1;
2453                 subdivpolyindex[subdivpolytriangles][1] = i2;
2454                 subdivpolyindex[subdivpolytriangles][2] = i3;
2455                 i2 = i3;
2456                 subdivpolytriangles++;
2457         }
2458 }
2459
2460 //Breaks a polygon up along axial 64 unit
2461 //boundaries so that turbulent and sky warps
2462 //can be done reasonably.
2463 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2464 {
2465         int i, j;
2466         surfvertex_t *v;
2467         surfmesh_t *mesh;
2468
2469         subdivpolytriangles = 0;
2470         subdivpolyverts = 0;
2471         SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2472         if (subdivpolytriangles < 1)
2473                 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2474
2475         surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2476         mesh->num_vertices = subdivpolyverts;
2477         mesh->num_triangles = subdivpolytriangles;
2478         mesh->vertex = (surfvertex_t *)(mesh + 1);
2479         mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2480         memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2481
2482         for (i = 0;i < mesh->num_triangles;i++)
2483                 for (j = 0;j < 3;j++)
2484                         mesh->index[i*3+j] = subdivpolyindex[i][j];
2485
2486         for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2487         {
2488                 VectorCopy(subdivpolyvert[i], v->v);
2489                 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2490                 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2491         }
2492 }
2493 #endif
2494
2495 extern cvar_t gl_max_lightmapsize;
2496 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2497 {
2498         msurface_t *surface;
2499         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2500         float texmins[2], texmaxs[2], val;
2501         rtexture_t *lightmaptexture, *deluxemaptexture;
2502         char vabuf[1024];
2503         int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2504
2505         if (sb->cursize % structsize)
2506                 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2507         count = sb->cursize / structsize;
2508         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2509         loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2510
2511         loadmodel->num_surfaces = count;
2512
2513         loadmodel->brushq1.firstrender = true;
2514         loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2515
2516         totalverts = 0;
2517         totaltris = 0;
2518         for (surfacenum = 0;surfacenum < count;surfacenum++)
2519         {
2520                 if (loadmodel->brush.isbsp2)
2521                         numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2522                 else
2523                         numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2524                 totalverts += numedges;
2525                 totaltris += numedges - 2;
2526         }
2527
2528         Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false, false);
2529
2530         lightmaptexture = NULL;
2531         deluxemaptexture = r_texture_blanknormalmap;
2532         lightmapnumber = 0;
2533         lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2534         totallightmapsamples = 0;
2535
2536         totalverts = 0;
2537         totaltris = 0;
2538         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2539         {
2540                 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2541                 // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
2542                 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2543                 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2544                 firstedge = MSG_ReadLittleLong(sb);
2545                 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2546                 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2547                 for (i = 0;i < MAXLIGHTMAPS;i++)
2548                         surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2549                 lightmapoffset = MSG_ReadLittleLong(sb);
2550
2551                 // FIXME: validate edges, texinfo, etc?
2552                 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)
2553                         Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2554                 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2555                         Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2556                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2557                         Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2558
2559                 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2560                 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
2561
2562                 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
2563                 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
2564                         lightmapoffset = -1;
2565
2566                 //surface->flags = surface->texture->flags;
2567                 //if (LittleShort(in->side))
2568                 //      surface->flags |= SURF_PLANEBACK;
2569                 //surface->plane = loadmodel->brush.data_planes + planenum;
2570
2571                 surface->num_firstvertex = totalverts;
2572                 surface->num_vertices = numedges;
2573                 surface->num_firsttriangle = totaltris;
2574                 surface->num_triangles = numedges - 2;
2575                 totalverts += numedges;
2576                 totaltris += numedges - 2;
2577
2578                 // convert edges back to a normal polygon
2579                 for (i = 0;i < surface->num_vertices;i++)
2580                 {
2581                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2582                         float s, t;
2583                         // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2584                         if (lindex >= 0)
2585                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2586                         else
2587                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2588                         s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2589                         t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2590                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2591                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2592                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2593                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2594                         (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2595                 }
2596
2597                 for (i = 0;i < surface->num_triangles;i++)
2598                 {
2599                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2600                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2601                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2602                 }
2603
2604                 // compile additional data about the surface geometry
2605                 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);
2606                 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);
2607                 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2608
2609                 // generate surface extents information
2610                 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2611                 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2612                 for (i = 1;i < surface->num_vertices;i++)
2613                 {
2614                         for (j = 0;j < 2;j++)
2615                         {
2616                                 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2617                                 texmins[j] = min(texmins[j], val);
2618                                 texmaxs[j] = max(texmaxs[j], val);
2619                         }
2620                 }
2621                 for (i = 0;i < 2;i++)
2622                 {
2623                         surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2624                         surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2625                 }
2626
2627                 smax = surface->lightmapinfo->extents[0] >> 4;
2628                 tmax = surface->lightmapinfo->extents[1] >> 4;
2629                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2630                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2631
2632                 // lighting info
2633                 surface->lightmaptexture = NULL;
2634                 surface->deluxemaptexture = r_texture_blanknormalmap;
2635                 if (lightmapoffset == -1)
2636                 {
2637                         surface->lightmapinfo->samples = NULL;
2638 #if 1
2639                         // give non-lightmapped water a 1x white lightmap
2640                         if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2641                         {
2642                                 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2643                                 surface->lightmapinfo->styles[0] = 0;
2644                                 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2645                         }
2646 #endif
2647                 }
2648                 else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LordHavoc: HalfLife map (bsp version 30)
2649                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2650                 else // LordHavoc: white lighting (bsp version 29)
2651                 {
2652                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2653                         if (loadmodel->brushq1.nmaplightdata)
2654                                 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2655                 }
2656
2657                 // check if we should apply a lightmap to this
2658                 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2659                 {
2660                         if (ssize > 256 || tsize > 256)
2661                                 Host_Error("Bad surface extents");
2662
2663                         if (lightmapsize < ssize)
2664                                 lightmapsize = ssize;
2665                         if (lightmapsize < tsize)
2666                                 lightmapsize = tsize;
2667
2668                         totallightmapsamples += ssize*tsize;
2669
2670                         // force lightmap upload on first time seeing the surface
2671                         //
2672                         // additionally this is used by the later code to see if a
2673                         // lightmap is needed on this surface (rather than duplicating the
2674                         // logic above)
2675                         loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2676                         loadmodel->lit = true;
2677                 }
2678         }
2679
2680         // small maps (such as ammo boxes especially) don't need big lightmap
2681         // textures, so this code tries to guess a good size based on
2682         // totallightmapsamples (size of the lightmaps lump basically), as well as
2683         // trying to max out the size if there is a lot of lightmap data to store
2684         // additionally, never choose a lightmapsize that is smaller than the
2685         // largest surface encountered (as it would fail)
2686         i = lightmapsize;
2687         for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2688                 ;
2689
2690         // now that we've decided the lightmap texture size, we can do the rest
2691         if (cls.state != ca_dedicated)
2692         {
2693                 int stainmapsize = 0;
2694                 mod_alloclightmap_state_t allocState;
2695
2696                 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
2697                 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2698                 {
2699                         int iu, iv, lightmapx = 0, lightmapy = 0;
2700                         float u, v, ubase, vbase, uscale, vscale;
2701
2702                         if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2703                                 continue;
2704
2705                         smax = surface->lightmapinfo->extents[0] >> 4;
2706                         tmax = surface->lightmapinfo->extents[1] >> 4;
2707                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2708                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2709                         stainmapsize += ssize * tsize * 3;
2710
2711                         if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2712                         {
2713                                 // allocate a texture pool if we need it
2714                                 if (loadmodel->texturepool == NULL)
2715                                         loadmodel->texturepool = R_AllocTexturePool();
2716                                 // could not find room, make a new lightmap
2717                                 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2718                                 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2719                                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2720                                 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);
2721                                 if (loadmodel->brushq1.nmaplightdata)
2722                                         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);
2723                                 lightmapnumber++;
2724                                 Mod_AllocLightmap_Reset(&allocState);
2725                                 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2726                         }
2727                         surface->lightmaptexture = lightmaptexture;
2728                         surface->deluxemaptexture = deluxemaptexture;
2729                         surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2730                         surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2731
2732                         uscale = 1.0f / (float)lightmapsize;
2733                         vscale = 1.0f / (float)lightmapsize;
2734                         ubase = lightmapx * uscale;
2735                         vbase = lightmapy * vscale;
2736
2737                         for (i = 0;i < surface->num_vertices;i++)
2738                         {
2739                                 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);
2740                                 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);
2741                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2742                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2743                                 // LordHavoc: calc lightmap data offset for vertex lighting to use
2744                                 iu = (int) u;
2745                                 iv = (int) v;
2746                                 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2747                         }
2748                 }
2749
2750                 if (cl_stainmaps.integer)
2751                 {
2752                         // allocate stainmaps for permanent marks on walls and clear white
2753                         unsigned char *stainsamples = NULL;
2754                         stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2755                         memset(stainsamples, 255, stainmapsize);
2756                         // assign pointers
2757                         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2758                         {
2759                                 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2760                                         continue;
2761                                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2762                                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2763                                 surface->lightmapinfo->stainsamples = stainsamples;
2764                                 stainsamples += ssize * tsize * 3;
2765                         }
2766                 }
2767         }
2768
2769         // generate ushort elements array if possible
2770         if (loadmodel->surfmesh.data_element3s)
2771                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2772                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2773 }
2774
2775 static void Mod_Q1BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2776 {
2777         //if (node->parent)
2778         //      Host_Error("Mod_Q1BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2779         node->parent = parent;
2780         if (node->plane)
2781         {
2782                 // this is a node, recurse to children
2783                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2784                 Mod_Q1BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2785                 // combine supercontents of children
2786                 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2787         }
2788         else
2789         {
2790                 int j;
2791                 mleaf_t *leaf = (mleaf_t *)node;
2792                 // if this is a leaf, calculate supercontents mask from all collidable
2793                 // primitives in the leaf (brushes and collision surfaces)
2794                 // also flag if the leaf contains any collision surfaces
2795                 leaf->combinedsupercontents = 0;
2796                 // combine the supercontents values of all brushes in this leaf
2797                 for (j = 0;j < leaf->numleafbrushes;j++)
2798                         leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2799                 // check if this leaf contains any collision surfaces (q3 patches)
2800                 for (j = 0;j < leaf->numleafsurfaces;j++)
2801                 {
2802                         msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2803                         if (surface->num_collisiontriangles)
2804                         {
2805                                 leaf->containscollisionsurfaces = true;
2806                                 leaf->combinedsupercontents |= surface->texture->supercontents;
2807                         }
2808                 }
2809         }
2810 }
2811
2812 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2813 {
2814         int                     i, j, count, p, child[2];
2815         mnode_t         *out;
2816         int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2817
2818         if (sb->cursize % structsize)
2819                 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2820         count = sb->cursize / structsize;
2821         if (count == 0)
2822                 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2823         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2824
2825         loadmodel->brush.data_nodes = out;
2826         loadmodel->brush.num_nodes = count;
2827
2828         for ( i=0 ; i<count ; i++, out++)
2829         {
2830                 p = MSG_ReadLittleLong(sb);
2831                 out->plane = loadmodel->brush.data_planes + p;
2832
2833                 if (loadmodel->brush.isbsp2rmqe)
2834                 {
2835                         child[0] = MSG_ReadLittleLong(sb);
2836                         child[1] = MSG_ReadLittleLong(sb);
2837                         out->mins[0] = MSG_ReadLittleShort(sb);
2838                         out->mins[1] = MSG_ReadLittleShort(sb);
2839                         out->mins[2] = MSG_ReadLittleShort(sb);
2840                         out->maxs[0] = MSG_ReadLittleShort(sb);
2841                         out->maxs[1] = MSG_ReadLittleShort(sb);
2842                         out->maxs[2] = MSG_ReadLittleShort(sb);
2843                         out->firstsurface = MSG_ReadLittleLong(sb);
2844                         out->numsurfaces = MSG_ReadLittleLong(sb);
2845                 }
2846                 else if (loadmodel->brush.isbsp2)
2847                 {
2848                         child[0] = MSG_ReadLittleLong(sb);
2849                         child[1] = MSG_ReadLittleLong(sb);
2850                         out->mins[0] = MSG_ReadLittleFloat(sb);
2851                         out->mins[1] = MSG_ReadLittleFloat(sb);
2852                         out->mins[2] = MSG_ReadLittleFloat(sb);
2853                         out->maxs[0] = MSG_ReadLittleFloat(sb);
2854                         out->maxs[1] = MSG_ReadLittleFloat(sb);
2855                         out->maxs[2] = MSG_ReadLittleFloat(sb);
2856                         out->firstsurface = MSG_ReadLittleLong(sb);
2857                         out->numsurfaces = MSG_ReadLittleLong(sb);
2858                 }
2859                 else
2860                 {
2861                         child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2862                         child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2863                         if (child[0] >= count)
2864                                 child[0] -= 65536;
2865                         if (child[1] >= count)
2866                                 child[1] -= 65536;
2867
2868                         out->mins[0] = MSG_ReadLittleShort(sb);
2869                         out->mins[1] = MSG_ReadLittleShort(sb);
2870                         out->mins[2] = MSG_ReadLittleShort(sb);
2871                         out->maxs[0] = MSG_ReadLittleShort(sb);
2872                         out->maxs[1] = MSG_ReadLittleShort(sb);
2873                         out->maxs[2] = MSG_ReadLittleShort(sb);
2874
2875                         out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2876                         out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2877                 }
2878
2879                 for (j=0 ; j<2 ; j++)
2880                 {
2881                         // LordHavoc: this code supports broken bsp files produced by
2882                         // arguire qbsp which can produce more than 32768 nodes, any value
2883                         // below count is assumed to be a node number, any other value is
2884                         // assumed to be a leaf number
2885                         p = child[j];
2886                         if (p >= 0)
2887                         {
2888                                 if (p < loadmodel->brush.num_nodes)
2889                                         out->children[j] = loadmodel->brush.data_nodes + p;
2890                                 else
2891                                 {
2892                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2893                                         // map it to the solid leaf
2894                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2895                                 }
2896                         }
2897                         else
2898                         {
2899                                 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2900                                 p = -(p+1);