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