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