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