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