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