]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - model_brush.c
3357d0dfe6968920bd025a6d2afc7f1e7c76f380
[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_trippy = {CF_CLIENT, "r_trippy", "0", "easter egg"};
30 //cvar_t r_subdivide_size = {CF_CLIENT | CF_ARCHIVE, "r_subdivide_size", "128", "how large water polygons should be (smaller values produce more polygons which give better warping effects)"};
31 cvar_t r_novis = {CF_CLIENT, "r_novis", "0", "draws whole level, see also sv_cullentities_pvs 0"};
32 cvar_t r_nosurftextures = {CF_CLIENT, "r_nosurftextures", "0", "pretends there was no texture lump found in the q1bsp/hlbsp loading (useful for debugging this rare case)"};
33
34 cvar_t r_subdivisions_tolerance = {CF_CLIENT, "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)"};
35 cvar_t r_subdivisions_mintess = {CF_CLIENT, "r_subdivisions_mintess", "0", "minimum number of subdivisions (values above 0 will smooth curves that don't need it)"};
36 cvar_t r_subdivisions_maxtess = {CF_CLIENT, "r_subdivisions_maxtess", "1024", "maximum number of subdivisions (prevents curves beyond a certain detail level, limits smoothing)"};
37 cvar_t r_subdivisions_maxvertices = {CF_CLIENT, "r_subdivisions_maxvertices", "65536", "maximum vertices allowed per subdivided curve"};
38 cvar_t mod_q3bsp_curves_subdivisions_tolerance = {CF_CLIENT | CF_SERVER, "mod_q3bsp_curves_subdivisions_tolerance", "15", "maximum error tolerance on curve subdivision for collision purposes (usually a larger error tolerance than for rendering)"};
39 cvar_t mod_q3bsp_curves_subdivisions_mintess = {CF_CLIENT | CF_SERVER, "mod_q3bsp_curves_subdivisions_mintess", "0", "minimum number of subdivisions for collision purposes (values above 0 will smooth curves that don't need it)"};
40 cvar_t mod_q3bsp_curves_subdivisions_maxtess = {CF_CLIENT | CF_SERVER, "mod_q3bsp_curves_subdivisions_maxtess", "1024", "maximum number of subdivisions for collision purposes (prevents curves beyond a certain detail level, limits smoothing)"};
41 cvar_t mod_q3bsp_curves_subdivisions_maxvertices = {CF_CLIENT | CF_SERVER, "mod_q3bsp_curves_subdivisions_maxvertices", "4225", "maximum vertices allowed per subdivided curve for collision purposes"};
42 cvar_t mod_q3bsp_curves_collisions = {CF_CLIENT | CF_SERVER, "mod_q3bsp_curves_collisions", "1", "enables collisions with curves (SLOW)"};
43 cvar_t mod_q3bsp_optimizedtraceline = {CF_CLIENT | CF_SERVER, "mod_q3bsp_optimizedtraceline", "1", "whether to use optimized traceline code for line traces (as opposed to tracebox code)"};
44 cvar_t mod_q3bsp_lightmapmergepower = {CF_CLIENT | CF_ARCHIVE, "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, ..."};
45 cvar_t mod_q3bsp_nolightmaps = {CF_CLIENT | CF_ARCHIVE, "mod_q3bsp_nolightmaps", "0", "do not load lightmaps in Q3BSP maps (to save video RAM, but be warned: it looks ugly)"};
46 cvar_t mod_q3bsp_tracelineofsight_brushes = {CF_CLIENT | CF_SERVER, "mod_q3bsp_tracelineofsight_brushes", "0", "enables culling of entities behind detail brushes, curves, etc"};
47 cvar_t mod_q3bsp_sRGBlightmaps = {CF_CLIENT, "mod_q3bsp_sRGBlightmaps", "0", "treat lightmaps from Q3 maps as sRGB when vid_sRGB is active"};
48 cvar_t mod_q3bsp_lightgrid_texture = {CF_CLIENT, "mod_q3bsp_lightgrid_texture", "1", "directly apply the lightgrid as a global texture rather than only reading it at the entity origin"};
49 cvar_t mod_q3bsp_lightgrid_world_surfaces = {CF_CLIENT, "mod_q3bsp_lightgrid_world_surfaces", "0", "apply lightgrid lighting to the world bsp geometry rather than using lightmaps (experimental/debug tool)"};
50 cvar_t mod_q3bsp_lightgrid_bsp_surfaces = {CF_CLIENT, "mod_q3bsp_lightgrid_bsp_surfaces", "0", "apply lightgrid lighting to bsp models other than the world rather than using their lightmaps (experimental/debug tool)"};
51 cvar_t mod_noshader_default_offsetmapping = {CF_CLIENT | CF_ARCHIVE, "mod_noshader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are not using q3 shader files"};
52 cvar_t mod_q3shader_default_offsetmapping = {CF_CLIENT | CF_ARCHIVE, "mod_q3shader_default_offsetmapping", "1", "use offsetmapping by default on all surfaces that are using q3 shader files"};
53 cvar_t mod_q3shader_default_offsetmapping_scale = {CF_CLIENT | CF_ARCHIVE, "mod_q3shader_default_offsetmapping_scale", "1", "default scale used for offsetmapping"};
54 cvar_t mod_q3shader_default_offsetmapping_bias = {CF_CLIENT | CF_ARCHIVE, "mod_q3shader_default_offsetmapping_bias", "0", "default bias used for offsetmapping"};
55 cvar_t mod_q3shader_default_polygonfactor = {CF_CLIENT, "mod_q3shader_default_polygonfactor", "0", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
56 cvar_t mod_q3shader_default_polygonoffset = {CF_CLIENT, "mod_q3shader_default_polygonoffset", "-2", "biases depth values of 'polygonoffset' shaders to prevent z-fighting artifacts"};
57 cvar_t mod_q3shader_default_refractive_index = {CF_CLIENT, "mod_q3shader_default_refractive_index", "1.33", "angle of refraction specified as n to apply when a photon is refracted, example values are: 1.0003 = air, water = 1.333, crown glass = 1.517, flint glass = 1.655, diamond = 2.417"};
58 cvar_t mod_q3shader_force_addalpha = {CF_CLIENT, "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"};
59 cvar_t mod_q3shader_force_terrain_alphaflag = {CF_CLIENT, "mod_q3shader_force_terrain_alphaflag", "0", "for multilayered terrain shaders force TEXF_ALPHA flag on both layers"};
60
61 cvar_t mod_q2bsp_littransparentsurfaces = {CF_CLIENT, "mod_q2bsp_littransparentsurfaces", "0", "allows lighting on rain in 3v3gloom3 and other cases of transparent surfaces that have lightmaps that were ignored by quake2"};
62
63 cvar_t mod_q1bsp_polygoncollisions = {CF_CLIENT | CF_SERVER, "mod_q1bsp_polygoncollisions", "0", "disables use of precomputed cliphulls and instead collides with polygons (uses Bounding Interval Hierarchy optimizations)"};
64 cvar_t mod_q1bsp_zero_hullsize_cutoff = {CF_CLIENT | CF_SERVER, "mod_q1bsp_zero_hullsize_cutoff", "3", "bboxes with an X dimension smaller than this will use the smallest cliphull (0x0x0) instead of being rounded up to the player cliphull (32x32x56) in Q1BSP, or crouching player (32x32x36) in HLBSP"};
65
66 cvar_t mod_bsp_portalize = {CF_CLIENT, "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_dlight_portalculling, r_shadow_realtime_world_compileportalculling"};
67 cvar_t mod_recalculatenodeboxes = {CF_CLIENT | CF_SERVER, "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"};
68
69 cvar_t mod_obj_orientation = {CF_CLIENT | CF_SERVER, "mod_obj_orientation", "1", "fix orientation of OBJ models to the usual conventions (if zero, use coordinates as is)"};
70
71 static texture_t mod_q1bsp_texture_solid;
72 static texture_t mod_q1bsp_texture_sky;
73 static texture_t mod_q1bsp_texture_lava;
74 static texture_t mod_q1bsp_texture_slime;
75 static texture_t mod_q1bsp_texture_water;
76
77 static qbool Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs);
78
79 void Mod_BrushInit(void)
80 {
81 //      Cvar_RegisterVariable(&r_subdivide_size);
82         Cvar_RegisterVariable(&mod_bsp_portalize);
83         Cvar_RegisterVariable(&r_novis);
84         Cvar_RegisterVariable(&r_nosurftextures);
85         Cvar_RegisterVariable(&r_subdivisions_tolerance);
86         Cvar_RegisterVariable(&r_subdivisions_mintess);
87         Cvar_RegisterVariable(&r_subdivisions_maxtess);
88         Cvar_RegisterVariable(&r_subdivisions_maxvertices);
89         Cvar_RegisterVariable(&mod_q3bsp_curves_subdivisions_tolerance);
90         Cvar_RegisterVariable(&mod_q3bsp_curves_subdivisions_mintess);
91         Cvar_RegisterVariable(&mod_q3bsp_curves_subdivisions_maxtess);
92         Cvar_RegisterVariable(&mod_q3bsp_curves_subdivisions_maxvertices);
93         Cvar_RegisterVariable(&r_trippy);
94         Cvar_RegisterVariable(&mod_noshader_default_offsetmapping);
95         Cvar_RegisterVariable(&mod_obj_orientation);
96         Cvar_RegisterVariable(&mod_q2bsp_littransparentsurfaces);
97         Cvar_RegisterVariable(&mod_q3bsp_curves_collisions);
98         Cvar_RegisterVariable(&mod_q3bsp_optimizedtraceline);
99         Cvar_RegisterVariable(&mod_q3bsp_lightmapmergepower);
100         Cvar_RegisterVariable(&mod_q3bsp_nolightmaps);
101         Cvar_RegisterVariable(&mod_q3bsp_sRGBlightmaps);
102         Cvar_RegisterVariable(&mod_q3bsp_lightgrid_texture);
103         Cvar_RegisterVariable(&mod_q3bsp_lightgrid_world_surfaces);
104         Cvar_RegisterVariable(&mod_q3bsp_lightgrid_bsp_surfaces);
105         Cvar_RegisterVariable(&mod_q3bsp_tracelineofsight_brushes);
106         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping);
107         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_scale);
108         Cvar_RegisterVariable(&mod_q3shader_default_offsetmapping_bias);
109         Cvar_RegisterVariable(&mod_q3shader_default_polygonfactor);
110         Cvar_RegisterVariable(&mod_q3shader_default_polygonoffset);
111         Cvar_RegisterVariable(&mod_q3shader_default_refractive_index);
112         Cvar_RegisterVariable(&mod_q3shader_force_addalpha);
113         Cvar_RegisterVariable(&mod_q3shader_force_terrain_alphaflag);
114         Cvar_RegisterVariable(&mod_q1bsp_polygoncollisions);
115         Cvar_RegisterVariable(&mod_q1bsp_zero_hullsize_cutoff);
116         Cvar_RegisterVariable(&mod_recalculatenodeboxes);
117
118         // these games were made for older DP engines and are no longer
119         // maintained; use this hack to show their textures properly
120         if(gamemode == GAME_NEXUIZ)
121                 Cvar_SetQuick(&mod_q3shader_force_addalpha, "1");
122
123         memset(&mod_q1bsp_texture_solid, 0, sizeof(mod_q1bsp_texture_solid));
124         dp_strlcpy(mod_q1bsp_texture_solid.name, "solid" , sizeof(mod_q1bsp_texture_solid.name));
125         mod_q1bsp_texture_solid.surfaceflags = 0;
126         mod_q1bsp_texture_solid.supercontents = SUPERCONTENTS_SOLID;
127
128         mod_q1bsp_texture_sky = mod_q1bsp_texture_solid;
129         dp_strlcpy(mod_q1bsp_texture_sky.name, "sky", sizeof(mod_q1bsp_texture_sky.name));
130         mod_q1bsp_texture_sky.surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
131         mod_q1bsp_texture_sky.supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP;
132
133         mod_q1bsp_texture_lava = mod_q1bsp_texture_solid;
134         dp_strlcpy(mod_q1bsp_texture_lava.name, "*lava", sizeof(mod_q1bsp_texture_lava.name));
135         mod_q1bsp_texture_lava.surfaceflags = Q3SURFACEFLAG_NOMARKS;
136         mod_q1bsp_texture_lava.supercontents = SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
137
138         mod_q1bsp_texture_slime = mod_q1bsp_texture_solid;
139         dp_strlcpy(mod_q1bsp_texture_slime.name, "*slime", sizeof(mod_q1bsp_texture_slime.name));
140         mod_q1bsp_texture_slime.surfaceflags = Q3SURFACEFLAG_NOMARKS;
141         mod_q1bsp_texture_slime.supercontents = SUPERCONTENTS_SLIME;
142
143         mod_q1bsp_texture_water = mod_q1bsp_texture_solid;
144         dp_strlcpy(mod_q1bsp_texture_water.name, "*water", sizeof(mod_q1bsp_texture_water.name));
145         mod_q1bsp_texture_water.surfaceflags = Q3SURFACEFLAG_NOMARKS;
146         mod_q1bsp_texture_water.supercontents = SUPERCONTENTS_WATER;
147 }
148
149 static mleaf_t *Mod_BSP_PointInLeaf(model_t *model, const vec3_t p)
150 {
151         mnode_t *node;
152
153         if (model == NULL)
154                 return NULL;
155
156         // LadyHavoc: modified to start at first clip node,
157         // in other words: first node of the (sub)model
158         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
159         while (node->plane)
160                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
161
162         return (mleaf_t *)node;
163 }
164
165 static void Mod_Q1BSP_AmbientSoundLevelsForPoint(model_t *model, const vec3_t p, unsigned char *out, int outsize)
166 {
167         int i;
168         mleaf_t *leaf;
169         leaf = Mod_BSP_PointInLeaf(model, p);
170         if (leaf)
171         {
172                 i = min(outsize, (int)sizeof(leaf->ambient_sound_level));
173                 if (i)
174                 {
175                         memcpy(out, leaf->ambient_sound_level, i);
176                         out += i;
177                         outsize -= i;
178                 }
179         }
180         if (outsize)
181                 memset(out, 0, outsize);
182 }
183
184 static int Mod_BSP_FindBoxClusters(model_t *model, const vec3_t mins, const vec3_t maxs, int maxclusters, int *clusterlist)
185 {
186         int numclusters = 0;
187         int nodestackindex = 0;
188         mnode_t *node, *nodestack[1024];
189         if (!model->brush.num_pvsclusters)
190                 return -1;
191         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
192         for (;;)
193         {
194 #if 1
195                 if (node->plane)
196                 {
197                         // node - recurse down the BSP tree
198                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
199                         if (sides < 3)
200                         {
201                                 if (sides == 0)
202                                         return -1; // ERROR: NAN bounding box!
203                                 // box is on one side of plane, take that path
204                                 node = node->children[sides-1];
205                         }
206                         else
207                         {
208                                 // box crosses plane, take one path and remember the other
209                                 if (nodestackindex < 1024)
210                                         nodestack[nodestackindex++] = node->children[0];
211                                 node = node->children[1];
212                         }
213                         continue;
214                 }
215                 else
216                 {
217                         // leaf - add clusterindex to list
218                         if (numclusters < maxclusters)
219                                 clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
220                         numclusters++;
221                 }
222 #else
223                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
224                 {
225                         if (node->plane)
226                         {
227                                 if (nodestackindex < 1024)
228                                         nodestack[nodestackindex++] = node->children[0];
229                                 node = node->children[1];
230                                 continue;
231                         }
232                         else
233                         {
234                                 // leaf - add clusterindex to list
235                                 if (numclusters < maxclusters)
236                                         clusterlist[numclusters] = ((mleaf_t *)node)->clusterindex;
237                                 numclusters++;
238                         }
239                 }
240 #endif
241                 // try another path we didn't take earlier
242                 if (nodestackindex == 0)
243                         break;
244                 node = nodestack[--nodestackindex];
245         }
246         // return number of clusters found (even if more than the maxclusters)
247         return numclusters;
248 }
249
250 static int Mod_BSP_BoxTouchingPVS(model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
251 {
252         int nodestackindex = 0;
253         mnode_t *node, *nodestack[1024];
254         if (!model->brush.num_pvsclusters)
255                 return true;
256         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
257         for (;;)
258         {
259 #if 1
260                 if (node->plane)
261                 {
262                         // node - recurse down the BSP tree
263                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
264                         if (sides < 3)
265                         {
266                                 if (sides == 0)
267                                         return -1; // ERROR: NAN bounding box!
268                                 // box is on one side of plane, take that path
269                                 node = node->children[sides-1];
270                         }
271                         else
272                         {
273                                 // box crosses plane, take one path and remember the other
274                                 if (nodestackindex < 1024)
275                                         nodestack[nodestackindex++] = node->children[0];
276                                 node = node->children[1];
277                         }
278                         continue;
279                 }
280                 else
281                 {
282                         // leaf - check cluster bit
283                         int clusterindex = ((mleaf_t *)node)->clusterindex;
284                         if (CHECKPVSBIT(pvs, clusterindex))
285                         {
286                                 // it is visible, return immediately with the news
287                                 return true;
288                         }
289                 }
290 #else
291                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
292                 {
293                         if (node->plane)
294                         {
295                                 if (nodestackindex < 1024)
296                                         nodestack[nodestackindex++] = node->children[0];
297                                 node = node->children[1];
298                                 continue;
299                         }
300                         else
301                         {
302                                 // leaf - check cluster bit
303                                 int clusterindex = ((mleaf_t *)node)->clusterindex;
304                                 if (CHECKPVSBIT(pvs, clusterindex))
305                                 {
306                                         // it is visible, return immediately with the news
307                                         return true;
308                                 }
309                         }
310                 }
311 #endif
312                 // nothing to see here, try another path we didn't take earlier
313                 if (nodestackindex == 0)
314                         break;
315                 node = nodestack[--nodestackindex];
316         }
317         // it is not visible
318         return false;
319 }
320
321 static int Mod_BSP_BoxTouchingLeafPVS(model_t *model, const unsigned char *pvs, const vec3_t mins, const vec3_t maxs)
322 {
323         int nodestackindex = 0;
324         mnode_t *node, *nodestack[1024];
325         if (!model->brush.num_leafs)
326                 return true;
327         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
328         for (;;)
329         {
330 #if 1
331                 if (node->plane)
332                 {
333                         // node - recurse down the BSP tree
334                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
335                         if (sides < 3)
336                         {
337                                 if (sides == 0)
338                                         return -1; // ERROR: NAN bounding box!
339                                 // box is on one side of plane, take that path
340                                 node = node->children[sides-1];
341                         }
342                         else
343                         {
344                                 // box crosses plane, take one path and remember the other
345                                 if (nodestackindex < 1024)
346                                         nodestack[nodestackindex++] = node->children[0];
347                                 node = node->children[1];
348                         }
349                         continue;
350                 }
351                 else
352                 {
353                         // leaf - check cluster bit
354                         int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
355                         if (CHECKPVSBIT(pvs, clusterindex))
356                         {
357                                 // it is visible, return immediately with the news
358                                 return true;
359                         }
360                 }
361 #else
362                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
363                 {
364                         if (node->plane)
365                         {
366                                 if (nodestackindex < 1024)
367                                         nodestack[nodestackindex++] = node->children[0];
368                                 node = node->children[1];
369                                 continue;
370                         }
371                         else
372                         {
373                                 // leaf - check cluster bit
374                                 int clusterindex = ((mleaf_t *)node) - model->brush.data_leafs;
375                                 if (CHECKPVSBIT(pvs, clusterindex))
376                                 {
377                                         // it is visible, return immediately with the news
378                                         return true;
379                                 }
380                         }
381                 }
382 #endif
383                 // nothing to see here, try another path we didn't take earlier
384                 if (nodestackindex == 0)
385                         break;
386                 node = nodestack[--nodestackindex];
387         }
388         // it is not visible
389         return false;
390 }
391
392 static int Mod_BSP_BoxTouchingVisibleLeafs(model_t *model, const unsigned char *visibleleafs, const vec3_t mins, const vec3_t maxs)
393 {
394         int nodestackindex = 0;
395         mnode_t *node, *nodestack[1024];
396         if (!model->brush.num_leafs)
397                 return true;
398         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
399         for (;;)
400         {
401 #if 1
402                 if (node->plane)
403                 {
404                         // node - recurse down the BSP tree
405                         int sides = BoxOnPlaneSide(mins, maxs, node->plane);
406                         if (sides < 3)
407                         {
408                                 if (sides == 0)
409                                         return -1; // ERROR: NAN bounding box!
410                                 // box is on one side of plane, take that path
411                                 node = node->children[sides-1];
412                         }
413                         else
414                         {
415                                 // box crosses plane, take one path and remember the other
416                                 if (nodestackindex < 1024)
417                                         nodestack[nodestackindex++] = node->children[0];
418                                 node = node->children[1];
419                         }
420                         continue;
421                 }
422                 else
423                 {
424                         // leaf - check if it is visible
425                         if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
426                         {
427                                 // it is visible, return immediately with the news
428                                 return true;
429                         }
430                 }
431 #else
432                 if (BoxesOverlap(mins, maxs, node->mins, node->maxs))
433                 {
434                         if (node->plane)
435                         {
436                                 if (nodestackindex < 1024)
437                                         nodestack[nodestackindex++] = node->children[0];
438                                 node = node->children[1];
439                                 continue;
440                         }
441                         else
442                         {
443                                 // leaf - check if it is visible
444                                 if (visibleleafs[(mleaf_t *)node - model->brush.data_leafs])
445                                 {
446                                         // it is visible, return immediately with the news
447                                         return true;
448                                 }
449                         }
450                 }
451 #endif
452                 // nothing to see here, try another path we didn't take earlier
453                 if (nodestackindex == 0)
454                         break;
455                 node = nodestack[--nodestackindex];
456         }
457         // it is not visible
458         return false;
459 }
460
461 typedef struct findnonsolidlocationinfo_s
462 {
463         vec3_t center;
464         vec3_t absmin, absmax;
465         vec_t radius;
466         vec3_t nudge;
467         vec_t bestdist;
468         model_t *model;
469 }
470 findnonsolidlocationinfo_t;
471
472 static void Mod_BSP_FindNonSolidLocation_r_Triangle(findnonsolidlocationinfo_t *info, msurface_t *surface, int k)
473 {
474         int i, *tri;
475         float dist, f, vert[3][3], edge[3][3], facenormal[3], edgenormal[3][3], point[3];
476
477         tri = (info->model->surfmesh.data_element3i + 3 * surface->num_firsttriangle) + k * 3;
478         VectorCopy((info->model->surfmesh.data_vertex3f + tri[0] * 3), vert[0]);
479         VectorCopy((info->model->surfmesh.data_vertex3f + tri[1] * 3), vert[1]);
480         VectorCopy((info->model->surfmesh.data_vertex3f + tri[2] * 3), vert[2]);
481         VectorSubtract(vert[1], vert[0], edge[0]);
482         VectorSubtract(vert[2], vert[1], edge[1]);
483         CrossProduct(edge[1], edge[0], facenormal);
484         if (facenormal[0] || facenormal[1] || facenormal[2])
485         {
486                 VectorNormalize(facenormal);
487                 f = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
488                 if (f <= info->bestdist && f >= -info->bestdist)
489                 {
490                         VectorSubtract(vert[0], vert[2], edge[2]);
491                         VectorNormalize(edge[0]);
492                         VectorNormalize(edge[1]);
493                         VectorNormalize(edge[2]);
494                         CrossProduct(facenormal, edge[0], edgenormal[0]);
495                         CrossProduct(facenormal, edge[1], edgenormal[1]);
496                         CrossProduct(facenormal, edge[2], edgenormal[2]);
497                         // face distance
498                         if (DotProduct(info->center, edgenormal[0]) < DotProduct(vert[0], edgenormal[0])
499                                         && DotProduct(info->center, edgenormal[1]) < DotProduct(vert[1], edgenormal[1])
500                                         && DotProduct(info->center, edgenormal[2]) < DotProduct(vert[2], edgenormal[2]))
501                         {
502                                 // we got lucky, the center is within the face
503                                 dist = DotProduct(info->center, facenormal) - DotProduct(vert[0], facenormal);
504                                 if (dist < 0)
505                                 {
506                                         dist = -dist;
507                                         if (info->bestdist > dist)
508                                         {
509                                                 info->bestdist = dist;
510                                                 VectorScale(facenormal, (info->radius - -dist), info->nudge);
511                                         }
512                                 }
513                                 else
514                                 {
515                                         if (info->bestdist > dist)
516                                         {
517                                                 info->bestdist = dist;
518                                                 VectorScale(facenormal, (info->radius - dist), info->nudge);
519                                         }
520                                 }
521                         }
522                         else
523                         {
524                                 // check which edge or vertex the center is nearest
525                                 for (i = 0;i < 3;i++)
526                                 {
527                                         f = DotProduct(info->center, edge[i]);
528                                         if (f >= DotProduct(vert[0], edge[i])
529                                                         && f <= DotProduct(vert[1], edge[i]))
530                                         {
531                                                 // on edge
532                                                 VectorMA(info->center, -f, edge[i], point);
533                                                 dist = sqrt(DotProduct(point, point));
534                                                 if (info->bestdist > dist)
535                                                 {
536                                                         info->bestdist = dist;
537                                                         VectorScale(point, (info->radius / dist), info->nudge);
538                                                 }
539                                                 // skip both vertex checks
540                                                 // (both are further away than this edge)
541                                                 i++;
542                                         }
543                                         else
544                                         {
545                                                 // not on edge, check first vertex of edge
546                                                 VectorSubtract(info->center, vert[i], point);
547                                                 dist = sqrt(DotProduct(point, point));
548                                                 if (info->bestdist > dist)
549                                                 {
550                                                         info->bestdist = dist;
551                                                         VectorScale(point, (info->radius / dist), info->nudge);
552                                                 }
553                                         }
554                                 }
555                         }
556                 }
557         }
558 }
559
560 static void Mod_BSP_FindNonSolidLocation_r_Leaf(findnonsolidlocationinfo_t *info, mleaf_t *leaf)
561 {
562         int surfacenum, k, *mark;
563         msurface_t *surface;
564         for (surfacenum = 0, mark = leaf->firstleafsurface;surfacenum < leaf->numleafsurfaces;surfacenum++, mark++)
565         {
566                 surface = info->model->data_surfaces + *mark;
567                 if(!surface->texture)
568                         continue;
569                 if (surface->texture->supercontents & SUPERCONTENTS_SOLID)
570                 {
571                         for (k = 0;k < surface->num_triangles;k++)
572                         {
573                                 Mod_BSP_FindNonSolidLocation_r_Triangle(info, surface, k);
574                         }
575                 }
576         }
577 }
578
579 static void Mod_BSP_FindNonSolidLocation_r(findnonsolidlocationinfo_t *info, mnode_t *node)
580 {
581         if (node->plane)
582         {
583                 float f = PlaneDiff(info->center, node->plane);
584                 if (f >= -info->bestdist)
585                         Mod_BSP_FindNonSolidLocation_r(info, node->children[0]);
586                 if (f <= info->bestdist)
587                         Mod_BSP_FindNonSolidLocation_r(info, node->children[1]);
588         }
589         else
590         {
591                 if (((mleaf_t *)node)->numleafsurfaces)
592                         Mod_BSP_FindNonSolidLocation_r_Leaf(info, (mleaf_t *)node);
593         }
594 }
595
596 static void Mod_BSP_FindNonSolidLocation(model_t *model, const vec3_t in, vec3_t out, float radius)
597 {
598         int i;
599         findnonsolidlocationinfo_t info;
600         if (model == NULL)
601         {
602                 VectorCopy(in, out);
603                 return;
604         }
605         VectorCopy(in, info.center);
606         info.radius = radius;
607         info.model = model;
608         i = 0;
609         do
610         {
611                 VectorClear(info.nudge);
612                 info.bestdist = radius;
613                 VectorCopy(info.center, info.absmin);
614                 VectorCopy(info.center, info.absmax);
615                 info.absmin[0] -= info.radius + 1;
616                 info.absmin[1] -= info.radius + 1;
617                 info.absmin[2] -= info.radius + 1;
618                 info.absmax[0] += info.radius + 1;
619                 info.absmax[1] += info.radius + 1;
620                 info.absmax[2] += info.radius + 1;
621                 Mod_BSP_FindNonSolidLocation_r(&info, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
622                 VectorAdd(info.center, info.nudge, info.center);
623         }
624         while (info.bestdist < radius && ++i < 10);
625         VectorCopy(info.center, out);
626 }
627
628 int Mod_Q1BSP_SuperContentsFromNativeContents(int nativecontents)
629 {
630         switch(nativecontents)
631         {
632                 case CONTENTS_EMPTY:
633                         return 0;
634                 case CONTENTS_SOLID:
635                         return SUPERCONTENTS_SOLID | SUPERCONTENTS_OPAQUE;
636                 case CONTENTS_WATER:
637                         return SUPERCONTENTS_WATER;
638                 case CONTENTS_SLIME:
639                         return SUPERCONTENTS_SLIME;
640                 case CONTENTS_LAVA:
641                         return SUPERCONTENTS_LAVA | SUPERCONTENTS_NODROP;
642                 case CONTENTS_SKY:
643                         return SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
644         }
645         return 0;
646 }
647
648 int Mod_Q1BSP_NativeContentsFromSuperContents(int supercontents)
649 {
650         if (supercontents & (SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY))
651                 return CONTENTS_SOLID;
652         if (supercontents & SUPERCONTENTS_SKY)
653                 return CONTENTS_SKY;
654         if (supercontents & SUPERCONTENTS_LAVA)
655                 return CONTENTS_LAVA;
656         if (supercontents & SUPERCONTENTS_SLIME)
657                 return CONTENTS_SLIME;
658         if (supercontents & SUPERCONTENTS_WATER)
659                 return CONTENTS_WATER;
660         return CONTENTS_EMPTY;
661 }
662
663 typedef struct RecursiveHullCheckTraceInfo_s
664 {
665         // the hull we're tracing through
666         const hull_t *hull;
667
668         // the trace structure to fill in
669         trace_t *trace;
670
671         // start, end, and end - start (in model space)
672         double start[3];
673         double end[3];
674         double dist[3];
675 }
676 RecursiveHullCheckTraceInfo_t;
677
678 // 1/32 epsilon to keep floating point happy
679 #define DIST_EPSILON (0.03125)
680
681 #define HULLCHECKSTATE_EMPTY 0
682 #define HULLCHECKSTATE_SOLID 1
683 #define HULLCHECKSTATE_DONE 2
684
685 static int Mod_Q1BSP_RecursiveHullCheck(RecursiveHullCheckTraceInfo_t *t, int num, double p1f, double p2f, double p1[3], double p2[3])
686 {
687         // status variables, these don't need to be saved on the stack when
688         // recursing...  but are because this should be thread-safe
689         // (note: tracing against a bbox is not thread-safe, yet)
690         int ret;
691         mplane_t *plane;
692         double t1, t2;
693
694         // variables that need to be stored on the stack when recursing
695         mclipnode_t *node;
696         int p1side, p2side;
697         double midf, mid[3];
698
699         // keep looping until we hit a leaf
700         while (num >= 0)
701         {
702                 // find the point distances
703                 node = t->hull->clipnodes + num;
704                 plane = t->hull->planes + node->planenum;
705
706                 // axial planes can be calculated more quickly without the DotProduct
707                 if (plane->type < 3)
708                 {
709                         t1 = p1[plane->type] - plane->dist;
710                         t2 = p2[plane->type] - plane->dist;
711                 }
712                 else
713                 {
714                         t1 = DotProduct (plane->normal, p1) - plane->dist;
715                         t2 = DotProduct (plane->normal, p2) - plane->dist;
716                 }
717
718                 // negative plane distances indicate children[1] (behind plane)
719                 p1side = t1 < 0;
720                 p2side = t2 < 0;
721
722                 // if the line starts and ends on the same side of the plane, recurse
723                 // into that child instantly
724                 if (p1side == p2side)
725                 {
726 #if COLLISIONPARANOID >= 3
727                         if (p1side)
728                                 Con_Print("<");
729                         else
730                                 Con_Print(">");
731 #endif
732                         // loop back and process the start child
733                         num = node->children[p1side];
734                 }
735                 else
736                 {
737                         // find the midpoint where the line crosses the plane, use the
738                         // original line for best accuracy
739 #if COLLISIONPARANOID >= 3
740                         Con_Print("M");
741 #endif
742                         if (plane->type < 3)
743                         {
744                                 t1 = t->start[plane->type] - plane->dist;
745                                 t2 = t->end[plane->type] - plane->dist;
746                         }
747                         else
748                         {
749                                 t1 = DotProduct (plane->normal, t->start) - plane->dist;
750                                 t2 = DotProduct (plane->normal, t->end) - plane->dist;
751                         }
752                         midf = t1 / (t1 - t2);
753                         midf = bound(p1f, midf, p2f);
754                         VectorMA(t->start, midf, t->dist, mid);
755
756                         // we now have a mid point, essentially splitting the line into
757                         // the segments in the near child and the far child, we can now
758                         // recurse those in order and get their results
759
760                         // recurse both sides, front side first
761                         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p1side], p1f, midf, p1, mid);
762                         // if this side is not empty, return what it is (solid or done)
763                         if (ret != HULLCHECKSTATE_EMPTY && !t->trace->allsolid)
764                                 return ret;
765
766                         ret = Mod_Q1BSP_RecursiveHullCheck(t, node->children[p2side], midf, p2f, mid, p2);
767                         // if other side is not solid, return what it is (empty or done)
768                         if (ret != HULLCHECKSTATE_SOLID)
769                                 return ret;
770
771                         // front is air and back is solid, this is the impact point...
772
773                         // copy the plane information, flipping it if needed
774                         if (p1side)
775                         {
776                                 t->trace->plane.dist = -plane->dist;
777                                 VectorNegate (plane->normal, t->trace->plane.normal);
778                         }
779                         else
780                         {
781                                 t->trace->plane.dist = plane->dist;
782                                 VectorCopy (plane->normal, t->trace->plane.normal);
783                         }
784
785                         // calculate the return fraction which is nudged off the surface a bit
786                         t1 = DotProduct(t->trace->plane.normal, t->start) - t->trace->plane.dist;
787                         t2 = DotProduct(t->trace->plane.normal, t->end) - t->trace->plane.dist;
788                         midf = (t1 - collision_impactnudge.value) / (t1 - t2);
789                         t->trace->fraction = bound(0, midf, 1);
790
791 #if COLLISIONPARANOID >= 3
792                         Con_Print("D");
793 #endif
794                         return HULLCHECKSTATE_DONE;
795                 }
796         }
797
798         // we reached a leaf contents
799
800         // check for empty
801         num = Mod_Q1BSP_SuperContentsFromNativeContents(num);
802         if (!t->trace->startfound)
803         {
804                 t->trace->startfound = true;
805                 t->trace->startsupercontents |= num;
806         }
807         if (num & SUPERCONTENTS_LIQUIDSMASK)
808                 t->trace->inwater = true;
809         if (num == 0)
810                 t->trace->inopen = true;
811         if (num & SUPERCONTENTS_SOLID)
812                 t->trace->hittexture = &mod_q1bsp_texture_solid;
813         else if (num & SUPERCONTENTS_SKY)
814                 t->trace->hittexture = &mod_q1bsp_texture_sky;
815         else if (num & SUPERCONTENTS_LAVA)
816                 t->trace->hittexture = &mod_q1bsp_texture_lava;
817         else if (num & SUPERCONTENTS_SLIME)
818                 t->trace->hittexture = &mod_q1bsp_texture_slime;
819         else
820                 t->trace->hittexture = &mod_q1bsp_texture_water;
821         t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
822         t->trace->hitsupercontents = num;
823         if (num & t->trace->hitsupercontentsmask)
824         {
825                 // if the first leaf is solid, set startsolid
826                 if (t->trace->allsolid)
827                         t->trace->startsolid = true;
828 #if COLLISIONPARANOID >= 3
829                 Con_Print("S");
830 #endif
831                 return HULLCHECKSTATE_SOLID;
832         }
833         else
834         {
835                 t->trace->allsolid = false;
836 #if COLLISIONPARANOID >= 3
837                 Con_Print("E");
838 #endif
839                 return HULLCHECKSTATE_EMPTY;
840         }
841 }
842
843 //#if COLLISIONPARANOID < 2
844 static int Mod_Q1BSP_RecursiveHullCheckPoint(RecursiveHullCheckTraceInfo_t *t, int num)
845 {
846         mplane_t *plane;
847         mclipnode_t *nodes = t->hull->clipnodes;
848         mplane_t *planes = t->hull->planes;
849         vec3_t point;
850         VectorCopy(t->start, point);
851         while (num >= 0)
852         {
853                 plane = planes + nodes[num].planenum;
854                 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
855         }
856         num = Mod_Q1BSP_SuperContentsFromNativeContents(num);
857         t->trace->startsupercontents |= num;
858         if (num & SUPERCONTENTS_LIQUIDSMASK)
859                 t->trace->inwater = true;
860         if (num == 0)
861                 t->trace->inopen = true;
862         if (num & t->trace->hitsupercontentsmask)
863         {
864                 t->trace->allsolid = t->trace->startsolid = true;
865                 return HULLCHECKSTATE_SOLID;
866         }
867         else
868         {
869                 t->trace->allsolid = t->trace->startsolid = false;
870                 return HULLCHECKSTATE_EMPTY;
871         }
872 }
873 //#endif
874
875 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, int skipsupercontentsmask, int skipmaterialflagsmask)
876 {
877         RecursiveHullCheckTraceInfo_t rhc;
878
879         memset(&rhc, 0, sizeof(rhc));
880         memset(trace, 0, sizeof(trace_t));
881         rhc.trace = trace;
882         rhc.trace->fraction = 1;
883         rhc.trace->allsolid = true;
884         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
885         VectorCopy(start, rhc.start);
886         VectorCopy(start, rhc.end);
887         Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
888 }
889
890 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, int skipsupercontentsmask, int skipmaterialflagsmask);
891
892 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, int skipsupercontentsmask, int skipmaterialflagsmask)
893 {
894         RecursiveHullCheckTraceInfo_t rhc;
895
896         if (VectorCompare(start, end))
897         {
898                 Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
899                 return;
900         }
901
902         // 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...
903         if (sv_gameplayfix_q1bsptracelinereportstexture.integer)
904         {
905                 Mod_Q1BSP_TraceLineAgainstSurfaces(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
906                 return;
907         }
908
909         memset(&rhc, 0, sizeof(rhc));
910         memset(trace, 0, sizeof(trace_t));
911         rhc.trace = trace;
912         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
913         rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
914         rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
915         rhc.trace->fraction = 1;
916         rhc.trace->allsolid = true;
917         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
918         VectorCopy(start, rhc.start);
919         VectorCopy(end, rhc.end);
920         VectorSubtract(rhc.end, rhc.start, rhc.dist);
921 #if COLLISIONPARANOID >= 2
922         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]);
923         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
924         {
925
926                 double test[3];
927                 trace_t testtrace;
928                 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
929                 memset(&testtrace, 0, sizeof(trace_t));
930                 rhc.trace = &testtrace;
931                 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
932                 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
933                 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
934                 rhc.trace->fraction = 1;
935                 rhc.trace->allsolid = true;
936                 VectorCopy(test, rhc.start);
937                 VectorCopy(test, rhc.end);
938                 VectorClear(rhc.dist);
939                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
940                 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
941                 if (!trace->startsolid && testtrace.startsolid)
942                         Con_Printf(" - ended in solid!\n");
943         }
944         Con_Print("\n");
945 #else
946         if (VectorLength2(rhc.dist))
947                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
948         else
949                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
950 #endif
951 }
952
953 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, int skipsupercontentsmask, int skipmaterialflagsmask)
954 {
955         // this function currently only supports same size start and end
956         double boxsize[3];
957         RecursiveHullCheckTraceInfo_t rhc;
958
959         if (VectorCompare(boxmins, boxmaxs))
960         {
961                 if (VectorCompare(start, end))
962                         Mod_Q1BSP_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
963                 else
964                         Mod_Q1BSP_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
965                 return;
966         }
967
968         memset(&rhc, 0, sizeof(rhc));
969         memset(trace, 0, sizeof(trace_t));
970         rhc.trace = trace;
971         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
972         rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
973         rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
974         rhc.trace->fraction = 1;
975         rhc.trace->allsolid = true;
976         VectorSubtract(boxmaxs, boxmins, boxsize);
977         if (boxsize[0] < mod_q1bsp_zero_hullsize_cutoff.value)
978                 rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
979         else if (model->brush.ishlbsp)
980         {
981                 // LadyHavoc: this has to have a minor tolerance (the .1) because of
982                 // minor float precision errors from the box being transformed around
983                 if (boxsize[0] < 32.1)
984                 {
985                         if (boxsize[2] < 54) // pick the nearest of 36 or 72
986                                 rhc.hull = &model->brushq1.hulls[3]; // 32x32x36
987                         else
988                                 rhc.hull = &model->brushq1.hulls[1]; // 32x32x72
989                 }
990                 else
991                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x64
992         }
993         else
994         {
995                 // LadyHavoc: this has to have a minor tolerance (the .1) because of
996                 // minor float precision errors from the box being transformed around
997                 if (boxsize[0] < 32.1)
998                         rhc.hull = &model->brushq1.hulls[1]; // 32x32x56
999                 else
1000                         rhc.hull = &model->brushq1.hulls[2]; // 64x64x88
1001         }
1002         VectorMAMAM(1, start, 1, boxmins, -1, rhc.hull->clip_mins, rhc.start);
1003         VectorMAMAM(1, end, 1, boxmins, -1, rhc.hull->clip_mins, rhc.end);
1004         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1005 #if COLLISIONPARANOID >= 2
1006         Con_Printf("t(%f %f %f,%f %f %f,%li %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]);
1007         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1008         {
1009
1010                 double test[3];
1011                 trace_t testtrace;
1012                 VectorLerp(rhc.start, rhc.trace->fraction, rhc.end, test);
1013                 memset(&testtrace, 0, sizeof(trace_t));
1014                 rhc.trace = &testtrace;
1015                 rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1016                 rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1017                 rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1018                 rhc.trace->fraction = 1;
1019                 rhc.trace->allsolid = true;
1020                 VectorCopy(test, rhc.start);
1021                 VectorCopy(test, rhc.end);
1022                 VectorClear(rhc.dist);
1023                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1024                 //Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, test, test);
1025                 if (!trace->startsolid && testtrace.startsolid)
1026                         Con_Printf(" - ended in solid!\n");
1027         }
1028         Con_Print("\n");
1029 #else
1030         if (VectorLength2(rhc.dist))
1031                 Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1032         else
1033                 Mod_Q1BSP_RecursiveHullCheckPoint(&rhc, rhc.hull->firstclipnode);
1034 #endif
1035 }
1036
1037 static int Mod_Q1BSP_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
1038 {
1039         int num = model->brushq1.hulls[0].firstclipnode;
1040         mplane_t *plane;
1041         mclipnode_t *nodes = model->brushq1.hulls[0].clipnodes;
1042         mplane_t *planes = model->brushq1.hulls[0].planes;
1043         while (num >= 0)
1044         {
1045                 plane = planes + nodes[num].planenum;
1046                 num = nodes[num].children[(plane->type < 3 ? point[plane->type] : DotProduct(plane->normal, point)) < plane->dist];
1047         }
1048         return Mod_Q1BSP_SuperContentsFromNativeContents(num);
1049 }
1050
1051 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 skipsupercontentsmask, int skipmaterialflagsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1052 {
1053 #if 1
1054         colbrushf_t cbox;
1055         colplanef_t cbox_planes[6];
1056         cbox.isaabb = true;
1057         cbox.hasaabbplanes = true;
1058         cbox.supercontents = boxsupercontents;
1059         cbox.numplanes = 6;
1060         cbox.numpoints = 0;
1061         cbox.numtriangles = 0;
1062         cbox.planes = cbox_planes;
1063         cbox.points = NULL;
1064         cbox.elements = NULL;
1065         cbox.markframe = 0;
1066         cbox.mins[0] = 0;
1067         cbox.mins[1] = 0;
1068         cbox.mins[2] = 0;
1069         cbox.maxs[0] = 0;
1070         cbox.maxs[1] = 0;
1071         cbox.maxs[2] = 0;
1072         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];
1073         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];
1074         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];
1075         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];
1076         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];
1077         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];
1078         cbox_planes[0].q3surfaceflags = boxq3surfaceflags;cbox_planes[0].texture = boxtexture;
1079         cbox_planes[1].q3surfaceflags = boxq3surfaceflags;cbox_planes[1].texture = boxtexture;
1080         cbox_planes[2].q3surfaceflags = boxq3surfaceflags;cbox_planes[2].texture = boxtexture;
1081         cbox_planes[3].q3surfaceflags = boxq3surfaceflags;cbox_planes[3].texture = boxtexture;
1082         cbox_planes[4].q3surfaceflags = boxq3surfaceflags;cbox_planes[4].texture = boxtexture;
1083         cbox_planes[5].q3surfaceflags = boxq3surfaceflags;cbox_planes[5].texture = boxtexture;
1084         memset(trace, 0, sizeof(trace_t));
1085         trace->hitsupercontentsmask = hitsupercontentsmask;
1086         trace->skipsupercontentsmask = skipsupercontentsmask;
1087         trace->skipmaterialflagsmask = skipmaterialflagsmask;
1088         trace->fraction = 1;
1089         Collision_TraceLineBrushFloat(trace, start, end, &cbox, &cbox);
1090 #else
1091         RecursiveHullCheckTraceInfo_t rhc;
1092         static hull_t box_hull;
1093         static mclipnode_t box_clipnodes[6];
1094         static mplane_t box_planes[6];
1095         // fill in a default trace
1096         memset(&rhc, 0, sizeof(rhc));
1097         memset(trace, 0, sizeof(trace_t));
1098         //To keep everything totally uniform, bounding boxes are turned into small
1099         //BSP trees instead of being compared directly.
1100         // create a temp hull from bounding box sizes
1101         box_planes[0].dist = cmaxs[0] - mins[0];
1102         box_planes[1].dist = cmins[0] - maxs[0];
1103         box_planes[2].dist = cmaxs[1] - mins[1];
1104         box_planes[3].dist = cmins[1] - maxs[1];
1105         box_planes[4].dist = cmaxs[2] - mins[2];
1106         box_planes[5].dist = cmins[2] - maxs[2];
1107 #if COLLISIONPARANOID >= 3
1108         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]);
1109 #endif
1110
1111         if (box_hull.clipnodes == NULL)
1112         {
1113                 int i, side;
1114
1115                 //Set up the planes and clipnodes so that the six floats of a bounding box
1116                 //can just be stored out and get a proper hull_t structure.
1117
1118                 box_hull.clipnodes = box_clipnodes;
1119                 box_hull.planes = box_planes;
1120                 box_hull.firstclipnode = 0;
1121                 box_hull.lastclipnode = 5;
1122
1123                 for (i = 0;i < 6;i++)
1124                 {
1125                         box_clipnodes[i].planenum = i;
1126
1127                         side = i&1;
1128
1129                         box_clipnodes[i].children[side] = CONTENTS_EMPTY;
1130                         if (i != 5)
1131                                 box_clipnodes[i].children[side^1] = i + 1;
1132                         else
1133                                 box_clipnodes[i].children[side^1] = CONTENTS_SOLID;
1134
1135                         box_planes[i].type = i>>1;
1136                         box_planes[i].normal[i>>1] = 1;
1137                 }
1138         }
1139
1140         // trace a line through the generated clipping hull
1141         //rhc.boxsupercontents = boxsupercontents;
1142         rhc.hull = &box_hull;
1143         rhc.trace = trace;
1144         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1145         rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1146         rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1147         rhc.trace->fraction = 1;
1148         rhc.trace->allsolid = true;
1149         VectorCopy(start, rhc.start);
1150         VectorCopy(end, rhc.end);
1151         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1152         Mod_Q1BSP_RecursiveHullCheck(&rhc, rhc.hull->firstclipnode, 0, 1, rhc.start, rhc.end);
1153         //VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1154         if (rhc.trace->startsupercontents)
1155                 rhc.trace->startsupercontents = boxsupercontents;
1156 #endif
1157 }
1158
1159 void Collision_ClipTrace_Point(trace_t *trace, const vec3_t cmins, const vec3_t cmaxs, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask, int boxsupercontents, int boxq3surfaceflags, const texture_t *boxtexture)
1160 {
1161         memset(trace, 0, sizeof(trace_t));
1162         trace->fraction = 1;
1163         trace->hitsupercontentsmask = hitsupercontentsmask;
1164         trace->skipsupercontentsmask = skipsupercontentsmask;
1165         trace->skipmaterialflagsmask = skipmaterialflagsmask;
1166         if (BoxesOverlap(start, start, cmins, cmaxs))
1167         {
1168                 trace->startsupercontents |= boxsupercontents;
1169                 if ((hitsupercontentsmask & boxsupercontents) && !(skipsupercontentsmask & boxsupercontents))
1170                 {
1171                         trace->startsolid = true;
1172                         trace->allsolid = true;
1173                 }
1174         }
1175 }
1176
1177 static qbool Mod_Q1BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
1178 {
1179         trace_t trace;
1180         Mod_Q1BSP_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
1181         return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
1182 }
1183
1184 static int Mod_BSP_LightPoint_RecursiveBSPNode(model_t *model, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal, const mnode_t *node, float x, float y, float startz, float endz)
1185 {
1186         int side;
1187         float front, back;
1188         float mid, distz = endz - startz;
1189
1190         while (node->plane)
1191         {
1192                 switch (node->plane->type)
1193                 {
1194                 case PLANE_X:
1195                         node = node->children[x < node->plane->dist];
1196                         continue; // loop back and process the new node
1197                 case PLANE_Y:
1198                         node = node->children[y < node->plane->dist];
1199                         continue; // loop back and process the new node
1200                 case PLANE_Z:
1201                         side = startz < node->plane->dist;
1202                         if ((endz < node->plane->dist) == side)
1203                         {
1204                                 node = node->children[side];
1205                                 continue; // loop back and process the new node
1206                         }
1207                         // found an intersection
1208                         mid = node->plane->dist;
1209                         break;
1210                 default:
1211                         back = front = x * node->plane->normal[0] + y * node->plane->normal[1];
1212                         front += startz * node->plane->normal[2];
1213                         back += endz * node->plane->normal[2];
1214                         side = front < node->plane->dist;
1215                         if ((back < node->plane->dist) == side)
1216                         {
1217                                 node = node->children[side];
1218                                 continue; // loop back and process the new node
1219                         }
1220                         // found an intersection
1221                         mid = startz + distz * (front - node->plane->dist) / (front - back);
1222                         break;
1223                 }
1224
1225                 // go down front side
1226                 if (node->children[side]->plane && Mod_BSP_LightPoint_RecursiveBSPNode(model, ambientcolor, diffusecolor, diffusenormal, node->children[side], x, y, startz, mid))
1227                         return true;    // hit something
1228
1229                 // check for impact on this node
1230                 if (node->numsurfaces)
1231                 {
1232                         unsigned int i;
1233                         int dsi, dti, lmwidth, lmheight;
1234                         float ds, dt;
1235                         msurface_t *surface;
1236                         unsigned char *lightmap;
1237                         int maps, line3, size3;
1238                         float dsfrac;
1239                         float dtfrac;
1240                         float scale, w, w00, w01, w10, w11;
1241
1242                         surface = model->data_surfaces + node->firstsurface;
1243                         for (i = 0;i < node->numsurfaces;i++, surface++)
1244                         {
1245                                 if(!surface->texture)
1246                                         continue;
1247                                 if (!(surface->texture->basematerialflags & MATERIALFLAG_WALL) || !surface->lightmapinfo || !surface->lightmapinfo->samples)
1248                                         continue;       // no lightmaps
1249
1250                                 // location we want to sample in the lightmap
1251                                 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;
1252                                 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;
1253
1254                                 // check the bounds
1255                                 // thanks to jitspoe for pointing out that this int cast was
1256                                 // rounding toward zero, so we floor it
1257                                 dsi = (int)floor(ds);
1258                                 dti = (int)floor(dt);
1259                                 lmwidth = ((surface->lightmapinfo->extents[0]>>4)+1);
1260                                 lmheight = ((surface->lightmapinfo->extents[1]>>4)+1);
1261
1262                                 // is it in bounds?
1263                                 // we have to tolerate a position of lmwidth-1 for some rare
1264                                 // cases - in which case the sampling position still gets
1265                                 // clamped but the color gets interpolated to that edge.
1266                                 if (dsi >= 0 && dsi < lmwidth && dti >= 0 && dti < lmheight)
1267                                 {
1268                                         // in the rare cases where we're sampling slightly off
1269                                         // the polygon, clamp the sampling position (we can still
1270                                         // interpolate outside it, where it becomes extrapolation)
1271                                         if (dsi < 0)
1272                                                 dsi = 0;
1273                                         if (dti < 0)
1274                                                 dti = 0;
1275                                         if (dsi > lmwidth-2)
1276                                                 dsi = lmwidth-2;
1277                                         if (dti > lmheight-2)
1278                                                 dti = lmheight-2;
1279                                         
1280                                         // calculate bilinear interpolation factors
1281                                         // and also multiply by fixedpoint conversion factors to
1282                                         // compensate for lightmaps being 0-255 (as 0-2), we use
1283                                         // r_refdef.scene.rtlightstylevalue here which is already
1284                                         // 0.000-2.148 range
1285                                         // (if we used r_refdef.scene.lightstylevalue this
1286                                         //  divisor would be 32768 rather than 128)
1287                                         dsfrac = ds - dsi;
1288                                         dtfrac = dt - dti;
1289                                         w00 = (1 - dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1290                                         w01 = (    dsfrac) * (1 - dtfrac) * (1.0f / 128.0f);
1291                                         w10 = (1 - dsfrac) * (    dtfrac) * (1.0f / 128.0f);
1292                                         w11 = (    dsfrac) * (    dtfrac) * (1.0f / 128.0f);
1293
1294                                         // values for pointer math
1295                                         line3 = lmwidth * 3; // LadyHavoc: *3 for colored lighting
1296                                         size3 = lmwidth * lmheight * 3; // LadyHavoc: *3 for colored lighting
1297
1298                                         // look up the pixel
1299                                         lightmap = surface->lightmapinfo->samples + dti * line3 + dsi*3; // LadyHavoc: *3 for colored lighting
1300
1301                                         // bilinear filter each lightmap style, and sum them
1302                                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++)
1303                                         {
1304                                                 scale = r_refdef.scene.rtlightstylevalue[surface->lightmapinfo->styles[maps]];
1305                                                 w = w00 * scale;VectorMA(ambientcolor, w, lightmap            , ambientcolor);
1306                                                 w = w01 * scale;VectorMA(ambientcolor, w, lightmap + 3        , ambientcolor);
1307                                                 w = w10 * scale;VectorMA(ambientcolor, w, lightmap + line3    , ambientcolor);
1308                                                 w = w11 * scale;VectorMA(ambientcolor, w, lightmap + line3 + 3, ambientcolor);
1309                                                 lightmap += size3;
1310                                         }
1311
1312                                         return true; // success
1313                                 }
1314                         }
1315                 }
1316
1317                 // go down back side
1318                 node = node->children[side ^ 1];
1319                 startz = mid;
1320                 distz = endz - startz;
1321                 // loop back and process the new node
1322         }
1323
1324         // did not hit anything
1325         return false;
1326 }
1327
1328 static void Mod_BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
1329 {
1330         // pretend lighting is coming down from above (due to lack of a lightgrid to know primary lighting direction)
1331         VectorSet(diffusenormal, 0, 0, 1);
1332
1333         if (!model->brushq1.lightdata)
1334         {
1335                 VectorSet(ambientcolor, 1, 1, 1);
1336                 VectorSet(diffusecolor, 0, 0, 0);
1337                 return;
1338         }
1339
1340         Mod_BSP_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);
1341 }
1342
1343 static const texture_t *Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(RecursiveHullCheckTraceInfo_t *t, const model_t *model, const mnode_t *node, double mid[3])
1344 {
1345         unsigned int i;
1346         int j;
1347         int k;
1348         const msurface_t *surface;
1349         float normal[3];
1350         float v0[3];
1351         float v1[3];
1352         float edgedir[3];
1353         float edgenormal[3];
1354         float p[4];
1355         float midf;
1356         float t1;
1357         float t2;
1358         VectorCopy(mid, p);
1359         p[3] = 1;
1360         surface = model->data_surfaces + node->firstsurface;
1361         for (i = 0;i < node->numsurfaces;i++, surface++)
1362         {
1363                 if(!surface->texture)
1364                         continue;
1365                 // skip surfaces whose bounding box does not include the point
1366 //              if (!BoxesOverlap(mid, mid, surface->mins, surface->maxs))
1367 //                      continue;
1368                 // skip faces with contents we don't care about
1369                 if (!(t->trace->hitsupercontentsmask & surface->texture->supercontents))
1370                         continue;
1371                 // ignore surfaces matching the skipsupercontentsmask (this is rare)
1372                 if (t->trace->skipsupercontentsmask & surface->texture->supercontents)
1373                         continue;
1374                 // skip surfaces matching the skipmaterialflagsmask (e.g. MATERIALFLAG_NOSHADOW)
1375                 if (t->trace->skipmaterialflagsmask & surface->texture->currentmaterialflags)
1376                         continue;
1377                 // get the surface normal - since it is flat we know any vertex normal will suffice
1378                 VectorCopy(model->surfmesh.data_normal3f + 3 * surface->num_firstvertex, normal);
1379                 // skip backfaces
1380                 if (DotProduct(t->dist, normal) > 0)
1381                         continue;
1382                 // iterate edges and see if the point is outside one of them
1383                 for (j = 0, k = surface->num_vertices - 1;j < surface->num_vertices;k = j, j++)
1384                 {
1385                         VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + k), v0);
1386                         VectorCopy(model->surfmesh.data_vertex3f + 3 * (surface->num_firstvertex + j), v1);
1387                         VectorSubtract(v0, v1, edgedir);
1388                         CrossProduct(edgedir, normal, edgenormal);
1389                         if (DotProduct(edgenormal, p) > DotProduct(edgenormal, v0))
1390                                 break;
1391                 }
1392                 // if the point is outside one of the edges, it is not within the surface
1393                 if (j < surface->num_vertices)
1394                         continue;
1395
1396                 // we hit a surface, this is the impact point...
1397                 VectorCopy(normal, t->trace->plane.normal);
1398                 t->trace->plane.dist = DotProduct(normal, p);
1399
1400                 // calculate the return fraction which is nudged off the surface a bit
1401                 t1 = DotProduct(t->start, t->trace->plane.normal) - t->trace->plane.dist;
1402                 t2 = DotProduct(t->end, t->trace->plane.normal) - t->trace->plane.dist;
1403                 midf = (t1 - collision_impactnudge.value) / (t1 - t2);
1404                 t->trace->fraction = bound(0, midf, 1);
1405
1406                 t->trace->hittexture = surface->texture->currentframe;
1407                 t->trace->hitq3surfaceflags = t->trace->hittexture->surfaceflags;
1408                 t->trace->hitsupercontents = t->trace->hittexture->supercontents;
1409                 return surface->texture->currentframe;
1410         }
1411         return NULL;
1412 }
1413
1414 static int Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(RecursiveHullCheckTraceInfo_t *t, const model_t *model, const mnode_t *node, const double p1[3], const double p2[3])
1415 {
1416         const mplane_t *plane;
1417         double t1, t2;
1418         int side;
1419         double midf, mid[3];
1420         const mleaf_t *leaf;
1421
1422         while (node->plane)
1423         {
1424                 plane = node->plane;
1425                 if (plane->type < 3)
1426                 {
1427                         t1 = p1[plane->type] - plane->dist;
1428                         t2 = p2[plane->type] - plane->dist;
1429                 }
1430                 else
1431                 {
1432                         t1 = DotProduct (plane->normal, p1) - plane->dist;
1433                         t2 = DotProduct (plane->normal, p2) - plane->dist;
1434                 }
1435                 if (t1 < 0)
1436                 {
1437                         if (t2 < 0)
1438                         {
1439                                 node = node->children[1];
1440                                 continue;
1441                         }
1442                         side = 1;
1443                 }
1444                 else
1445                 {
1446                         if (t2 >= 0)
1447                         {
1448                                 node = node->children[0];
1449                                 continue;
1450                         }
1451                         side = 0;
1452                 }
1453
1454                 // the line intersects, find intersection point
1455                 // LadyHavoc: this uses the original trace for maximum accuracy
1456                 if (plane->type < 3)
1457                 {
1458                         t1 = t->start[plane->type] - plane->dist;
1459                         t2 = t->end[plane->type] - plane->dist;
1460                 }
1461                 else
1462                 {
1463                         t1 = DotProduct (plane->normal, t->start) - plane->dist;
1464                         t2 = DotProduct (plane->normal, t->end) - plane->dist;
1465                 }
1466         
1467                 midf = t1 / (t1 - t2);
1468                 VectorMA(t->start, midf, t->dist, mid);
1469
1470                 // recurse both sides, front side first, return if we hit a surface
1471                 if (Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side], p1, mid) == HULLCHECKSTATE_DONE)
1472                         return HULLCHECKSTATE_DONE;
1473
1474                 // test each surface on the node
1475                 Mod_Q1BSP_TraceLineAgainstSurfacesFindTextureOnNode(t, model, node, mid);
1476                 if (t->trace->hittexture)
1477                         return HULLCHECKSTATE_DONE;
1478
1479                 // recurse back side
1480                 return Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(t, model, node->children[side ^ 1], mid, p2);
1481         }
1482         leaf = (const mleaf_t *)node;
1483         side = Mod_Q1BSP_SuperContentsFromNativeContents(leaf->contents);
1484         if (!t->trace->startfound)
1485         {
1486                 t->trace->startfound = true;
1487                 t->trace->startsupercontents |= side;
1488         }
1489         if (side & SUPERCONTENTS_LIQUIDSMASK)
1490                 t->trace->inwater = true;
1491         if (side == 0)
1492                 t->trace->inopen = true;
1493         if (side & t->trace->hitsupercontentsmask)
1494         {
1495                 // if the first leaf is solid, set startsolid
1496                 if (t->trace->allsolid)
1497                         t->trace->startsolid = true;
1498                 return HULLCHECKSTATE_SOLID;
1499         }
1500         else
1501         {
1502                 t->trace->allsolid = false;
1503                 return HULLCHECKSTATE_EMPTY;
1504         }
1505 }
1506
1507 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, int skipsupercontentsmask, int skipmaterialflagsmask)
1508 {
1509         RecursiveHullCheckTraceInfo_t rhc;
1510
1511         memset(&rhc, 0, sizeof(rhc));
1512         memset(trace, 0, sizeof(trace_t));
1513         rhc.trace = trace;
1514         rhc.trace->hitsupercontentsmask = hitsupercontentsmask;
1515         rhc.trace->skipsupercontentsmask = skipsupercontentsmask;
1516         rhc.trace->skipmaterialflagsmask = skipmaterialflagsmask;
1517         rhc.trace->fraction = 1;
1518         rhc.trace->allsolid = true;
1519         rhc.hull = &model->brushq1.hulls[0]; // 0x0x0
1520         VectorCopy(start, rhc.start);
1521         VectorCopy(end, rhc.end);
1522         VectorSubtract(rhc.end, rhc.start, rhc.dist);
1523         Mod_Q1BSP_TraceLineAgainstSurfacesRecursiveBSPNode(&rhc, model, model->brush.data_nodes + rhc.hull->firstclipnode, rhc.start, rhc.end);
1524         VectorMA(rhc.start, rhc.trace->fraction, rhc.dist, rhc.trace->endpos);
1525 }
1526
1527 static void Mod_BSP_DecompressVis(const unsigned char *in, const unsigned char *inend, unsigned char *out, unsigned char *outend)
1528 {
1529         int c;
1530         unsigned char *outstart = out;
1531         while (out < outend)
1532         {
1533                 if (in == inend)
1534                 {
1535                         Con_Printf("Mod_BSP_DecompressVis: input underrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
1536                         return;
1537                 }
1538                 c = *in++;
1539                 if (c)
1540                         *out++ = c;
1541                 else
1542                 {
1543                         if (in == inend)
1544                         {
1545                                 Con_Printf("Mod_BSP_DecompressVis: input underrun (during zero-run) on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
1546                                 return;
1547                         }
1548                         for (c = *in++;c > 0;c--)
1549                         {
1550                                 if (out == outend)
1551                                 {
1552                                         Con_Printf("Mod_BSP_DecompressVis: output overrun on model \"%s\" (decompressed %i of %i output bytes)\n", loadmodel->name, (int)(out - outstart), (int)(outend - outstart));
1553                                         return;
1554                                 }
1555                                 *out++ = 0;
1556                         }
1557                 }
1558         }
1559 }
1560
1561 /*
1562 =============
1563 Mod_Q1BSP_LoadSplitSky
1564
1565 A sky texture is 256*128, with the right side being a masked overlay
1566 ==============
1567 */
1568 static void Mod_Q1BSP_LoadSplitSky (unsigned char *src, int width, int height, int bytesperpixel)
1569 {
1570         int x, y;
1571         int w = width/2;
1572         int h = height;
1573         unsigned int *solidpixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1574         unsigned int *alphapixels = (unsigned int *)Mem_Alloc(tempmempool, w*h*sizeof(unsigned char[4]));
1575
1576         // allocate a texture pool if we need it
1577         if (loadmodel->texturepool == NULL && cls.state != ca_dedicated)
1578                 loadmodel->texturepool = R_AllocTexturePool();
1579
1580         if (bytesperpixel == 4)
1581         {
1582                 for (y = 0;y < h;y++)
1583                 {
1584                         for (x = 0;x < w;x++)
1585                         {
1586                                 solidpixels[y*w+x] = ((unsigned *)src)[y*width+x+w];
1587                                 alphapixels[y*w+x] = ((unsigned *)src)[y*width+x];
1588                         }
1589                 }
1590         }
1591         else
1592         {
1593                 // make an average value for the back to avoid
1594                 // a fringe on the top level
1595                 int p, r, g, b;
1596                 union
1597                 {
1598                         unsigned int i;
1599                         unsigned char b[4];
1600                 }
1601                 bgra;
1602                 r = g = b = 0;
1603                 for (y = 0;y < h;y++)
1604                 {
1605                         for (x = 0;x < w;x++)
1606                         {
1607                                 p = src[x*width+y+w];
1608                                 r += palette_rgb[p][0];
1609                                 g += palette_rgb[p][1];
1610                                 b += palette_rgb[p][2];
1611                         }
1612                 }
1613                 bgra.b[2] = r/(w*h);
1614                 bgra.b[1] = g/(w*h);
1615                 bgra.b[0] = b/(w*h);
1616                 bgra.b[3] = 0;
1617                 for (y = 0;y < h;y++)
1618                 {
1619                         for (x = 0;x < w;x++)
1620                         {
1621                                 solidpixels[y*w+x] = palette_bgra_complete[src[y*width+x+w]];
1622                                 p = src[y*width+x];
1623                                 alphapixels[y*w+x] = p ? palette_bgra_complete[p] : bgra.i;
1624                         }
1625                 }
1626         }
1627
1628         loadmodel->brush.solidskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_solidtexture", 0         , (unsigned char *) solidpixels, w, h, 0, 0, 0, vid.sRGB3D);
1629         loadmodel->brush.alphaskyskinframe = R_SkinFrame_LoadInternalBGRA("sky_alphatexture", TEXF_ALPHA, (unsigned char *) alphapixels, w, h, 0, 0, 0, vid.sRGB3D);
1630         Mem_Free(solidpixels);
1631         Mem_Free(alphapixels);
1632 }
1633
1634 static void Mod_Q1BSP_LoadTextures(sizebuf_t *sb)
1635 {
1636         int i, j, k, num, max, altmax, mtwidth, mtheight, doffset, incomplete, nummiptex = 0, firstskynoshadowtexture = 0;
1637         skinframe_t *skinframemissing;
1638         texture_t *tx, *tx2, *anims[10], *altanims[10], *currentskynoshadowtexture;
1639         texture_t backuptex;
1640         unsigned char *data, *mtdata;
1641         const char *s;
1642         char mapname[MAX_QPATH], name[MAX_QPATH];
1643         unsigned char zeroopaque[4], zerotrans[4];
1644         sizebuf_t miptexsb;
1645         char vabuf[1024];
1646         Vector4Set(zeroopaque, 0, 0, 0, 255);
1647         Vector4Set(zerotrans, 0, 0, 0, 128);
1648
1649         loadmodel->data_textures = NULL;
1650
1651         // add two slots for notexture walls and notexture liquids, and duplicate
1652         // all sky textures; sky surfaces can be shadow-casting or not, the surface
1653         // loading will choose according to the contents behind the surface
1654         // (necessary to support e1m5 logo shadow which has a SKY contents brush,
1655         // while correctly treating sky textures as occluders in other situations).
1656         if (sb->cursize)
1657         {
1658                 int numsky = 0;
1659                 size_t watermark;
1660                 nummiptex = MSG_ReadLittleLong(sb);
1661                 loadmodel->num_textures = nummiptex + 2;
1662                 // save the position so we can go back to it
1663                 watermark = sb->readcount;
1664                 for (i = 0; i < nummiptex; i++)
1665                 {
1666                         doffset = MSG_ReadLittleLong(sb);
1667                         if (r_nosurftextures.integer)
1668                                 continue;
1669                         if (doffset == -1)
1670                         {
1671                                 Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1672                                 continue;
1673                         }
1674
1675                         MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1676
1677                         // copy name, but only up to 16 characters
1678                         // (the output buffer can hold more than this, but the input buffer is
1679                         //  only 16)
1680                         for (j = 0; j < 16; j++)
1681                                 name[j] = MSG_ReadByte(&miptexsb);
1682                         name[j] = 0;
1683                         // pretty up the buffer (replacing any trailing garbage with 0)
1684                         for (j = (int)strlen(name); j < 16; j++)
1685                                 name[j] = 0;
1686                         // bones_was_here: force all names to lowercase (matching code below) so we don't crash on e2m9
1687                         for (j = 0;name[j];j++)
1688                                 if (name[j] >= 'A' && name[j] <= 'Z')
1689                                         name[j] += 'a' - 'A';
1690
1691                         if (!strncmp(name, "sky", 3))
1692                                 numsky++;
1693                 }
1694
1695                 // bump it back to where we started parsing
1696                 sb->readcount = (int)watermark;
1697
1698                 firstskynoshadowtexture = loadmodel->num_textures;
1699                 loadmodel->num_textures += numsky;
1700         }
1701         else
1702         {
1703                 loadmodel->num_textures = 2;
1704                 firstskynoshadowtexture = loadmodel->num_textures;
1705         }
1706         loadmodel->num_texturesperskin = loadmodel->num_textures;
1707
1708         loadmodel->data_textures = (texture_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_textures * sizeof(texture_t));
1709
1710         // we'll be writing to these in parallel for sky textures
1711         currentskynoshadowtexture = loadmodel->data_textures + firstskynoshadowtexture;
1712
1713         // fill out all slots with notexture
1714         skinframemissing = R_SkinFrame_LoadMissing();
1715         for (i = 0, tx = loadmodel->data_textures;i < loadmodel->num_textures;i++, tx++)
1716         {
1717                 dp_strlcpy(tx->name, "NO TEXTURE FOUND", sizeof(tx->name));
1718                 tx->width = 16;
1719                 tx->height = 16;
1720                 tx->basealpha = 1.0f;
1721                 tx->materialshaderpass = tx->shaderpasses[0] = Mod_CreateShaderPass(loadmodel->mempool, skinframemissing);
1722                 tx->materialshaderpass->skinframes[0] = skinframemissing;
1723                 tx->currentskinframe = skinframemissing;
1724                 tx->basematerialflags = MATERIALFLAG_WALL;
1725                 if (i == loadmodel->num_textures - 1)
1726                 {
1727                         tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1728                         tx->supercontents = mod_q1bsp_texture_water.supercontents;
1729                         tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1730                 }
1731                 else
1732                 {
1733                         tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1734                         tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1735                 }
1736                 tx->currentframe = tx;
1737
1738                 // clear water settings
1739                 tx->reflectmin = 0;
1740                 tx->reflectmax = 1;
1741                 tx->refractive_index = mod_q3shader_default_refractive_index.value;
1742                 tx->refractfactor = 1;
1743                 Vector4Set(tx->refractcolor4f, 1, 1, 1, 1);
1744                 tx->reflectfactor = 1;
1745                 Vector4Set(tx->reflectcolor4f, 1, 1, 1, 1);
1746                 tx->r_water_wateralpha = 1;
1747                 tx->offsetmapping = OFFSETMAPPING_DEFAULT;
1748                 tx->offsetscale = 1;
1749                 tx->offsetbias = 0;
1750                 tx->specularscalemod = 1;
1751                 tx->specularpowermod = 1;
1752                 tx->transparentsort = TRANSPARENTSORT_DISTANCE;
1753                 // WHEN ADDING DEFAULTS HERE, REMEMBER TO PUT DEFAULTS IN ALL LOADERS
1754                 // JUST GREP FOR "specularscalemod = 1".
1755         }
1756
1757         if (!sb->cursize)
1758         {
1759                 Con_Printf("%s: no miptex lump to load textures from\n", loadmodel->name);
1760                 return;
1761         }
1762
1763         s = loadmodel->name;
1764         if (!strncasecmp(s, "maps/", 5))
1765                 s += 5;
1766         FS_StripExtension(s, mapname, sizeof(mapname));
1767
1768         // LadyHavoc: mostly rewritten map texture loader
1769         for (i = 0;i < nummiptex;i++)
1770         {
1771                 doffset = MSG_ReadLittleLong(sb);
1772                 if (r_nosurftextures.integer)
1773                         continue;
1774                 if (doffset == -1)
1775                 {
1776                         Con_DPrintf("%s: miptex #%i missing\n", loadmodel->name, i);
1777                         continue;
1778                 }
1779
1780                 MSG_InitReadBuffer(&miptexsb, sb->data + doffset, sb->cursize - doffset);
1781
1782                 // copy name, but only up to 16 characters
1783                 // (the output buffer can hold more than this, but the input buffer is
1784                 //  only 16)
1785                 for (j = 0;j < 16;j++)
1786                         name[j] = MSG_ReadByte(&miptexsb);
1787                 name[j] = 0;
1788                 // pretty up the buffer (replacing any trailing garbage with 0)
1789                 for (j = (int)strlen(name);j < 16;j++)
1790                         name[j] = 0;
1791
1792                 if (!name[0])
1793                 {
1794                         dpsnprintf(name, sizeof(name), "unnamed%i", i);
1795                         Con_DPrintf("%s: warning: renaming unnamed texture to %s\n", loadmodel->name, name);
1796                 }
1797
1798                 mtwidth = MSG_ReadLittleLong(&miptexsb);
1799                 mtheight = MSG_ReadLittleLong(&miptexsb);
1800                 mtdata = NULL;
1801                 j = MSG_ReadLittleLong(&miptexsb);
1802                 if (j)
1803                 {
1804                         // texture included
1805                         if (j < 40 || j + mtwidth * mtheight > miptexsb.cursize)
1806                         {
1807                                 Con_Printf("%s: Texture \"%s\" is corrupt or incomplete\n", loadmodel->name, name);
1808                                 continue;
1809                         }
1810                         mtdata = miptexsb.data + j;
1811                 }
1812
1813                 if ((mtwidth & 15) || (mtheight & 15))
1814                         Con_DPrintf("%s: warning: texture \"%s\" is not 16 aligned\n", loadmodel->name, name);
1815
1816                 // LadyHavoc: force all names to lowercase
1817                 for (j = 0;name[j];j++)
1818                         if (name[j] >= 'A' && name[j] <= 'Z')
1819                                 name[j] += 'a' - 'A';
1820
1821                 tx = loadmodel->data_textures + i;
1822                 // try to load shader or external textures, but first we have to backup the texture_t because shader loading overwrites it even if it fails
1823                 backuptex = loadmodel->data_textures[i];
1824                 if (name[0] && /* HACK */ strncmp(name, "sky", 3) /* END HACK */ && (Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, loadmodel->data_textures + i, va(vabuf, sizeof(vabuf), "%s/%s", mapname, name), false, false, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL) ||
1825                                 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, loadmodel->data_textures + i, va(vabuf, sizeof(vabuf), "%s"   , name), false, false, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL)))
1826                 {
1827                         // set the width/height fields which are used for parsing texcoords in this bsp format
1828                         tx->width = mtwidth;
1829                         tx->height = mtheight;
1830                         continue;
1831                 }
1832                 // no luck with loading shaders or external textures - restore the in-progress texture loading
1833                 loadmodel->data_textures[i] = backuptex;
1834
1835                 dp_strlcpy(tx->name, name, sizeof(tx->name));
1836                 tx->width = mtwidth;
1837                 tx->height = mtheight;
1838                 tx->basealpha = 1.0f;
1839
1840                 // start out with no animation
1841                 tx->currentframe = tx;
1842                 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
1843
1844                 if (tx->name[0] == '*')
1845                 {
1846                         if (!strncmp(tx->name, "*lava", 5))
1847                         {
1848                                 tx->supercontents = mod_q1bsp_texture_lava.supercontents;
1849                                 tx->surfaceflags = mod_q1bsp_texture_lava.surfaceflags;
1850                         }
1851                         else if (!strncmp(tx->name, "*slime", 6))
1852                         {
1853                                 tx->supercontents = mod_q1bsp_texture_slime.supercontents;
1854                                 tx->surfaceflags = mod_q1bsp_texture_slime.surfaceflags;
1855                         }
1856                         else
1857                         {
1858                                 tx->supercontents = mod_q1bsp_texture_water.supercontents;
1859                                 tx->surfaceflags = mod_q1bsp_texture_water.surfaceflags;
1860                         }
1861                 }
1862                 else if (!strncmp(tx->name, "sky", 3))
1863                 {
1864                         tx->supercontents = mod_q1bsp_texture_sky.supercontents;
1865                         tx->surfaceflags = mod_q1bsp_texture_sky.surfaceflags;
1866                         // for the surface traceline we need to hit this surface as a solid...
1867                         tx->supercontents |= SUPERCONTENTS_SOLID;
1868                 }
1869                 else
1870                 {
1871                         tx->supercontents = mod_q1bsp_texture_solid.supercontents;
1872                         tx->surfaceflags = mod_q1bsp_texture_solid.surfaceflags;
1873                 }
1874
1875                 if (cls.state != ca_dedicated)
1876                 {
1877                         skinframe_t *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, false);
1878                         if ((!skinframe &&
1879                             !(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, false)))
1880                                 // HACK: It loads custom skybox textures as a wall if loaded as a skinframe.
1881                                 || !strncmp(tx->name, "sky", 3))
1882                         {
1883                                 // did not find external texture via shader loading, load it from the bsp or wad3
1884                                 if (loadmodel->brush.ishlbsp)
1885                                 {
1886                                         // internal texture overrides wad
1887                                         unsigned char* pixels, * freepixels;
1888                                         pixels = freepixels = NULL;
1889                                         if (mtdata)
1890                                                 pixels = W_ConvertWAD3TextureBGRA(&miptexsb);
1891                                         if (pixels == NULL)
1892                                                 pixels = freepixels = W_GetTextureBGRA(tx->name);
1893                                         if (pixels != NULL)
1894                                         {
1895                                                 tx->width = image_width;
1896                                                 tx->height = image_height;
1897                                                 tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, pixels, image_width, image_height, image_width, image_height, CRC_Block(pixels, image_width * image_height * 4), true);
1898                                         }
1899                                         if (freepixels)
1900                                                 Mem_Free(freepixels);
1901                                 }
1902                                 else if (!strncmp(tx->name, "sky", 3) && mtwidth == mtheight * 2)
1903                                 {
1904                                         data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s/%s", mapname, tx->name), false, false, false, NULL);
1905                                         if (!data)
1906                                                 data = loadimagepixelsbgra(gamemode == GAME_TENEBRAE ? tx->name : va(vabuf, sizeof(vabuf), "textures/%s", tx->name), false, false, false, NULL);
1907                                         if (data && image_width == image_height * 2)
1908                                         {
1909                                                 Mod_Q1BSP_LoadSplitSky(data, image_width, image_height, 4);
1910                                                 Mem_Free(data);
1911                                         }
1912                                         else if (mtdata != NULL)
1913                                                 Mod_Q1BSP_LoadSplitSky(mtdata, mtwidth, mtheight, 1);
1914                                 }
1915                                 else if (mtdata) // texture included
1916                                         tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalQuake(tx->name, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP, false, r_fullbrights.integer, mtdata, tx->width, tx->height);
1917                                 // if mtdata is NULL, the "missing" texture has already been assigned to this
1918                                 // LadyHavoc: some Tenebrae textures get replaced by black
1919                                 if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1920                                         tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, TEXF_MIPMAP | TEXF_ALPHA, zerotrans, 1, 1, 0, 0, 0, false);
1921                                 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1922                                         tx->materialshaderpass->skinframes[0] = R_SkinFrame_LoadInternalBGRA(tx->name, 0, zeroopaque, 1, 1, 0, 0, 0, false);
1923                         }
1924                         else
1925                                 tx->materialshaderpass->skinframes[0] = skinframe;
1926                         tx->currentskinframe = tx->materialshaderpass->skinframes[0];
1927                 }
1928
1929                 tx->basematerialflags = MATERIALFLAG_WALL;
1930                 if (tx->name[0] == '*')
1931                 {
1932                         // LadyHavoc: some turbulent textures should not be affected by wateralpha
1933                         if (!strncmp(tx->name, "*glassmirror", 12)) // Tenebrae
1934                                 tx->basematerialflags |= MATERIALFLAG_NOSHADOW | MATERIALFLAG_ADD | MATERIALFLAG_BLENDED | MATERIALFLAG_REFLECTION;
1935                         else if (!strncmp(tx->name,"*lava",5)
1936                          || !strncmp(tx->name,"*teleport",9)
1937                          || !strncmp(tx->name,"*rift",5)) // Scourge of Armagon texture
1938                                 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW;
1939                         else
1940                                 tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_LIGHTBOTHSIDES | MATERIALFLAG_NOSHADOW | MATERIALFLAG_WATERALPHA | MATERIALFLAG_WATERSHADER;
1941                         if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1942                                 tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1943                 }
1944                 else if (tx->name[0] == '{') // fence textures
1945                 {
1946                         tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
1947                 }
1948                 else if (!strncmp(tx->name, "mirror", 6)) // Tenebrae
1949                 {
1950                         // replace the texture with black
1951                         tx->basematerialflags |= MATERIALFLAG_REFLECTION;
1952                 }
1953                 else if (!strncmp(tx->name, "sky", 3))
1954                         tx->basematerialflags = MATERIALFLAG_SKY;
1955                 else if (!strcmp(tx->name, "caulk"))
1956                         tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
1957                 else if (tx->currentskinframe != NULL && tx->currentskinframe->hasalpha)
1958                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED | MATERIALFLAG_NOSHADOW;
1959                 tx->currentmaterialflags = tx->basematerialflags;
1960
1961                 // duplicate of sky with NOSHADOW
1962                 if (tx->basematerialflags & MATERIALFLAG_SKY)
1963                 {
1964                         *currentskynoshadowtexture = *tx;
1965                         currentskynoshadowtexture->basematerialflags |= MATERIALFLAG_NOSHADOW;
1966                         tx->skynoshadowtexture = currentskynoshadowtexture;
1967                         currentskynoshadowtexture++;
1968                 }
1969         }
1970
1971         // sequence the animations
1972         for (i = 0;i < nummiptex;i++)
1973         {
1974                 tx = loadmodel->data_textures + i;
1975                 if (!tx || tx->name[0] != '+' || tx->name[1] == 0 || tx->name[2] == 0)
1976                         continue;
1977                 num = tx->name[1];
1978                 if ((num < '0' || num > '9') && (num < 'a' || num > 'j'))
1979                 {
1980                         Con_Printf("Bad animating texture %s\n", tx->name);
1981                         continue;
1982                 }
1983                 if (tx->anim_total[0] || tx->anim_total[1])
1984                         continue;       // already sequenced
1985
1986                 // find the number of frames in the animation
1987                 memset(anims, 0, sizeof(anims));
1988                 memset(altanims, 0, sizeof(altanims));
1989
1990                 for (j = i;j < nummiptex;j++)
1991                 {
1992                         tx2 = loadmodel->data_textures + j;
1993                         if (!tx2 || tx2->name[0] != '+' || strcmp(tx2->name+2, tx->name+2))
1994                                 continue;
1995
1996                         num = tx2->name[1];
1997                         if (num >= '0' && num <= '9')
1998                                 anims[num - '0'] = tx2;
1999                         else if (num >= 'a' && num <= 'j')
2000                                 altanims[num - 'a'] = tx2;
2001                         // No need to warn otherwise - we already did above.
2002                 }
2003
2004                 max = altmax = 0;
2005                 for (j = 0;j < 10;j++)
2006                 {
2007                         if (anims[j])
2008                                 max = j + 1;
2009                         if (altanims[j])
2010                                 altmax = j + 1;
2011                 }
2012                 //Con_Printf("linking animation %s (%i:%i frames)\n\n", tx->name, max, altmax);
2013
2014                 incomplete = false;
2015                 for (j = 0;j < max;j++)
2016                 {
2017                         if (!anims[j])
2018                         {
2019                                 Con_Printf("Missing frame %i of %s\n", j, tx->name);
2020                                 incomplete = true;
2021                         }
2022                 }
2023                 for (j = 0;j < altmax;j++)
2024                 {
2025                         if (!altanims[j])
2026                         {
2027                                 Con_Printf("Missing altframe %i of %s\n", j, tx->name);
2028                                 incomplete = true;
2029                         }
2030                 }
2031                 if (incomplete)
2032                         continue;
2033
2034                 // If we have exactly one frame, something's wrong.
2035                 if (max + altmax <= 1)
2036                 {
2037                         Con_Printf("Texture %s is animated (leading +) but has only one frame\n", tx->name);
2038                 }
2039
2040                 if (altmax < 1)
2041                 {
2042                         // if there is no alternate animation, duplicate the primary
2043                         // animation into the alternate
2044                         altmax = max;
2045                         for (k = 0;k < 10;k++)
2046                                 altanims[k] = anims[k];
2047                 }
2048
2049                 if (max < 1)
2050                 {
2051                         // Warn.
2052                         Con_Printf("Missing frame 0 of %s\n", tx->name);
2053
2054                         // however, we can handle this by duplicating the alternate animation into the primary
2055                         max = altmax;
2056                         for (k = 0;k < 10;k++)
2057                                 anims[k] = altanims[k];
2058                 }
2059
2060
2061                 // link together the primary animation
2062                 for (j = 0;j < max;j++)
2063                 {
2064                         tx2 = anims[j];
2065                         tx2->animated = 1; // q1bsp
2066                         tx2->anim_total[0] = max;
2067                         tx2->anim_total[1] = altmax;
2068                         for (k = 0;k < 10;k++)
2069                         {
2070                                 tx2->anim_frames[0][k] = anims[k];
2071                                 tx2->anim_frames[1][k] = altanims[k];
2072                         }
2073                 }
2074
2075                 // if there really is an alternate anim...
2076                 if (anims[0] != altanims[0])
2077                 {
2078                         // link together the alternate animation
2079                         for (j = 0;j < altmax;j++)
2080                         {
2081                                 tx2 = altanims[j];
2082                                 tx2->animated = 1; // q1bsp
2083                                 // the primary/alternate are reversed here
2084                                 tx2->anim_total[0] = altmax;
2085                                 tx2->anim_total[1] = max;
2086                                 for (k = 0;k < 10;k++)
2087                                 {
2088                                         tx2->anim_frames[0][k] = altanims[k];
2089                                         tx2->anim_frames[1][k] = anims[k];
2090                                 }
2091                         }
2092                 }
2093         }
2094 }
2095
2096 static void Mod_Q1BSP_LoadLighting(sizebuf_t *sb)
2097 {
2098         int i;
2099         unsigned char *in, *out, *data, d;
2100         char litfilename[MAX_QPATH];
2101         char dlitfilename[MAX_QPATH];
2102         fs_offset_t filesize;
2103         if (loadmodel->brush.ishlbsp) // LadyHavoc: load the colored lighting data straight
2104         {
2105                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2106                 for (i = 0;i < sb->cursize;i++)
2107                         loadmodel->brushq1.lightdata[i] = sb->data[i] >>= 1;
2108         }
2109         else // LadyHavoc: bsp version 29 (normal white lighting)
2110         {
2111                 // LadyHavoc: hope is not lost yet, check for a .lit file to load
2112                 dp_strlcpy (litfilename, loadmodel->name, sizeof (litfilename));
2113                 FS_StripExtension (litfilename, litfilename, sizeof (litfilename));
2114                 dp_strlcpy (dlitfilename, litfilename, sizeof (dlitfilename));
2115                 dp_strlcat (litfilename, ".lit", sizeof (litfilename));
2116                 dp_strlcat (dlitfilename, ".dlit", sizeof (dlitfilename));
2117                 data = (unsigned char*) FS_LoadFile(litfilename, tempmempool, false, &filesize);
2118                 if (data)
2119                 {
2120                         if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2121                         {
2122                                 i = LittleLong(((int *)data)[1]);
2123                                 if (i == 1)
2124                                 {
2125                                         if (developer_loading.integer)
2126                                                 Con_Printf("loaded %s\n", litfilename);
2127                                         loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2128                                         memcpy(loadmodel->brushq1.lightdata, data + 8, filesize - 8);
2129                                         Mem_Free(data);
2130                                         data = (unsigned char*) FS_LoadFile(dlitfilename, tempmempool, false, &filesize);
2131                                         if (data)
2132                                         {
2133                                                 if (filesize == (fs_offset_t)(8 + sb->cursize * 3) && data[0] == 'Q' && data[1] == 'L' && data[2] == 'I' && data[3] == 'T')
2134                                                 {
2135                                                         i = LittleLong(((int *)data)[1]);
2136                                                         if (i == 1)
2137                                                         {
2138                                                                 if (developer_loading.integer)
2139                                                                         Con_Printf("loaded %s\n", dlitfilename);
2140                                                                 loadmodel->brushq1.nmaplightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, filesize - 8);
2141                                                                 memcpy(loadmodel->brushq1.nmaplightdata, data + 8, filesize - 8);
2142                                                                 loadmodel->brushq3.deluxemapping_modelspace = false;
2143                                                                 loadmodel->brushq3.deluxemapping = true;
2144                                                         }
2145                                                 }
2146                                                 Mem_Free(data);
2147                                                 data = NULL;
2148                                         }
2149                                         return;
2150                                 }
2151                                 else
2152                                         Con_Printf("Unknown .lit file version (%d)\n", i);
2153                         }
2154                         else if (filesize == 8)
2155                                 Con_Print("Empty .lit file, ignoring\n");
2156                         else
2157                                 Con_Printf("Corrupt .lit file (file size %i bytes, should be %i bytes), ignoring\n", (int) filesize, (int) (8 + sb->cursize * 3));
2158                         if (data)
2159                         {
2160                                 Mem_Free(data);
2161                                 data = NULL;
2162                         }
2163                 }
2164                 // LadyHavoc: oh well, expand the white lighting data
2165                 if (!sb->cursize)
2166                         return;
2167                 loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize*3);
2168                 in = sb->data;
2169                 out = loadmodel->brushq1.lightdata;
2170                 for (i = 0;i < sb->cursize;i++)
2171                 {
2172                         d = *in++;
2173                         *out++ = d;
2174                         *out++ = d;
2175                         *out++ = d;
2176                 }
2177         }
2178 }
2179
2180 static void Mod_Q1BSP_LoadVisibility(sizebuf_t *sb)
2181 {
2182         loadmodel->brushq1.num_compressedpvs = 0;
2183         loadmodel->brushq1.data_compressedpvs = NULL;
2184         if (!sb->cursize)
2185                 return;
2186         loadmodel->brushq1.num_compressedpvs = sb->cursize;
2187         loadmodel->brushq1.data_compressedpvs = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
2188         MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.data_compressedpvs);
2189 }
2190
2191 // used only for HalfLife maps
2192 static void Mod_Q1BSP_ParseWadsFromEntityLump(const char *data)
2193 {
2194         char key[128], value[4096];
2195         int i, j, k;
2196         if (!data)
2197                 return;
2198         if (!COM_ParseToken_Simple(&data, false, false, true))
2199                 return; // error
2200         if (com_token[0] != '{')
2201                 return; // error
2202         while (1)
2203         {
2204                 if (!COM_ParseToken_Simple(&data, false, false, true))
2205                         return; // error
2206                 if (com_token[0] == '}')
2207                         break; // end of worldspawn
2208                 if (com_token[0] == '_')
2209                         dp_strlcpy(key, com_token + 1, sizeof(key));
2210                 else
2211                         dp_strlcpy(key, com_token, sizeof(key));
2212                 while (key[strlen(key)-1] == ' ') // remove trailing spaces
2213                         key[strlen(key)-1] = 0;
2214                 if (!COM_ParseToken_Simple(&data, false, false, true))
2215                         return; // error
2216                 dpsnprintf(value, sizeof(value), "%s", com_token);
2217                 if (!strcmp("wad", key)) // for HalfLife maps
2218                 {
2219                         if (loadmodel->brush.ishlbsp)
2220                         {
2221                                 j = 0;
2222                                 for (i = 0;i < (int)sizeof(value);i++)
2223                                         if (value[i] != ';' && value[i] != '\\' && value[i] != '/' && value[i] != ':')
2224                                                 break;
2225                                 if (i < (int)sizeof(value) && value[i])
2226                                 {
2227                                         for (;i < (int)sizeof(value);i++)
2228                                         {
2229                                                 // ignore path - the \\ check is for HalfLife... stupid windoze 'programmers'...
2230                                                 if (value[i] == '\\' || value[i] == '/' || value[i] == ':')
2231                                                         j = i+1;
2232                                                 else if (value[i] == ';' || value[i] == 0)
2233                                                 {
2234                                                         k = value[i];
2235                                                         value[i] = 0;
2236                                                         W_LoadTextureWadFile(&value[j], false);
2237                                                         j = i+1;
2238                                                         if (!k)
2239                                                                 break;
2240                                                 }
2241                                         }
2242                                 }
2243                         }
2244                 }
2245         }
2246 }
2247
2248 static void Mod_Q1BSP_LoadEntities(sizebuf_t *sb)
2249 {
2250         loadmodel->brush.entities = NULL;
2251         if (!sb->cursize)
2252                 return;
2253         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
2254         MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
2255         loadmodel->brush.entities[sb->cursize] = 0;
2256         if (loadmodel->brush.ishlbsp)
2257                 Mod_Q1BSP_ParseWadsFromEntityLump(loadmodel->brush.entities);
2258 }
2259
2260
2261 static void Mod_Q1BSP_LoadVertexes(sizebuf_t *sb)
2262 {
2263         mvertex_t       *out;
2264         int                     i, count;
2265         int                     structsize = 12;
2266
2267         if (sb->cursize % structsize)
2268                 Host_Error("Mod_Q1BSP_LoadVertexes: funny lump size in %s",loadmodel->name);
2269         count = sb->cursize / structsize;
2270         out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2271
2272         loadmodel->brushq1.vertexes = out;
2273         loadmodel->brushq1.numvertexes = count;
2274
2275         for ( i=0 ; i<count ; i++, out++)
2276         {
2277                 out->position[0] = MSG_ReadLittleFloat(sb);
2278                 out->position[1] = MSG_ReadLittleFloat(sb);
2279                 out->position[2] = MSG_ReadLittleFloat(sb);
2280         }
2281 }
2282
2283 static void Mod_BSP_LoadSubmodels(sizebuf_t *sb, hullinfo_t *hullinfo)
2284 {
2285         mmodel_t        *out;
2286         int                     i, j, count;
2287         int                     structsize = hullinfo ? (48+4*hullinfo->filehulls) : 48;
2288
2289         if (sb->cursize % structsize)
2290                 Host_Error ("Mod_BSP_LoadSubmodels: funny lump size in %s", loadmodel->name);
2291
2292         count = sb->cursize / structsize;
2293         out = (mmodel_t *)Mem_Alloc (loadmodel->mempool, count*sizeof(*out));
2294
2295         loadmodel->brushq1.submodels = out;
2296         loadmodel->brush.numsubmodels = count;
2297
2298         for (i = 0; i < count; i++, out++)
2299         {
2300         // spread out the mins / maxs by a pixel
2301                 out->mins[0] = MSG_ReadLittleFloat(sb) - 1;
2302                 out->mins[1] = MSG_ReadLittleFloat(sb) - 1;
2303                 out->mins[2] = MSG_ReadLittleFloat(sb) - 1;
2304                 out->maxs[0] = MSG_ReadLittleFloat(sb) + 1;
2305                 out->maxs[1] = MSG_ReadLittleFloat(sb) + 1;
2306                 out->maxs[2] = MSG_ReadLittleFloat(sb) + 1;
2307                 out->origin[0] = MSG_ReadLittleFloat(sb);
2308                 out->origin[1] = MSG_ReadLittleFloat(sb);
2309                 out->origin[2] = MSG_ReadLittleFloat(sb);
2310                 if(hullinfo)
2311                 {
2312                         for (j = 0; j < hullinfo->filehulls; j++)
2313                                 out->headnode[j] = MSG_ReadLittleLong(sb);
2314                         out->visleafs  = MSG_ReadLittleLong(sb);
2315                 }
2316                 else // Quake 2 has only one hull
2317                         out->headnode[0] = MSG_ReadLittleLong(sb);
2318
2319                 out->firstface = MSG_ReadLittleLong(sb);
2320                 out->numfaces  = MSG_ReadLittleLong(sb);
2321         }
2322 }
2323
2324 static void Mod_Q1BSP_LoadEdges(sizebuf_t *sb)
2325 {
2326         medge_t *out;
2327         int     i, count;
2328         int             structsize = loadmodel->brush.isbsp2 ? 8 : 4;
2329
2330         if (sb->cursize % structsize)
2331                 Host_Error("Mod_Q1BSP_LoadEdges: funny lump size in %s",loadmodel->name);
2332         count = sb->cursize / structsize;
2333         out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2334
2335         loadmodel->brushq1.edges = out;
2336         loadmodel->brushq1.numedges = count;
2337
2338         for ( i=0 ; i<count ; i++, out++)
2339         {
2340                 if (loadmodel->brush.isbsp2)
2341                 {
2342                         out->v[0] = (unsigned int)MSG_ReadLittleLong(sb);
2343                         out->v[1] = (unsigned int)MSG_ReadLittleLong(sb);
2344                 }
2345                 else
2346                 {
2347                         out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
2348                         out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
2349                 }
2350                 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
2351                 {
2352                         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);
2353                         if(!loadmodel->brushq1.numvertexes)
2354                                 Host_Error("Mod_Q1BSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
2355                                 
2356                         out->v[0] = 0;
2357                         out->v[1] = 0;
2358                 }
2359         }
2360 }
2361
2362 static void Mod_Q1BSP_LoadTexinfo(sizebuf_t *sb)
2363 {
2364         mtexinfo_t *out;
2365         int i, j, k, count, miptex;
2366         int structsize = 40;
2367
2368         if (sb->cursize % structsize)
2369                 Host_Error("Mod_Q1BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
2370         count = sb->cursize / structsize;
2371         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
2372
2373         loadmodel->brushq1.texinfo = out;
2374         loadmodel->brushq1.numtexinfo = count;
2375
2376         for (i = 0;i < count;i++, out++)
2377         {
2378                 for (k = 0;k < 2;k++)
2379                         for (j = 0;j < 4;j++)
2380                                 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
2381
2382                 miptex = MSG_ReadLittleLong(sb);
2383                 out->q1flags = MSG_ReadLittleLong(sb);
2384
2385                 if (out->q1flags & TEX_SPECIAL)
2386                 {
2387                         // if texture chosen is NULL or the shader needs a lightmap,
2388                         // force to notexture water shader
2389                         out->textureindex = loadmodel->num_textures - 1;
2390                 }
2391                 else
2392                 {
2393                         // if texture chosen is NULL, force to notexture
2394                         out->textureindex = loadmodel->num_textures - 2;
2395                 }
2396                 // see if the specified miptex is valid and try to use it instead
2397                 if (loadmodel->data_textures)
2398                 {
2399                         if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
2400                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
2401                         else
2402                                 out->textureindex = miptex;
2403                 }
2404         }
2405 }
2406
2407 #if 0
2408 void BoundPoly(int numverts, float *verts, vec3_t mins, vec3_t maxs)
2409 {
2410         int             i, j;
2411         float   *v;
2412
2413         mins[0] = mins[1] = mins[2] = 9999;
2414         maxs[0] = maxs[1] = maxs[2] = -9999;
2415         v = verts;
2416         for (i = 0;i < numverts;i++)
2417         {
2418                 for (j = 0;j < 3;j++, v++)
2419                 {
2420                         if (*v < mins[j])
2421                                 mins[j] = *v;
2422                         if (*v > maxs[j])
2423                                 maxs[j] = *v;
2424                 }
2425         }
2426 }
2427
2428 #define MAX_SUBDIVPOLYTRIANGLES 4096
2429 #define MAX_SUBDIVPOLYVERTS(MAX_SUBDIVPOLYTRIANGLES * 3)
2430
2431 static int subdivpolyverts, subdivpolytriangles;
2432 static int subdivpolyindex[MAX_SUBDIVPOLYTRIANGLES][3];
2433 static float subdivpolyvert[MAX_SUBDIVPOLYVERTS][3];
2434
2435 static int subdivpolylookupvert(vec3_t v)
2436 {
2437         int i;
2438         for (i = 0;i < subdivpolyverts;i++)
2439                 if (subdivpolyvert[i][0] == v[0]
2440                  && subdivpolyvert[i][1] == v[1]
2441                  && subdivpolyvert[i][2] == v[2])
2442                         return i;
2443         if (subdivpolyverts >= MAX_SUBDIVPOLYVERTS)
2444                 Host_Error("SubDividePolygon: ran out of vertices in buffer, please increase your r_subdivide_size");
2445         VectorCopy(v, subdivpolyvert[subdivpolyverts]);
2446         return subdivpolyverts++;
2447 }
2448
2449 static void SubdividePolygon(int numverts, float *verts)
2450 {
2451         int             i, i1, i2, i3, f, b, c, p;
2452         vec3_t  mins, maxs, front[256], back[256];
2453         float   m, *pv, *cv, dist[256], frac;
2454
2455         if (numverts > 250)
2456                 Host_Error("SubdividePolygon: ran out of verts in buffer");
2457
2458         BoundPoly(numverts, verts, mins, maxs);
2459
2460         for (i = 0;i < 3;i++)
2461         {
2462                 m = (mins[i] + maxs[i]) * 0.5;
2463                 m = r_subdivide_size.value * floor(m/r_subdivide_size.value + 0.5);
2464                 if (maxs[i] - m < 8)
2465                         continue;
2466                 if (m - mins[i] < 8)
2467                         continue;
2468
2469                 // cut it
2470                 for (cv = verts, c = 0;c < numverts;c++, cv += 3)
2471                         dist[c] = cv[i] - m;
2472
2473                 f = b = 0;
2474                 for (p = numverts - 1, c = 0, pv = verts + p * 3, cv = verts;c < numverts;p = c, c++, pv = cv, cv += 3)
2475                 {
2476                         if (dist[p] >= 0)
2477                         {
2478                                 VectorCopy(pv, front[f]);
2479                                 f++;
2480                         }
2481                         if (dist[p] <= 0)
2482                         {
2483                                 VectorCopy(pv, back[b]);
2484                                 b++;
2485                         }
2486                         if (dist[p] == 0 || dist[c] == 0)
2487                                 continue;
2488                         if ((dist[p] > 0) != (dist[c] > 0) )
2489                         {
2490                                 // clip point
2491                                 frac = dist[p] / (dist[p] - dist[c]);
2492                                 front[f][0] = back[b][0] = pv[0] + frac * (cv[0] - pv[0]);
2493                                 front[f][1] = back[b][1] = pv[1] + frac * (cv[1] - pv[1]);
2494                                 front[f][2] = back[b][2] = pv[2] + frac * (cv[2] - pv[2]);
2495                                 f++;
2496                                 b++;
2497                         }
2498                 }
2499
2500                 SubdividePolygon(f, front[0]);
2501                 SubdividePolygon(b, back[0]);
2502                 return;
2503         }
2504
2505         i1 = subdivpolylookupvert(verts);
2506         i2 = subdivpolylookupvert(verts + 3);
2507         for (i = 2;i < numverts;i++)
2508         {
2509                 if (subdivpolytriangles >= MAX_SUBDIVPOLYTRIANGLES)
2510                 {
2511                         Con_Print("SubdividePolygon: ran out of triangles in buffer, please increase your r_subdivide_size\n");
2512                         return;
2513                 }
2514
2515                 i3 = subdivpolylookupvert(verts + i * 3);
2516                 subdivpolyindex[subdivpolytriangles][0] = i1;
2517                 subdivpolyindex[subdivpolytriangles][1] = i2;
2518                 subdivpolyindex[subdivpolytriangles][2] = i3;
2519                 i2 = i3;
2520                 subdivpolytriangles++;
2521         }
2522 }
2523
2524 //Breaks a polygon up along axial 64 unit
2525 //boundaries so that turbulent and sky warps
2526 //can be done reasonably.
2527 static void Mod_Q1BSP_GenerateWarpMesh(msurface_t *surface)
2528 {
2529         int i, j;
2530         surfvertex_t *v;
2531         surfmesh_t *mesh;
2532
2533         subdivpolytriangles = 0;
2534         subdivpolyverts = 0;
2535         SubdividePolygon(surface->num_vertices, (surface->mesh->data_vertex3f + 3 * surface->num_firstvertex));
2536         if (subdivpolytriangles < 1)
2537                 Host_Error("Mod_Q1BSP_GenerateWarpMesh: no triangles?");
2538
2539         surface->mesh = mesh = Mem_Alloc(loadmodel->mempool, sizeof(surfmesh_t) + subdivpolytriangles * sizeof(int[3]) + subdivpolyverts * sizeof(surfvertex_t));
2540         mesh->num_vertices = subdivpolyverts;
2541         mesh->num_triangles = subdivpolytriangles;
2542         mesh->vertex = (surfvertex_t *)(mesh + 1);
2543         mesh->index = (int *)(mesh->vertex + mesh->num_vertices);
2544         memset(mesh->vertex, 0, mesh->num_vertices * sizeof(surfvertex_t));
2545
2546         for (i = 0;i < mesh->num_triangles;i++)
2547                 for (j = 0;j < 3;j++)
2548                         mesh->index[i*3+j] = subdivpolyindex[i][j];
2549
2550         for (i = 0, v = mesh->vertex;i < subdivpolyverts;i++, v++)
2551         {
2552                 VectorCopy(subdivpolyvert[i], v->v);
2553                 v->st[0] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[0]);
2554                 v->st[1] = DotProduct(v->v, surface->lightmapinfo->texinfo->vecs[1]);
2555         }
2556 }
2557 #endif
2558
2559 extern cvar_t gl_max_lightmapsize;
2560 static void Mod_Q1BSP_LoadFaces(sizebuf_t *sb)
2561 {
2562         msurface_t *surface;
2563         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
2564         float texmins[2], texmaxs[2], val;
2565         rtexture_t *lightmaptexture, *deluxemaptexture;
2566         char vabuf[1024];
2567         int structsize = loadmodel->brush.isbsp2 ? 28 : 20;
2568
2569         if (sb->cursize % structsize)
2570                 Host_Error("Mod_Q1BSP_LoadFaces: funny lump size in %s",loadmodel->name);
2571         count = sb->cursize / structsize;
2572         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
2573         loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
2574
2575         loadmodel->num_surfaces = count;
2576
2577         loadmodel->brushq1.firstrender = true;
2578         loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
2579
2580         totalverts = 0;
2581         totaltris = 0;
2582         for (surfacenum = 0;surfacenum < count;surfacenum++)
2583         {
2584                 if (loadmodel->brush.isbsp2)
2585                         numedges = BuffLittleLong(sb->data + structsize * surfacenum + 12);
2586                 else
2587                         numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
2588                 totalverts += numedges;
2589                 totaltris += numedges - 2;
2590         }
2591
2592         Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false);
2593
2594         lightmaptexture = NULL;
2595         deluxemaptexture = r_texture_blanknormalmap;
2596         lightmapnumber = 0;
2597         lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
2598         totallightmapsamples = 0;
2599
2600         totalverts = 0;
2601         totaltris = 0;
2602         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2603         {
2604                 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
2605                 // the struct on disk is the same in BSP29 (Q1), BSP30 (HL1), and IBSP38 (Q2)
2606                 planenum = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2607                 /*side = */loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2608                 firstedge = MSG_ReadLittleLong(sb);
2609                 numedges = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2610                 texinfoindex = loadmodel->brush.isbsp2 ? MSG_ReadLittleLong(sb) : (unsigned short)MSG_ReadLittleShort(sb);
2611                 for (i = 0;i < MAXLIGHTMAPS;i++)
2612                         surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
2613                 lightmapoffset = MSG_ReadLittleLong(sb);
2614
2615                 // FIXME: validate edges, texinfo, etc?
2616                 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)
2617                         Host_Error("Mod_Q1BSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
2618                 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
2619                         Host_Error("Mod_Q1BSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
2620                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
2621                         Host_Error("Mod_Q1BSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
2622
2623                 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
2624                 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
2625
2626                 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
2627                 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
2628                         lightmapoffset = -1;
2629
2630                 //surface->flags = surface->texture->flags;
2631                 //if (LittleShort(in->side))
2632                 //      surface->flags |= SURF_PLANEBACK;
2633                 //surface->plane = loadmodel->brush.data_planes + planenum;
2634
2635                 surface->num_firstvertex = totalverts;
2636                 surface->num_vertices = numedges;
2637                 surface->num_firsttriangle = totaltris;
2638                 surface->num_triangles = numedges - 2;
2639                 totalverts += numedges;
2640                 totaltris += numedges - 2;
2641
2642                 // convert edges back to a normal polygon
2643                 for (i = 0;i < surface->num_vertices;i++)
2644                 {
2645                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
2646                         float s, t;
2647                         // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
2648                         if (lindex >= 0)
2649                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2650                         else
2651                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
2652                         s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2653                         t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2654                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
2655                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
2656                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
2657                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
2658                         (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
2659                 }
2660
2661                 for (i = 0;i < surface->num_triangles;i++)
2662                 {
2663                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
2664                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
2665                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
2666                 }
2667
2668                 // compile additional data about the surface geometry
2669                 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);
2670                 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);
2671                 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
2672
2673                 // generate surface extents information
2674                 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
2675                 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
2676                 for (i = 1;i < surface->num_vertices;i++)
2677                 {
2678                         for (j = 0;j < 2;j++)
2679                         {
2680                                 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
2681                                 texmins[j] = min(texmins[j], val);
2682                                 texmaxs[j] = max(texmaxs[j], val);
2683                         }
2684                 }
2685                 for (i = 0;i < 2;i++)
2686                 {
2687                         surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
2688                         surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
2689                 }
2690
2691                 smax = surface->lightmapinfo->extents[0] >> 4;
2692                 tmax = surface->lightmapinfo->extents[1] >> 4;
2693                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2694                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2695
2696                 // lighting info
2697                 surface->lightmaptexture = NULL;
2698                 surface->deluxemaptexture = r_texture_blanknormalmap;
2699                 if (lightmapoffset == -1)
2700                 {
2701                         surface->lightmapinfo->samples = NULL;
2702 #if 1
2703                         // give non-lightmapped water a 1x white lightmap
2704                         if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
2705                         {
2706                                 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
2707                                 surface->lightmapinfo->styles[0] = 0;
2708                                 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
2709                         }
2710 #endif
2711                 }
2712                 else if (loadmodel->brush.ishlbsp || loadmodel->brush.isq2bsp) // LadyHavoc: HalfLife map (bsp version 30)
2713                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
2714                 else // LadyHavoc: white lighting (bsp version 29)
2715                 {
2716                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + (lightmapoffset * 3);
2717                         if (loadmodel->brushq1.nmaplightdata)
2718                                 surface->lightmapinfo->nmapsamples = loadmodel->brushq1.nmaplightdata + (lightmapoffset * 3);
2719                 }
2720
2721                 // check if we should apply a lightmap to this
2722                 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
2723                 {
2724                         if (ssize > 256 || tsize > 256)
2725                                 Host_Error("Bad surface extents");
2726
2727                         if (lightmapsize < ssize)
2728                                 lightmapsize = ssize;
2729                         if (lightmapsize < tsize)
2730                                 lightmapsize = tsize;
2731
2732                         totallightmapsamples += ssize*tsize;
2733
2734                         // force lightmap upload on first time seeing the surface
2735                         //
2736                         // additionally this is used by the later code to see if a
2737                         // lightmap is needed on this surface (rather than duplicating the
2738                         // logic above)
2739                         loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
2740                         loadmodel->lit = true;
2741                 }
2742         }
2743
2744         // small maps (such as ammo boxes especially) don't need big lightmap
2745         // textures, so this code tries to guess a good size based on
2746         // totallightmapsamples (size of the lightmaps lump basically), as well as
2747         // trying to max out the size if there is a lot of lightmap data to store
2748         // additionally, never choose a lightmapsize that is smaller than the
2749         // largest surface encountered (as it would fail)
2750         i = lightmapsize;
2751         for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
2752                 ;
2753
2754         // now that we've decided the lightmap texture size, we can do the rest
2755         if (cls.state != ca_dedicated)
2756         {
2757                 int stainmapsize = 0;
2758                 mod_alloclightmap_state_t allocState;
2759
2760                 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
2761                 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2762                 {
2763                         int iu, iv, lightmapx = 0, lightmapy = 0;
2764                         float u, v, ubase, vbase, uscale, vscale;
2765
2766                         if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2767                                 continue;
2768
2769                         smax = surface->lightmapinfo->extents[0] >> 4;
2770                         tmax = surface->lightmapinfo->extents[1] >> 4;
2771                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2772                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2773                         stainmapsize += ssize * tsize * 3;
2774
2775                         if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
2776                         {
2777                                 // allocate a texture pool if we need it
2778                                 if (loadmodel->texturepool == NULL)
2779                                         loadmodel->texturepool = R_AllocTexturePool();
2780                                 // could not find room, make a new lightmap
2781                                 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
2782                                 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
2783                                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
2784                                 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);
2785                                 if (loadmodel->brushq1.nmaplightdata)
2786                                         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);
2787                                 lightmapnumber++;
2788                                 Mod_AllocLightmap_Reset(&allocState);
2789                                 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
2790                         }
2791                         surface->lightmaptexture = lightmaptexture;
2792                         surface->deluxemaptexture = deluxemaptexture;
2793                         surface->lightmapinfo->lightmaporigin[0] = lightmapx;
2794                         surface->lightmapinfo->lightmaporigin[1] = lightmapy;
2795
2796                         uscale = 1.0f / (float)lightmapsize;
2797                         vscale = 1.0f / (float)lightmapsize;
2798                         ubase = lightmapx * uscale;
2799                         vbase = lightmapy * vscale;
2800
2801                         for (i = 0;i < surface->num_vertices;i++)
2802                         {
2803                                 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);
2804                                 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);
2805                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
2806                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
2807                                 // LadyHavoc: calc lightmap data offset for vertex lighting to use
2808                                 iu = (int) u;
2809                                 iv = (int) v;
2810                                 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
2811                         }
2812                 }
2813
2814                 if (cl_stainmaps.integer)
2815                 {
2816                         // allocate stainmaps for permanent marks on walls and clear white
2817                         unsigned char *stainsamples = NULL;
2818                         stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
2819                         memset(stainsamples, 255, stainmapsize);
2820                         // assign pointers
2821                         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
2822                         {
2823                                 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
2824                                         continue;
2825                                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
2826                                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
2827                                 surface->lightmapinfo->stainsamples = stainsamples;
2828                                 stainsamples += ssize * tsize * 3;
2829                         }
2830                 }
2831         }
2832
2833         // generate ushort elements array if possible
2834         if (loadmodel->surfmesh.data_element3s)
2835                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
2836                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
2837 }
2838
2839 static void Mod_BSP_LoadNodes_RecursiveSetParent(mnode_t *node, mnode_t *parent)
2840 {
2841         //if (node->parent)
2842         //      Host_Error("Mod_BSP_LoadNodes_RecursiveSetParent: runaway recursion");
2843         node->parent = parent;
2844         if (node->plane)
2845         {
2846                 // this is a node, recurse to children
2847                 Mod_BSP_LoadNodes_RecursiveSetParent(node->children[0], node);
2848                 Mod_BSP_LoadNodes_RecursiveSetParent(node->children[1], node);
2849                 // combine supercontents of children
2850                 node->combinedsupercontents = node->children[0]->combinedsupercontents | node->children[1]->combinedsupercontents;
2851         }
2852         else
2853         {
2854                 int j;
2855                 mleaf_t *leaf = (mleaf_t *)node;
2856                 // if this is a leaf, calculate supercontents mask from all collidable
2857                 // primitives in the leaf (brushes and collision surfaces)
2858                 // also flag if the leaf contains any collision surfaces
2859                 leaf->combinedsupercontents = 0;
2860                 // combine the supercontents values of all brushes in this leaf
2861                 for (j = 0;j < leaf->numleafbrushes;j++)
2862                         leaf->combinedsupercontents |= loadmodel->brush.data_brushes[leaf->firstleafbrush[j]].texture->supercontents;
2863                 // check if this leaf contains any collision surfaces (q3 patches)
2864                 for (j = 0;j < leaf->numleafsurfaces;j++)
2865                 {
2866                         msurface_t *surface = loadmodel->data_surfaces + leaf->firstleafsurface[j];
2867                         if (surface->num_collisiontriangles)
2868                         {
2869                                 leaf->containscollisionsurfaces = true;
2870                                 leaf->combinedsupercontents |= surface->texture->supercontents;
2871                         }
2872                 }
2873         }
2874 }
2875
2876 static void Mod_Q1BSP_LoadNodes(sizebuf_t *sb)
2877 {
2878         int                     i, j, count, p, child[2];
2879         mnode_t         *out;
2880         int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 24);
2881
2882         if (sb->cursize % structsize)
2883                 Host_Error("Mod_Q1BSP_LoadNodes: funny lump size in %s",loadmodel->name);
2884         count = sb->cursize / structsize;
2885         if (count == 0)
2886                 Host_Error("Mod_Q1BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
2887         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2888
2889         loadmodel->brush.data_nodes = out;
2890         loadmodel->brush.num_nodes = count;
2891
2892         for ( i=0 ; i<count ; i++, out++)
2893         {
2894                 p = MSG_ReadLittleLong(sb);
2895                 out->plane = loadmodel->brush.data_planes + p;
2896
2897                 if (loadmodel->brush.isbsp2rmqe)
2898                 {
2899                         child[0] = MSG_ReadLittleLong(sb);
2900                         child[1] = MSG_ReadLittleLong(sb);
2901                         out->mins[0] = MSG_ReadLittleShort(sb);
2902                         out->mins[1] = MSG_ReadLittleShort(sb);
2903                         out->mins[2] = MSG_ReadLittleShort(sb);
2904                         out->maxs[0] = MSG_ReadLittleShort(sb);
2905                         out->maxs[1] = MSG_ReadLittleShort(sb);
2906                         out->maxs[2] = MSG_ReadLittleShort(sb);
2907                         out->firstsurface = MSG_ReadLittleLong(sb);
2908                         out->numsurfaces = MSG_ReadLittleLong(sb);
2909                 }
2910                 else if (loadmodel->brush.isbsp2)
2911                 {
2912                         child[0] = MSG_ReadLittleLong(sb);
2913                         child[1] = MSG_ReadLittleLong(sb);
2914                         out->mins[0] = MSG_ReadLittleFloat(sb);
2915                         out->mins[1] = MSG_ReadLittleFloat(sb);
2916                         out->mins[2] = MSG_ReadLittleFloat(sb);
2917                         out->maxs[0] = MSG_ReadLittleFloat(sb);
2918                         out->maxs[1] = MSG_ReadLittleFloat(sb);
2919                         out->maxs[2] = MSG_ReadLittleFloat(sb);
2920                         out->firstsurface = MSG_ReadLittleLong(sb);
2921                         out->numsurfaces = MSG_ReadLittleLong(sb);
2922                 }
2923                 else
2924                 {
2925                         child[0] = (unsigned short)MSG_ReadLittleShort(sb);
2926                         child[1] = (unsigned short)MSG_ReadLittleShort(sb);
2927                         if (child[0] >= count)
2928                                 child[0] -= 65536;
2929                         if (child[1] >= count)
2930                                 child[1] -= 65536;
2931
2932                         out->mins[0] = MSG_ReadLittleShort(sb);
2933                         out->mins[1] = MSG_ReadLittleShort(sb);
2934                         out->mins[2] = MSG_ReadLittleShort(sb);
2935                         out->maxs[0] = MSG_ReadLittleShort(sb);
2936                         out->maxs[1] = MSG_ReadLittleShort(sb);
2937                         out->maxs[2] = MSG_ReadLittleShort(sb);
2938
2939                         out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
2940                         out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
2941                 }
2942
2943                 for (j=0 ; j<2 ; j++)
2944                 {
2945                         // LadyHavoc: this code supports broken bsp files produced by
2946                         // arguire qbsp which can produce more than 32768 nodes, any value
2947                         // below count is assumed to be a node number, any other value is
2948                         // assumed to be a leaf number
2949                         p = child[j];
2950                         if (p >= 0)
2951                         {
2952                                 if (p < loadmodel->brush.num_nodes)
2953                                         out->children[j] = loadmodel->brush.data_nodes + p;
2954                                 else
2955                                 {
2956                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
2957                                         // map it to the solid leaf
2958                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2959                                 }
2960                         }
2961                         else
2962                         {
2963                                 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
2964                                 p = -(p+1);
2965                                 if (p < loadmodel->brush.num_leafs)
2966                                         out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
2967                                 else
2968                                 {
2969                                         Con_Printf("Mod_Q1BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
2970                                         // map it to the solid leaf
2971                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
2972                                 }
2973                         }
2974                 }
2975         }
2976
2977         Mod_BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);        // sets nodes and leafs
2978 }
2979
2980 static void Mod_Q1BSP_LoadLeafs(sizebuf_t *sb)
2981 {
2982         mleaf_t *out;
2983         int i, j, count, p, firstmarksurface, nummarksurfaces;
2984         int structsize = loadmodel->brush.isbsp2rmqe ? 32 : (loadmodel->brush.isbsp2 ? 44 : 28);
2985
2986         if (sb->cursize % structsize)
2987                 Host_Error("Mod_Q1BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
2988         count = sb->cursize / structsize;
2989         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
2990
2991         loadmodel->brush.data_leafs = out;
2992         loadmodel->brush.num_leafs = count;
2993         // get visleafs from the submodel data
2994         loadmodel->brush.num_pvsclusters = loadmodel->brushq1.submodels[0].visleafs;
2995         loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters+7)>>3;
2996         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2997         memset(loadmodel->brush.data_pvsclusters, 0xFF, loadmodel->brush.num_pvsclusters * loadmodel->brush.num_pvsclusterbytes);
2998
2999         // FIXME: this function could really benefit from some error checking
3000         for ( i=0 ; i<count ; i++, out++)
3001         {
3002                 out->contents = MSG_ReadLittleLong(sb);
3003
3004                 out->clusterindex = i - 1;
3005                 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
3006                         out->clusterindex = -1;
3007
3008                 p = MSG_ReadLittleLong(sb);
3009                 // ignore visofs errors on leaf 0 (solid)
3010                 if (p >= 0 && out->clusterindex >= 0)
3011                 {
3012                         if (p >= loadmodel->brushq1.num_compressedpvs)
3013                                 Con_Print("Mod_Q1BSP_LoadLeafs: invalid visofs\n");
3014                         else
3015                                 Mod_BSP_DecompressVis(loadmodel->brushq1.data_compressedpvs + p, loadmodel->brushq1.data_compressedpvs + loadmodel->brushq1.num_compressedpvs, loadmodel->brush.data_pvsclusters + out->clusterindex * loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.data_pvsclusters + (out->clusterindex + 1) * loadmodel->brush.num_pvsclusterbytes);
3016                 }
3017
3018                 if (loadmodel->brush.isbsp2rmqe)
3019                 {
3020                         out->mins[0] = MSG_ReadLittleShort(sb);
3021                         out->mins[1] = MSG_ReadLittleShort(sb);
3022                         out->mins[2] = MSG_ReadLittleShort(sb);
3023                         out->maxs[0] = MSG_ReadLittleShort(sb);
3024                         out->maxs[1] = MSG_ReadLittleShort(sb);
3025                         out->maxs[2] = MSG_ReadLittleShort(sb);
3026         
3027                         firstmarksurface = MSG_ReadLittleLong(sb);
3028                         nummarksurfaces = MSG_ReadLittleLong(sb);
3029                 }
3030                 else if (loadmodel->brush.isbsp2)
3031                 {
3032                         out->mins[0] = MSG_ReadLittleFloat(sb);
3033                         out->mins[1] = MSG_ReadLittleFloat(sb);
3034                         out->mins[2] = MSG_ReadLittleFloat(sb);
3035                         out->maxs[0] = MSG_ReadLittleFloat(sb);
3036                         out->maxs[1] = MSG_ReadLittleFloat(sb);
3037                         out->maxs[2] = MSG_ReadLittleFloat(sb);
3038         
3039                         firstmarksurface = MSG_ReadLittleLong(sb);
3040                         nummarksurfaces = MSG_ReadLittleLong(sb);
3041                 }
3042                 else
3043                 {
3044                         out->mins[0] = MSG_ReadLittleShort(sb);
3045                         out->mins[1] = MSG_ReadLittleShort(sb);
3046                         out->mins[2] = MSG_ReadLittleShort(sb);
3047                         out->maxs[0] = MSG_ReadLittleShort(sb);
3048                         out->maxs[1] = MSG_ReadLittleShort(sb);
3049                         out->maxs[2] = MSG_ReadLittleShort(sb);
3050         
3051                         firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
3052                         nummarksurfaces  = (unsigned short)MSG_ReadLittleShort(sb);
3053                 }
3054
3055                 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
3056                 {
3057                         out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
3058                         out->numleafsurfaces = nummarksurfaces;
3059                 }
3060                 else
3061                 {
3062                         Con_Printf("Mod_Q1BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
3063                         out->firstleafsurface = NULL;
3064                         out->numleafsurfaces = 0;
3065                 }
3066
3067                 for (j = 0;j < 4;j++)
3068                         out->ambient_sound_level[j] = MSG_ReadByte(sb);
3069         }
3070 }
3071
3072 static qbool Mod_Q1BSP_CheckWaterAlphaSupport(void)
3073 {
3074         int i, j;
3075         mleaf_t *leaf;
3076         const unsigned char *pvs;
3077         // if there's no vis data, assume supported (because everything is visible all the time)
3078         if (!loadmodel->brush.data_pvsclusters)
3079                 return true;
3080         // check all liquid leafs to see if they can see into empty leafs, if any
3081         // can we can assume this map supports r_wateralpha
3082         for (i = 0, leaf = loadmodel->brush.data_leafs;i < loadmodel->brush.num_leafs;i++, leaf++)
3083         {
3084                 if ((leaf->contents == CONTENTS_WATER || leaf->contents == CONTENTS_SLIME) && leaf->clusterindex >= 0)
3085                 {
3086                         pvs = loadmodel->brush.data_pvsclusters + leaf->clusterindex * loadmodel->brush.num_pvsclusterbytes;
3087                         for (j = 0;j < loadmodel->brush.num_leafs;j++)
3088                                 if (CHECKPVSBIT(pvs, loadmodel->brush.data_leafs[j].clusterindex) && loadmodel->brush.data_leafs[j].contents == CONTENTS_EMPTY)
3089                                         return true;
3090                 }
3091         }
3092         return false;
3093 }
3094
3095 static void Mod_Q1BSP_LoadClipnodes(sizebuf_t *sb, hullinfo_t *hullinfo)
3096 {
3097         mclipnode_t *out;
3098         int                     i, count;
3099         hull_t          *hull;
3100         int structsize = loadmodel->brush.isbsp2 ? 12 : 8;
3101
3102         if (sb->cursize % structsize)
3103                 Host_Error("Mod_Q1BSP_LoadClipnodes: funny lump size in %s",loadmodel->name);
3104         count = sb->cursize / structsize;
3105         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
3106
3107         loadmodel->brushq1.clipnodes = out;
3108         loadmodel->brushq1.numclipnodes = count;
3109
3110         for (i = 1; i < MAX_MAP_HULLS; i++)
3111         {
3112                 hull = &loadmodel->brushq1.hulls[i];
3113                 hull->clipnodes = out;
3114                 hull->firstclipnode = 0;
3115                 hull->lastclipnode = count-1;
3116                 hull->planes = loadmodel->brush.data_planes;
3117                 hull->clip_mins[0] = hullinfo->hullsizes[i][0][0];
3118                 hull->clip_mins[1] = hullinfo->hullsizes[i][0][1];
3119                 hull->clip_mins[2] = hullinfo->hullsizes[i][0][2];
3120                 hull->clip_maxs[0] = hullinfo->hullsizes[i][1][0];
3121                 hull->clip_maxs[1] = hullinfo->hullsizes[i][1][1];
3122                 hull->clip_maxs[2] = hullinfo->hullsizes[i][1][2];
3123                 VectorSubtract(hull->clip_maxs, hull->clip_mins, hull->clip_size);
3124         }
3125
3126         for (i=0 ; i<count ; i++, out++)
3127         {
3128                 out->planenum = MSG_ReadLittleLong(sb);
3129                 if (out->planenum < 0 || out->planenum >= loadmodel->brush.num_planes)
3130                         Host_Error("%s: Corrupt clipping hull(out of range planenum)", loadmodel->name);
3131                 if (loadmodel->brush.isbsp2)
3132                 {
3133                         out->children[0] = MSG_ReadLittleLong(sb);
3134                         out->children[1] = MSG_ReadLittleLong(sb);
3135                         if (out->children[0] >= count)
3136                                 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3137                         if (out->children[1] >= count)
3138                                 Host_Error("%s: Corrupt clipping hull (invalid child index)", loadmodel->name);
3139                 }
3140                 else
3141                 {
3142                         // LadyHavoc: this code supports arguire qbsp's broken clipnodes indices (more than 32768 clipnodes), values above count are assumed to be contents values
3143                         out->children[0] = (unsigned short)MSG_ReadLittleShort(sb);
3144                         out->children[1] = (unsigned short)MSG_ReadLittleShort(sb);
3145                         if (out->children[0] >= count)
3146                                 out->children[0] -= 65536;
3147                         if (out->children[1] >= count)
3148                                 out->children[1] -= 65536;
3149                 }
3150         }
3151 }
3152
3153 //Duplicate the drawing hull structure as a clipping hull
3154 static void Mod_Q1BSP_MakeHull0(void)
3155 {
3156         mnode_t         *in;
3157         mclipnode_t *out;
3158         int                     i;
3159         hull_t          *hull;
3160
3161         hull = &loadmodel->brushq1.hulls[0];
3162
3163         in = loadmodel->brush.data_nodes;
3164         out = (mclipnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_nodes * sizeof(*out));
3165
3166         hull->clipnodes = out;
3167         hull->firstclipnode = 0;
3168         hull->lastclipnode = loadmodel->brush.num_nodes - 1;
3169         hull->planes = loadmodel->brush.data_planes;
3170
3171         for (i = 0;i < loadmodel->brush.num_nodes;i++, out++, in++)
3172         {
3173                 out->planenum = in->plane - loadmodel->brush.data_planes;
3174                 out->children[0] = in->children[0]->plane ? in->children[0] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[0])->contents;
3175                 out->children[1] = in->children[1]->plane ? in->children[1] - loadmodel->brush.data_nodes : ((mleaf_t *)in->children[1])->contents;
3176         }
3177 }
3178
3179 static void Mod_Q1BSP_LoadLeaffaces(sizebuf_t *sb)
3180 {
3181         int i, j;
3182         int structsize = loadmodel->brush.isbsp2 ? 4 : 2;
3183
3184         if (sb->cursize % structsize)
3185                 Host_Error("Mod_Q1BSP_LoadLeaffaces: funny lump size in %s",loadmodel->name);
3186         loadmodel->brush.num_leafsurfaces = sb->cursize / structsize;
3187         loadmodel->brush.data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafsurfaces * sizeof(int));
3188
3189         if (loadmodel->brush.isbsp2)
3190         {
3191                 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3192                 {
3193                         j = MSG_ReadLittleLong(sb);
3194                         if (j < 0 || j >= loadmodel->num_surfaces)
3195                                 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3196                         loadmodel->brush.data_leafsurfaces[i] = j;
3197                 }
3198         }
3199         else
3200         {
3201                 for (i = 0;i < loadmodel->brush.num_leafsurfaces;i++)
3202                 {
3203                         j = (unsigned short) MSG_ReadLittleShort(sb);
3204                         if (j >= loadmodel->num_surfaces)
3205                                 Host_Error("Mod_Q1BSP_LoadLeaffaces: bad surface number");
3206                         loadmodel->brush.data_leafsurfaces[i] = j;
3207                 }
3208         }
3209 }
3210
3211 static void Mod_Q1BSP_LoadSurfedges(sizebuf_t *sb)
3212 {
3213         int             i;
3214         int structsize = 4;
3215
3216         if (sb->cursize % structsize)
3217                 Host_Error("Mod_Q1BSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
3218         loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
3219         loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
3220
3221         for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
3222                 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
3223 }
3224
3225
3226 static void Mod_Q1BSP_LoadPlanes(sizebuf_t *sb)
3227 {
3228         int                     i;
3229         mplane_t        *out;
3230         int structsize = 20;
3231
3232         if (sb->cursize % structsize)
3233                 Host_Error("Mod_Q1BSP_LoadPlanes: funny lump size in %s", loadmodel->name);
3234         loadmodel->brush.num_planes = sb->cursize / structsize;
3235         loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
3236
3237         for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
3238         {
3239                 out->normal[0] = MSG_ReadLittleFloat(sb);
3240                 out->normal[1] = MSG_ReadLittleFloat(sb);
3241                 out->normal[2] = MSG_ReadLittleFloat(sb);
3242                 out->dist = MSG_ReadLittleFloat(sb);
3243                 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
3244                 PlaneClassify(out);
3245         }
3246 }
3247
3248 // fixes up sky surfaces that have SKY contents behind them, so that they do not cast shadows (e1m5 logo shadow trick).
3249 static void Mod_Q1BSP_AssignNoShadowSkySurfaces(model_t *mod)
3250 {
3251         int surfaceindex;
3252         msurface_t *surface;
3253         vec3_t center;
3254         int contents;
3255         for (surfaceindex = mod->submodelsurfaces_start; surfaceindex < mod->submodelsurfaces_end;surfaceindex++)
3256         {
3257                 surface = mod->data_surfaces + surfaceindex;
3258                 if (surface->texture->basematerialflags & MATERIALFLAG_SKY)
3259                 {
3260                         // check if the point behind the surface polygon is SOLID or SKY contents
3261                         VectorMAMAM(0.5f, surface->mins, 0.5f, surface->maxs, -0.25f, mod->surfmesh.data_normal3f + 3*surface->num_firstvertex, center);
3262                         contents = Mod_Q1BSP_PointSuperContents(mod, 0, center);
3263                         if (!(contents & SUPERCONTENTS_SOLID))
3264                                 surface->texture = surface->texture->skynoshadowtexture;
3265                 }
3266         }
3267 }
3268
3269 static void Mod_Q1BSP_LoadMapBrushes(void)
3270 {
3271 #if 0
3272 // unfinished
3273         int submodel, numbrushes;
3274         qbool firstbrush;
3275         char *text, *maptext;
3276         char mapfilename[MAX_QPATH];
3277         FS_StripExtension (loadmodel->name, mapfilename, sizeof (mapfilename));
3278         strlcat (mapfilename, ".map", sizeof (mapfilename));
3279         maptext = (unsigned char*) FS_LoadFile(mapfilename, tempmempool, false, NULL);
3280         if (!maptext)
3281                 return;
3282         text = maptext;
3283         if (!COM_ParseToken_Simple(&data, false, false, true))
3284                 return; // error
3285         submodel = 0;
3286         for (;;)
3287         {
3288                 if (!COM_ParseToken_Simple(&data, false, false, true))
3289                         break;
3290                 if (com_token[0] != '{')
3291                         return; // error
3292                 // entity
3293                 firstbrush = true;
3294                 numbrushes = 0;
3295                 maxbrushes = 256;
3296                 brushes = Mem_Alloc(loadmodel->mempool, maxbrushes * sizeof(mbrush_t));
3297                 for (;;)
3298                 {
3299                         if (!COM_ParseToken_Simple(&data, false, false, true))
3300                                 return; // error
3301                         if (com_token[0] == '}')
3302                                 break; // end of entity
3303                         if (com_token[0] == '{')
3304                         {
3305                                 // brush
3306                                 if (firstbrush)
3307                                 {
3308                                         if (submodel)
3309                                         {
3310                                                 if (submodel > loadmodel->brush.numsubmodels)
3311                                                 {
3312                                                         Con_Printf("Mod_Q1BSP_LoadMapBrushes: .map has more submodels than .bsp!\n");
3313                                                         model = NULL;
3314                                                 }
3315                                                 else
3316                                                         model = loadmodel->brush.submodels[submodel];
3317                                         }
3318                                         else
3319                                                 model = loadmodel;
3320                                 }
3321                                 for (;;)
3322                                 {
3323                                         if (!COM_ParseToken_Simple(&data, false, false, true))
3324                                                 return; // error
3325                                         if (com_token[0] == '}')
3326                                                 break; // end of brush
3327                                         // each brush face should be this format:
3328                                         // ( x y z ) ( x y z ) ( x y z ) texture scroll_s scroll_t rotateangle scale_s scale_t
3329                                         // FIXME: support hl .map format
3330                                         for (pointnum = 0;pointnum < 3;pointnum++)
3331                                         {
3332                                                 COM_ParseToken_Simple(&data, false, false, true);
3333                                                 for (componentnum = 0;componentnum < 3;componentnum++)
3334                                                 {
3335                                                         COM_ParseToken_Simple(&data, false, false, true);
3336                                                         point[pointnum][componentnum] = atof(com_token);
3337                                                 }
3338                                                 COM_ParseToken_Simple(&data, false, false, true);
3339                                         }
3340                                         COM_ParseToken_Simple(&data, false, false, true);
3341                                         strlcpy(facetexture, com_token, sizeof(facetexture));
3342                                         COM_ParseToken_Simple(&data, false, false, true);
3343                                         //scroll_s = atof(com_token);
3344                                         COM_ParseToken_Simple(&data, false, false, true);
3345                                         //scroll_t = atof(com_token);
3346                                         COM_ParseToken_Simple(&data, false, false, true);
3347                                         //rotate = atof(com_token);
3348                                         COM_ParseToken_Simple(&data, false, false, true);
3349                                         //scale_s = atof(com_token);
3350                                         COM_ParseToken_Simple(&data, false, false, true);
3351                                         //scale_t = atof(com_token);
3352                                         TriangleNormal(point[0], point[1], point[2], planenormal);
3353                                         VectorNormalizeDouble(planenormal);
3354                                         planedist = DotProduct(point[0], planenormal);
3355                                         //ChooseTexturePlane(planenormal, texturevector[0], texturevector[1]);
3356                                 }
3357                                 continue;
3358                         }
3359                 }
3360         }
3361 #endif
3362 }
3363
3364
3365 #define MAX_PORTALPOINTS 64
3366
3367 typedef struct portal_s
3368 {
3369         mplane_t plane;
3370         mnode_t *nodes[2];              // [0] = front side of plane
3371         struct portal_s *next[2];
3372         int numpoints;
3373         double points[3*MAX_PORTALPOINTS];
3374         struct portal_s *chain; // all portals are linked into a list
3375 }
3376 portal_t;
3377
3378 static memexpandablearray_t portalarray;
3379
3380 static void Mod_BSP_RecursiveRecalcNodeBBox(mnode_t *node)
3381 {
3382         // process only nodes (leafs already had their box calculated)
3383         if (!node->plane)
3384                 return;
3385
3386         // calculate children first
3387         Mod_BSP_RecursiveRecalcNodeBBox(node->children[0]);
3388         Mod_BSP_RecursiveRecalcNodeBBox(node->children[1]);
3389
3390         // make combined bounding box from children
3391         node->mins[0] = min(node->children[0]->mins[0], node->children[1]->mins[0]);
3392         node->mins[1] = min(node->children[0]->mins[1], node->children[1]->mins[1]);
3393         node->mins[2] = min(node->children[0]->mins[2], node->children[1]->mins[2]);
3394         node->maxs[0] = max(node->children[0]->maxs[0], node->children[1]->maxs[0]);
3395         node->maxs[1] = max(node->children[0]->maxs[1], node->children[1]->maxs[1]);
3396         node->maxs[2] = max(node->children[0]->maxs[2], node->children[1]->maxs[2]);
3397 }
3398
3399 static void Mod_BSP_FinalizePortals(void)
3400 {
3401         int i, j, numportals, numpoints, portalindex, portalrange = (int)Mem_ExpandableArray_IndexRange(&portalarray);
3402         portal_t *p;
3403         mportal_t *portal;
3404         mvertex_t *point;
3405         mleaf_t *leaf, *endleaf;
3406
3407         // tally up portal and point counts and recalculate bounding boxes for all
3408         // leafs (because qbsp is very sloppy)
3409         leaf = loadmodel->brush.data_leafs;
3410         endleaf = leaf + loadmodel->brush.num_leafs;
3411         if (mod_recalculatenodeboxes.integer)
3412         {
3413                 for (;leaf < endleaf;leaf++)
3414                 {
3415                         VectorSet(leaf->mins,  2000000000,  2000000000,  2000000000);
3416                         VectorSet(leaf->maxs, -2000000000, -2000000000, -2000000000);
3417                 }
3418         }
3419         numportals = 0;
3420         numpoints = 0;
3421         for (portalindex = 0;portalindex < portalrange;portalindex++)
3422         {
3423                 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3424                 if (!p)
3425                         continue;
3426                 // note: this check must match the one below or it will usually corrupt memory
3427                 // the nodes[0] != nodes[1] check is because leaf 0 is the shared solid leaf, it can have many portals inside with leaf 0 on both sides
3428                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1] && ((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3429                 {
3430                         numportals += 2;
3431                         numpoints += p->numpoints * 2;
3432                 }
3433         }
3434         loadmodel->brush.data_portals = (mportal_t *)Mem_Alloc(loadmodel->mempool, numportals * sizeof(mportal_t) + numpoints * sizeof(mvertex_t));
3435         loadmodel->brush.num_portals = numportals;
3436         loadmodel->brush.data_portalpoints = (mvertex_t *)((unsigned char *) loadmodel->brush.data_portals + numportals * sizeof(mportal_t));
3437         loadmodel->brush.num_portalpoints = numpoints;
3438         // clear all leaf portal chains
3439         for (i = 0;i < loadmodel->brush.num_leafs;i++)
3440                 loadmodel->brush.data_leafs[i].portals = NULL;
3441         // process all portals in the global portal chain, while freeing them
3442         portal = loadmodel->brush.data_portals;
3443         point = loadmodel->brush.data_portalpoints;
3444         for (portalindex = 0;portalindex < portalrange;portalindex++)
3445         {
3446                 p = (portal_t*)Mem_ExpandableArray_RecordAtIndex(&portalarray, portalindex);
3447                 if (!p)
3448                         continue;
3449                 if (p->numpoints >= 3 && p->nodes[0] != p->nodes[1])
3450                 {
3451                         // note: this check must match the one above or it will usually corrupt memory
3452                         // the nodes[0] != nodes[1] check is because leaf 0 is the shared solid leaf, it can have many portals inside with leaf 0 on both sides
3453                         if (((mleaf_t *)p->nodes[0])->clusterindex >= 0 && ((mleaf_t *)p->nodes[1])->clusterindex >= 0)
3454                         {
3455                                 // first make the back to front portal(forward portal)
3456                                 portal->points = point;
3457                                 portal->numpoints = p->numpoints;
3458                                 portal->plane.dist = p->plane.dist;
3459                                 VectorCopy(p->plane.normal, portal->plane.normal);
3460                                 portal->here = (mleaf_t *)p->nodes[1];
3461                                 portal->past = (mleaf_t *)p->nodes[0];
3462                                 // copy points
3463                                 for (j = 0;j < portal->numpoints;j++)
3464                                 {
3465                                         VectorCopy(p->points + j*3, point->position);
3466                                         point++;
3467                                 }
3468                                 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3469                                 PlaneClassify(&portal->plane);
3470
3471                                 // link into leaf's portal chain
3472                                 portal->next = portal->here->portals;
3473                                 portal->here->portals = portal;
3474
3475                                 // advance to next portal
3476                                 portal++;
3477
3478                                 // then make the front to back portal(backward portal)
3479                                 portal->points = point;
3480                                 portal->numpoints = p->numpoints;
3481                                 portal->plane.dist = -p->plane.dist;
3482                                 VectorNegate(p->plane.normal, portal->plane.normal);
3483                                 portal->here = (mleaf_t *)p->nodes[0];
3484                                 portal->past = (mleaf_t *)p->nodes[1];
3485                                 // copy points
3486                                 for (j = portal->numpoints - 1;j >= 0;j--)
3487                                 {
3488                                         VectorCopy(p->points + j*3, point->position);
3489                                         point++;
3490                                 }
3491                                 BoxFromPoints(portal->mins, portal->maxs, portal->numpoints, portal->points->position);
3492                                 PlaneClassify(&portal->plane);
3493
3494                                 // link into leaf's portal chain
3495                                 portal->next = portal->here->portals;
3496                                 portal->here->portals = portal;
3497
3498                                 // advance to next portal
3499                                 portal++;
3500                         }
3501                         // add the portal's polygon points to the leaf bounding boxes
3502                         if (mod_recalculatenodeboxes.integer)
3503                         {
3504                                 for (i = 0;i < 2;i++)
3505                                 {
3506                                         leaf = (mleaf_t *)p->nodes[i];
3507                                         for (j = 0;j < p->numpoints;j++)
3508                                         {
3509                                                 if (leaf->mins[0] > p->points[j*3+0]) leaf->mins[0] = p->points[j*3+0];
3510                                                 if (leaf->mins[1] > p->points[j*3+1]) leaf->mins[1] = p->points[j*3+1];
3511                                                 if (leaf->mins[2] > p->points[j*3+2]) leaf->mins[2] = p->points[j*3+2];
3512                                                 if (leaf->maxs[0] < p->points[j*3+0]) leaf->maxs[0] = p->points[j*3+0];
3513                                                 if (leaf->maxs[1] < p->points[j*3+1]) leaf->maxs[1] = p->points[j*3+1];
3514                                                 if (leaf->maxs[2] < p->points[j*3+2]) leaf->maxs[2] = p->points[j*3+2];
3515                                         }
3516                                 }
3517                         }
3518                 }
3519         }
3520         // now recalculate the node bounding boxes from the leafs
3521         if (mod_recalculatenodeboxes.integer)
3522                 Mod_BSP_RecursiveRecalcNodeBBox(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3523 }
3524
3525 /*
3526 =============
3527 AddPortalToNodes
3528 =============
3529 */
3530 static void AddPortalToNodes(portal_t *p, mnode_t *front, mnode_t *back)
3531 {
3532         if (!front)
3533                 Host_Error("AddPortalToNodes: NULL front node");
3534         if (!back)
3535                 Host_Error("AddPortalToNodes: NULL back node");
3536         if (p->nodes[0] || p->nodes[1])
3537                 Host_Error("AddPortalToNodes: already included");
3538         // note: front == back is handled gracefully, because leaf 0 is the shared solid leaf, it can often have portals with the same leaf on both sides
3539
3540         p->nodes[0] = front;
3541         p->next[0] = (portal_t *)front->portals;
3542         front->portals = (mportal_t *)p;
3543
3544         p->nodes[1] = back;
3545         p->next[1] = (portal_t *)back->portals;
3546         back->portals = (mportal_t *)p;
3547 }
3548
3549 /*
3550 =============
3551 RemovePortalFromNode
3552 =============
3553 */
3554 static void RemovePortalFromNodes(portal_t *portal)
3555 {
3556         int i;
3557         mnode_t *node;
3558         void **portalpointer;
3559         portal_t *t;
3560         for (i = 0;i < 2;i++)
3561         {
3562                 node = portal->nodes[i];
3563
3564                 portalpointer = (void **) &node->portals;
3565                 while (1)
3566                 {
3567                         t = (portal_t *)*portalpointer;
3568                         if (!t)
3569                                 Host_Error("RemovePortalFromNodes: portal not in leaf");
3570
3571                         if (t == portal)
3572                         {
3573                                 if (portal->nodes[0] == node)
3574                                 {
3575                                         *portalpointer = portal->next[0];
3576                                         portal->nodes[0] = NULL;
3577                                 }
3578                                 else if (portal->nodes[1] == node)
3579                                 {
3580                                         *portalpointer = portal->next[1];
3581                                         portal->nodes[1] = NULL;
3582                                 }
3583                                 else
3584                                         Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3585                                 break;
3586                         }
3587
3588                         if (t->nodes[0] == node)
3589                                 portalpointer = (void **) &t->next[0];
3590                         else if (t->nodes[1] == node)
3591                                 portalpointer = (void **) &t->next[1];
3592                         else
3593                                 Host_Error("RemovePortalFromNodes: portal not bounding leaf");
3594                 }
3595         }
3596 }
3597
3598 #define PORTAL_DIST_EPSILON (1.0 / 32.0)
3599 static double *portalpointsbuffer;
3600 static int portalpointsbufferoffset;
3601 static int portalpointsbuffersize;
3602 static void Mod_BSP_RecursiveNodePortals(mnode_t *node)
3603 {
3604         int i, side;
3605         mnode_t *front, *back, *other_node;
3606         mplane_t clipplane, *plane;
3607         portal_t *portal, *nextportal, *nodeportal, *splitportal, *temp;
3608         int numfrontpoints, numbackpoints;
3609         double *frontpoints, *backpoints;
3610
3611         // if a leaf, we're done
3612         if (!node->plane)
3613                 return;
3614
3615         // get some space for our clipping operations to use
3616         if (portalpointsbuffersize < portalpointsbufferoffset + 6*MAX_PORTALPOINTS)
3617         {
3618                 portalpointsbuffersize = portalpointsbufferoffset * 2;
3619                 portalpointsbuffer = (double *)Mem_Realloc(loadmodel->mempool, portalpointsbuffer, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3620         }
3621         frontpoints = portalpointsbuffer + portalpointsbufferoffset;
3622         portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3623         backpoints = portalpointsbuffer + portalpointsbufferoffset;
3624         portalpointsbufferoffset += 3*MAX_PORTALPOINTS;
3625
3626         plane = node->plane;
3627
3628         front = node->children[0];
3629         back = node->children[1];
3630         if (front == back)
3631                 Host_Error("Mod_BSP_RecursiveNodePortals: corrupt node hierarchy");
3632
3633         // create the new portal by generating a polygon for the node plane,
3634         // and clipping it by all of the other portals(which came from nodes above this one)
3635         nodeportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3636         nodeportal->plane = *plane;
3637
3638         // TODO: calculate node bounding boxes during recursion and calculate a maximum plane size accordingly to improve precision (as most maps do not need 1 billion unit plane polygons)
3639         PolygonD_QuadForPlane(nodeportal->points, nodeportal->plane.normal[0], nodeportal->plane.normal[1], nodeportal->plane.normal[2], nodeportal->plane.dist, 1024.0*1024.0*1024.0);
3640         nodeportal->numpoints = 4;
3641
3642         for (portal = (portal_t *)node->portals;portal;portal = portal->next[side])
3643         {
3644                 clipplane = portal->plane;
3645                 if (portal->nodes[0] == portal->nodes[1])
3646                         Host_Error("Mod_BSP_RecursiveNodePortals: portal has same node on both sides(1)");
3647                 if (portal->nodes[0] == node)
3648                         side = 0;
3649                 else if (portal->nodes[1] == node)
3650                 {
3651                         clipplane.dist = -clipplane.dist;
3652                         VectorNegate(clipplane.normal, clipplane.normal);
3653                         side = 1;
3654                 }
3655                 else
3656                 {
3657                         Host_Error("Mod_BSP_RecursiveNodePortals: mislinked portal");
3658                         side = 0; // hush warning
3659                 }
3660
3661                 for (i = 0;i < nodeportal->numpoints*3;i++)
3662                         frontpoints[i] = nodeportal->points[i];
3663                 PolygonD_Divide(nodeportal->numpoints, frontpoints, clipplane.normal[0], clipplane.normal[1], clipplane.normal[2], clipplane.dist, PORTAL_DIST_EPSILON, MAX_PORTALPOINTS, nodeportal->points, &nodeportal->numpoints, 0, NULL, NULL, NULL);
3664                 if (nodeportal->numpoints <= 0 || nodeportal->numpoints >= MAX_PORTALPOINTS)
3665                         break;
3666         }
3667
3668         if (nodeportal->numpoints < 3)
3669         {
3670                 Con_Print(CON_WARN "Mod_BSP_RecursiveNodePortals: WARNING: new portal was clipped away\n");
3671                 nodeportal->numpoints = 0;
3672         }
3673         else if (nodeportal->numpoints >= MAX_PORTALPOINTS)
3674         {
3675                 Con_Print(CON_WARN "Mod_BSP_RecursiveNodePortals: WARNING: new portal has too many points\n");
3676                 nodeportal->numpoints = 0;
3677         }
3678
3679         AddPortalToNodes(nodeportal, front, back);
3680
3681         // split the portals of this node along this node's plane and assign them to the children of this node
3682         // (migrating the portals downward through the tree)
3683         for (portal = (portal_t *)node->portals;portal;portal = nextportal)
3684         {
3685                 if (portal->nodes[0] == portal->nodes[1])
3686                         Host_Error("Mod_BSP_RecursiveNodePortals: portal has same node on both sides(2)");
3687                 if (portal->nodes[0] == node)
3688                         side = 0;
3689                 else if (portal->nodes[1] == node)
3690                         side = 1;
3691                 else
3692                 {
3693                         Host_Error("Mod_BSP_RecursiveNodePortals: mislinked portal");
3694                         side = 0; // hush warning
3695                 }
3696                 nextportal = portal->next[side];
3697                 if (!portal->numpoints)
3698                         continue;
3699
3700                 other_node = portal->nodes[!side];
3701                 RemovePortalFromNodes(portal);
3702
3703                 // cut the portal into two portals, one on each side of the node plane
3704                 PolygonD_Divide(portal->numpoints, portal->points, plane->normal[0], plane->normal[1], plane->normal[2], plane->dist, PORTAL_DIST_EPSILON, MAX_PORTALPOINTS, frontpoints, &numfrontpoints, MAX_PORTALPOINTS, backpoints, &numbackpoints, NULL);
3705
3706                 if (!numfrontpoints)
3707                 {
3708                         if (side == 0)
3709                                 AddPortalToNodes(portal, back, other_node);
3710                         else
3711                                 AddPortalToNodes(portal, other_node, back);
3712                         continue;
3713                 }
3714                 if (!numbackpoints)
3715                 {
3716                         if (side == 0)
3717                                 AddPortalToNodes(portal, front, other_node);
3718                         else
3719                                 AddPortalToNodes(portal, other_node, front);
3720                         continue;
3721                 }
3722
3723                 // the portal is split
3724                 splitportal = (portal_t *)Mem_ExpandableArray_AllocRecord(&portalarray);
3725                 temp = splitportal->chain;
3726                 *splitportal = *portal;
3727                 splitportal->chain = temp;
3728                 for (i = 0;i < numbackpoints*3;i++)
3729                         splitportal->points[i] = backpoints[i];
3730                 splitportal->numpoints = numbackpoints;
3731                 for (i = 0;i < numfrontpoints*3;i++)
3732                         portal->points[i] = frontpoints[i];
3733                 portal->numpoints = numfrontpoints;
3734
3735                 if (side == 0)
3736                 {
3737                         AddPortalToNodes(portal, front, other_node);
3738                         AddPortalToNodes(splitportal, back, other_node);
3739                 }
3740                 else
3741                 {
3742                         AddPortalToNodes(portal, other_node, front);
3743                         AddPortalToNodes(splitportal, other_node, back);
3744                 }
3745         }
3746
3747         Mod_BSP_RecursiveNodePortals(front);
3748         Mod_BSP_RecursiveNodePortals(back);
3749
3750         portalpointsbufferoffset -= 6*MAX_PORTALPOINTS;
3751 }
3752
3753 static void Mod_BSP_MakePortals(void)
3754 {
3755         Mem_ExpandableArray_NewArray(&portalarray, loadmodel->mempool, sizeof(portal_t), 1020*1024/sizeof(portal_t));
3756         portalpointsbufferoffset = 0;
3757         portalpointsbuffersize = 6*MAX_PORTALPOINTS*128;
3758         portalpointsbuffer = (double *)Mem_Alloc(loadmodel->mempool, portalpointsbuffersize * sizeof(*portalpointsbuffer));
3759         Mod_BSP_RecursiveNodePortals(loadmodel->brush.data_nodes + loadmodel->brushq1.hulls[0].firstclipnode);
3760         Mem_Free(portalpointsbuffer);
3761         portalpointsbuffer = NULL;
3762         portalpointsbufferoffset = 0;
3763         portalpointsbuffersize = 0;
3764         Mod_BSP_FinalizePortals();
3765         Mem_ExpandableArray_FreeArray(&portalarray);
3766 }
3767
3768 //Returns PVS data for a given point
3769 //(note: can return NULL)
3770 static unsigned char *Mod_BSP_GetPVS(model_t *model, const vec3_t p)
3771 {
3772         mnode_t *node;
3773         node = model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode;
3774         while (node->plane)
3775                 node = node->children[(node->plane->type < 3 ? p[node->plane->type] : DotProduct(p,node->plane->normal)) < node->plane->dist];
3776         if (((mleaf_t *)node)->clusterindex >= 0)
3777                 return model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3778         else
3779                 return NULL;
3780 }
3781
3782 static void Mod_BSP_FatPVS_RecursiveBSPNode(model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbytes, mnode_t *node)
3783 {
3784         while (node->plane)
3785         {
3786                 float d = PlaneDiff(org, node->plane);
3787                 if (d > radius)
3788                         node = node->children[0];
3789                 else if (d < -radius)
3790                         node = node->children[1];
3791                 else
3792                 {
3793                         // go down both sides
3794                         Mod_BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, pvsbytes, node->children[0]);
3795                         node = node->children[1];
3796                 }
3797         }
3798         // if this leaf is in a cluster, accumulate the pvs bits
3799         if (((mleaf_t *)node)->clusterindex >= 0)
3800         {
3801                 int i;
3802                 unsigned char *pvs = model->brush.data_pvsclusters + ((mleaf_t *)node)->clusterindex * model->brush.num_pvsclusterbytes;
3803                 for (i = 0;i < pvsbytes;i++)
3804                         pvsbuffer[i] |= pvs[i];
3805         }
3806 }
3807
3808 //Calculates a PVS that is the inclusive or of all leafs within radius pixels
3809 //of the given point.
3810 static int Mod_BSP_FatPVS(model_t *model, const vec3_t org, vec_t radius, unsigned char *pvsbuffer, int pvsbufferlength, qbool merge)
3811 {
3812         int bytes = model->brush.num_pvsclusterbytes;
3813         bytes = min(bytes, pvsbufferlength);
3814         if (r_novis.integer || r_trippy.integer || !model->brush.num_pvsclusters || !Mod_BSP_GetPVS(model, org))
3815         {
3816                 memset(pvsbuffer, 0xFF, bytes);
3817                 return bytes;
3818         }
3819         if (!merge)
3820                 memset(pvsbuffer, 0, bytes);
3821         Mod_BSP_FatPVS_RecursiveBSPNode(model, org, radius, pvsbuffer, bytes, model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode);
3822         return bytes;
3823 }
3824
3825 static void Mod_Q1BSP_RoundUpToHullSize(model_t *cmodel, const vec3_t inmins, const vec3_t inmaxs, vec3_t outmins, vec3_t outmaxs)
3826 {
3827         vec3_t size;
3828         const hull_t *hull;
3829
3830         VectorSubtract(inmaxs, inmins, size);
3831         if (size[0] < mod_q1bsp_zero_hullsize_cutoff.value)
3832                 hull = &cmodel->brushq1.hulls[0]; // 0x0x0
3833         else if (cmodel->brush.ishlbsp)
3834         {
3835                 if (size[0] <= 32)
3836                 {
3837                         if (size[2] < 54) // pick the nearest of 36 or 72
3838                                 hull = &cmodel->brushq1.hulls[3]; // 32x32x36
3839                         else
3840                                 hull = &cmodel->brushq1.hulls[1]; // 32x32x72
3841                 }
3842                 else
3843                         hull = &cmodel->brushq1.hulls[2]; // 64x64x64
3844         }
3845         else
3846         {
3847                 if (size[0] <= 32)
3848                         hull = &cmodel->brushq1.hulls[1]; // 32x32x56
3849                 else
3850                         hull = &cmodel->brushq1.hulls[2]; // 64x64x88
3851         }
3852         VectorCopy(inmins, outmins);
3853         VectorAdd(inmins, hull->clip_size, outmaxs);
3854 }
3855
3856 void Mod_CollisionBIH_TraceLineAgainstSurfaces(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask);
3857
3858 void Mod_2PSB_Load(model_t *mod, void *buffer, void *bufferend)
3859 {
3860         mod->brush.isbsp2 = true;
3861         mod->brush.isbsp2rmqe = true; // like bsp2 except leaf/node bounds are 16bit (unexpanded)
3862         mod->modeldatatypestring = "Q1BSP2rmqe";
3863         Mod_Q1BSP_Load(mod, buffer, bufferend);
3864 }
3865
3866 void Mod_BSP2_Load(model_t *mod, void *buffer, void *bufferend)
3867 {
3868         mod->brush.isbsp2 = true;
3869         mod->modeldatatypestring = "Q1BSP2";
3870         Mod_Q1BSP_Load(mod, buffer, bufferend);
3871 }
3872
3873 void Mod_HLBSP_Load(model_t *mod, void *buffer, void *bufferend)
3874 {
3875         mod->brush.ishlbsp = true;
3876         mod->modeldatatypestring = "HLBSP";
3877         Mod_Q1BSP_Load(mod, buffer, bufferend);
3878 }
3879
3880 void Mod_Q1BSP_Load(model_t *mod, void *buffer, void *bufferend)
3881 {
3882         int i, j, k;
3883         sizebuf_t lumpsb[HEADER_LUMPS];
3884         mmodel_t *bm;
3885         float dist, modelyawradius, modelradius;
3886         msurface_t *surface;
3887         hullinfo_t hullinfo;
3888         int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
3889         model_brush_lightstyleinfo_t styleinfo[256];
3890         int *datapointer;
3891         model_brush_lightstyleinfo_t *lsidatapointer;
3892         sizebuf_t sb;
3893
3894         MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
3895
3896         mod->type = mod_brushq1;
3897
3898         mod->brush.skymasking = true;
3899         i = MSG_ReadLittleLong(&sb);
3900
3901         if(!mod->modeldatatypestring)
3902                 mod->modeldatatypestring = "Q1BSP";
3903
3904 // fill in hull info
3905         VectorClear (hullinfo.hullsizes[0][0]);
3906         VectorClear (hullinfo.hullsizes[0][1]);
3907         if (mod->brush.ishlbsp)
3908         {
3909                 hullinfo.filehulls = 4;
3910                 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -36);
3911                 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 36);
3912                 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -32);
3913                 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 32);
3914                 VectorSet (hullinfo.hullsizes[3][0], -16, -16, -18);
3915                 VectorSet (hullinfo.hullsizes[3][1], 16, 16, 18);
3916         }
3917         else
3918         {
3919                 hullinfo.filehulls = 4;
3920                 VectorSet (hullinfo.hullsizes[1][0], -16, -16, -24);
3921                 VectorSet (hullinfo.hullsizes[1][1], 16, 16, 32);
3922                 VectorSet (hullinfo.hullsizes[2][0], -32, -32, -24);
3923                 VectorSet (hullinfo.hullsizes[2][1], 32, 32, 64);
3924         }
3925
3926 // read lumps
3927         for (i = 0; i < HEADER_LUMPS; i++)
3928         {
3929                 int offset = MSG_ReadLittleLong(&sb);
3930                 int size = MSG_ReadLittleLong(&sb);
3931                 if (offset < 0 || offset + size > sb.cursize)
3932                         Host_Error("Mod_Q1BSP_Load: %s has invalid lump %i (offset %i, size %i, file size %i)\n", mod->name, i, offset, size, (int)sb.cursize);
3933                 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
3934         }
3935
3936         mod->soundfromcenter = true;
3937         mod->TraceBox = Mod_Q1BSP_TraceBox;
3938         mod->TraceLine = Mod_Q1BSP_TraceLine;
3939         mod->TracePoint = Mod_Q1BSP_TracePoint;
3940         mod->PointSuperContents = Mod_Q1BSP_PointSuperContents;
3941         mod->TraceLineAgainstSurfaces = Mod_Q1BSP_TraceLineAgainstSurfaces;
3942         mod->brush.TraceLineOfSight = Mod_Q1BSP_TraceLineOfSight;
3943         mod->brush.SuperContentsFromNativeContents = Mod_Q1BSP_SuperContentsFromNativeContents;
3944         mod->brush.NativeContentsFromSuperContents = Mod_Q1BSP_NativeContentsFromSuperContents;
3945         mod->brush.GetPVS = Mod_BSP_GetPVS;
3946         mod->brush.FatPVS = Mod_BSP_FatPVS;
3947         mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
3948         mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
3949         mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
3950         mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
3951         mod->brush.LightPoint = Mod_BSP_LightPoint;
3952         mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
3953         mod->brush.AmbientSoundLevelsForPoint = Mod_Q1BSP_AmbientSoundLevelsForPoint;
3954         mod->brush.RoundUpToHullSize = Mod_Q1BSP_RoundUpToHullSize;
3955         mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
3956         mod->Draw = R_Mod_Draw;
3957         mod->DrawDepth = R_Mod_DrawDepth;
3958         mod->DrawDebug = R_Mod_DrawDebug;
3959         mod->DrawPrepass = R_Mod_DrawPrepass;
3960         mod->GetLightInfo = R_Mod_GetLightInfo;
3961         mod->CompileShadowMap = R_Mod_CompileShadowMap;
3962         mod->DrawShadowMap = R_Mod_DrawShadowMap;
3963         mod->DrawLight = R_Mod_DrawLight;
3964
3965 // load into heap
3966
3967         mod->brush.qw_md4sum = 0;
3968         mod->brush.qw_md4sum2 = 0;
3969         for (i = 0;i < HEADER_LUMPS;i++)
3970         {
3971                 int temp;
3972                 if (i == LUMP_ENTITIES)
3973                         continue;
3974                 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
3975                 mod->brush.qw_md4sum ^= LittleLong(temp);
3976                 if (i == LUMP_VISIBILITY || i == LUMP_LEAFS || i == LUMP_NODES)
3977                         continue;
3978                 mod->brush.qw_md4sum2 ^= LittleLong(temp);
3979         }
3980
3981         Mod_Q1BSP_LoadEntities(&lumpsb[LUMP_ENTITIES]);
3982         Mod_Q1BSP_LoadVertexes(&lumpsb[LUMP_VERTEXES]);
3983         Mod_Q1BSP_LoadEdges(&lumpsb[LUMP_EDGES]);
3984         Mod_Q1BSP_LoadSurfedges(&lumpsb[LUMP_SURFEDGES]);
3985         Mod_Q1BSP_LoadTextures(&lumpsb[LUMP_TEXTURES]);
3986         Mod_Q1BSP_LoadLighting(&lumpsb[LUMP_LIGHTING]);
3987         Mod_Q1BSP_LoadPlanes(&lumpsb[LUMP_PLANES]);
3988         Mod_Q1BSP_LoadTexinfo(&lumpsb[LUMP_TEXINFO]);
3989         Mod_Q1BSP_LoadFaces(&lumpsb[LUMP_FACES]);
3990         Mod_Q1BSP_LoadLeaffaces(&lumpsb[LUMP_MARKSURFACES]);
3991         Mod_Q1BSP_LoadVisibility(&lumpsb[LUMP_VISIBILITY]);
3992         // load submodels before leafs because they contain the number of vis leafs
3993         Mod_BSP_LoadSubmodels(&lumpsb[LUMP_MODELS], &hullinfo);
3994         Mod_Q1BSP_LoadLeafs(&lumpsb[LUMP_LEAFS]);
3995         Mod_Q1BSP_LoadNodes(&lumpsb[LUMP_NODES]);
3996         Mod_Q1BSP_LoadClipnodes(&lumpsb[LUMP_CLIPNODES], &hullinfo);
3997
3998         for (i = 0; i < HEADER_LUMPS; i++)
3999                 if (lumpsb[i].readcount != lumpsb[i].cursize && i != LUMP_TEXTURES && i != LUMP_LIGHTING)
4000                         Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4001
4002         // check if the map supports transparent water rendering
4003         loadmodel->brush.supportwateralpha = Mod_Q1BSP_CheckWaterAlphaSupport();
4004
4005         // we don't need the compressed pvs data anymore
4006         if (mod->brushq1.data_compressedpvs)
4007                 Mem_Free(mod->brushq1.data_compressedpvs);
4008         mod->brushq1.data_compressedpvs = NULL;
4009         mod->brushq1.num_compressedpvs = 0;
4010
4011         Mod_Q1BSP_MakeHull0();
4012         if (mod_bsp_portalize.integer && cls.state != ca_dedicated)
4013                 Mod_BSP_MakePortals();
4014
4015         mod->numframes = 2;             // regular and alternate animation
4016         mod->numskins = 1;
4017
4018         if (loadmodel->brush.numsubmodels)
4019                 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
4020
4021         // LadyHavoc: to clear the fog around the original quake submodel code, I
4022         // will explain:
4023         // first of all, some background info on the submodels:
4024         // model 0 is the map model (the world, named maps/e1m1.bsp for example)
4025         // model 1 and higher are submodels (doors and the like, named *1, *2, etc)
4026         // now the weird for loop itself:
4027         // the loop functions in an odd way, on each iteration it sets up the
4028         // current 'mod' model (which despite the confusing code IS the model of
4029         // the number i), at the end of the loop it duplicates the model to become
4030         // the next submodel, and loops back to set up the new submodel.
4031
4032         // LadyHavoc: now the explanation of my sane way (which works identically):
4033         // set up the world model, then on each submodel copy from the world model
4034         // and set up the submodel with the respective model info.
4035         totalstylesurfaces = 0;
4036         totalstyles = 0;
4037         for (i = 0;i < mod->brush.numsubmodels;i++)
4038         {
4039                 memset(stylecounts, 0, sizeof(stylecounts));
4040                 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4041                 {
4042                         surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4043                         for (j = 0;j < MAXLIGHTMAPS;j++)
4044                                 stylecounts[surface->lightmapinfo->styles[j]]++;
4045                 }
4046                 for (k = 0;k < 255;k++)
4047                 {
4048                         totalstyles++;
4049                         if (stylecounts[k])
4050                                 totalstylesurfaces += stylecounts[k];
4051                 }
4052         }
4053         // bones_was_here: using a separate allocation for model_brush_lightstyleinfo_t
4054         // because on a 64-bit machine it no longer has the same alignment requirement as int.
4055         lsidatapointer = Mem_AllocType(mod->mempool, model_brush_lightstyleinfo_t, totalstyles * sizeof(model_brush_lightstyleinfo_t));
4056         datapointer = Mem_AllocType(mod->mempool, int, mod->num_surfaces * sizeof(int) + totalstylesurfaces * sizeof(int));
4057         mod->modelsurfaces_sorted = datapointer;datapointer += mod->num_surfaces;
4058         for (i = 0;i < mod->brush.numsubmodels;i++)
4059         {
4060                 // LadyHavoc: this code was originally at the end of this loop, but
4061                 // has been transformed to something more readable at the start here.
4062
4063                 if (i > 0)
4064                 {
4065                         char name[10];
4066                         // duplicate the basic information
4067                         dpsnprintf(name, sizeof(name), "*%i", i);
4068                         mod = Mod_FindName(name, loadmodel->name);
4069                         // copy the base model to this one
4070                         *mod = *loadmodel;
4071                         // rename the clone back to its proper name
4072                         dp_strlcpy(mod->name, name, sizeof(mod->name));
4073                         mod->brush.parentmodel = loadmodel;
4074                         // textures and memory belong to the main model
4075                         mod->texturepool = NULL;
4076                         mod->mempool = NULL;
4077                         mod->brush.GetPVS = NULL;
4078                         mod->brush.FatPVS = NULL;
4079                         mod->brush.BoxTouchingPVS = NULL;
4080                         mod->brush.BoxTouchingLeafPVS = NULL;
4081                         mod->brush.BoxTouchingVisibleLeafs = NULL;
4082                         mod->brush.FindBoxClusters = NULL;
4083                         mod->brush.LightPoint = NULL;
4084                         mod->brush.AmbientSoundLevelsForPoint = NULL;
4085                 }
4086
4087                 mod->brush.submodel = i;
4088
4089                 if (loadmodel->brush.submodels)
4090                         loadmodel->brush.submodels[i] = mod;
4091
4092                 bm = &mod->brushq1.submodels[i];
4093
4094                 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
4095                 for (j=1 ; j<MAX_MAP_HULLS ; j++)
4096                 {
4097                         mod->brushq1.hulls[j].firstclipnode = bm->headnode[j];
4098                         mod->brushq1.hulls[j].lastclipnode = mod->brushq1.numclipnodes - 1;
4099                 }
4100
4101                 mod->submodelsurfaces_start = bm->firstface;
4102                 mod->submodelsurfaces_end = bm->firstface + bm->numfaces;
4103
4104                 // set node/leaf parents for this submodel
4105                 Mod_BSP_LoadNodes_RecursiveSetParent(mod->brush.data_nodes + mod->brushq1.hulls[0].firstclipnode, NULL);
4106
4107                 // this has to occur after hull info has been set, as it uses Mod_Q1BSP_PointSuperContents
4108                 Mod_Q1BSP_AssignNoShadowSkySurfaces(mod);
4109
4110                 // copy the submodel bounds, then enlarge the yaw and rotated bounds according to radius
4111                 // (previously this code measured the radius of the vertices of surfaces in the submodel, but that broke submodels that contain only CLIP brushes, which do not produce surfaces)
4112                 VectorCopy(bm->mins, mod->normalmins);
4113                 VectorCopy(bm->maxs, mod->normalmaxs);
4114                 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
4115                 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
4116                 modelyawradius = dist*dist+modelyawradius*modelyawradius;
4117                 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
4118                 modelradius = modelyawradius + modelradius * modelradius;
4119                 modelyawradius = sqrt(modelyawradius);
4120                 modelradius = sqrt(modelradius);
4121                 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
4122                 mod->yawmins[2] = mod->normalmins[2];
4123                 mod->yawmaxs[0] = mod->yawmaxs[1] =  modelyawradius;
4124                 mod->yawmaxs[2] = mod->normalmaxs[2];
4125                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
4126                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] =  modelradius;
4127                 mod->radius = modelradius;
4128                 mod->radius2 = modelradius * modelradius;
4129
4130                 Mod_SetDrawSkyAndWater(mod);
4131
4132                 if (mod->submodelsurfaces_start < mod->submodelsurfaces_end)
4133                 {
4134                         // build lightstyle update chains
4135                         // (used to rapidly mark lightmapupdateflags on many surfaces
4136                         // when d_lightstylevalue changes)
4137                         memset(stylecounts, 0, sizeof(stylecounts));
4138                         for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
4139                                 for (j = 0;j < MAXLIGHTMAPS;j++)
4140                                         stylecounts[mod->data_surfaces[k].lightmapinfo->styles[j]]++;
4141                         mod->brushq1.num_lightstyles = 0;
4142                         for (k = 0;k < 255;k++)
4143                         {
4144                                 if (stylecounts[k])
4145                                 {
4146                                         styleinfo[mod->brushq1.num_lightstyles].style = k;
4147                                         styleinfo[mod->brushq1.num_lightstyles].value = 0;
4148                                         styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
4149                                         styleinfo[mod->brushq1.num_lightstyles].surfacelist = datapointer;datapointer += stylecounts[k];
4150                                         remapstyles[k] = mod->brushq1.num_lightstyles;
4151                                         mod->brushq1.num_lightstyles++;
4152                                 }
4153                         }
4154                         for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
4155                         {
4156                                 surface = mod->data_surfaces + k;
4157                                 for (j = 0;j < MAXLIGHTMAPS;j++)
4158                                 {
4159                                         if (surface->lightmapinfo->styles[j] != 255)
4160                                         {
4161                                                 int r = remapstyles[surface->lightmapinfo->styles[j]];
4162                                                 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = k;
4163                                         }
4164                                 }
4165                         }
4166                         mod->brushq1.data_lightstyleinfo = lsidatapointer;lsidatapointer += mod->brushq1.num_lightstyles;
4167                         memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
4168                 }
4169                 else
4170                 {
4171                         // LadyHavoc: empty submodel(lacrima.bsp has such a glitch)
4172                         Con_Printf(CON_WARN "warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
4173                 }
4174                 //mod->brushq1.num_visleafs = bm->visleafs;
4175
4176                 // build a Bounding Interval Hierarchy for culling triangles in light rendering
4177                 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
4178
4179                 if (mod_q1bsp_polygoncollisions.integer)
4180                 {
4181                         mod->collision_bih = mod->render_bih;
4182                         // point traces and contents checks still use the bsp tree
4183                         mod->TraceLine = Mod_CollisionBIH_TraceLine;
4184                         mod->TraceBox = Mod_CollisionBIH_TraceBox;
4185                         mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4186                         mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLineAgainstSurfaces;
4187                 }
4188
4189                 // generate VBOs and other shared data before cloning submodels
4190                 if (i == 0)
4191                 {
4192                         Mod_BuildVBOs();
4193                         Mod_Q1BSP_LoadMapBrushes();
4194                         //Mod_Q1BSP_ProcessLightList();
4195                 }
4196         }
4197         mod = loadmodel;
4198
4199         // make the model surface list (used by shadowing/lighting)
4200         Mod_MakeSortedSurfaces(loadmodel);
4201
4202         Con_DPrintf("Stats for q1bsp model \"%s\": %i faces, %i nodes, %i leafs, %i visleafs, %i visleafportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
4203 }
4204
4205 int Mod_Q2BSP_SuperContentsFromNativeContents(int nativecontents)
4206 {
4207         int supercontents = 0;
4208         if (nativecontents & CONTENTSQ2_SOLID)
4209                 supercontents |= SUPERCONTENTS_SOLID;
4210         if (nativecontents & CONTENTSQ2_WATER)
4211                 supercontents |= SUPERCONTENTS_WATER;
4212         if (nativecontents & CONTENTSQ2_SLIME)
4213                 supercontents |= SUPERCONTENTS_SLIME;
4214         if (nativecontents & CONTENTSQ2_LAVA)
4215                 supercontents |= SUPERCONTENTS_LAVA;
4216         if (nativecontents & CONTENTSQ2_MONSTER)
4217                 supercontents |= SUPERCONTENTS_BODY;
4218         if (nativecontents & CONTENTSQ2_DEADMONSTER)
4219                 supercontents |= SUPERCONTENTS_CORPSE;
4220         if (nativecontents & CONTENTSQ2_PLAYERCLIP)
4221                 supercontents |= SUPERCONTENTS_PLAYERCLIP;
4222         if (nativecontents & CONTENTSQ2_MONSTERCLIP)
4223                 supercontents |= SUPERCONTENTS_MONSTERCLIP;
4224         if (!(nativecontents & CONTENTSQ2_TRANSLUCENT))
4225                 supercontents |= SUPERCONTENTS_OPAQUE;
4226         return supercontents;
4227 }
4228
4229 int Mod_Q2BSP_NativeContentsFromSuperContents(int supercontents)
4230 {
4231         int nativecontents = 0;
4232         if (supercontents & SUPERCONTENTS_SOLID)
4233                 nativecontents |= CONTENTSQ2_SOLID;
4234         if (supercontents & SUPERCONTENTS_WATER)
4235                 nativecontents |= CONTENTSQ2_WATER;
4236         if (supercontents & SUPERCONTENTS_SLIME)
4237                 nativecontents |= CONTENTSQ2_SLIME;
4238         if (supercontents & SUPERCONTENTS_LAVA)
4239                 nativecontents |= CONTENTSQ2_LAVA;
4240         if (supercontents & SUPERCONTENTS_BODY)
4241                 nativecontents |= CONTENTSQ2_MONSTER;
4242         if (supercontents & SUPERCONTENTS_CORPSE)
4243                 nativecontents |= CONTENTSQ2_DEADMONSTER;
4244         if (supercontents & SUPERCONTENTS_PLAYERCLIP)
4245                 nativecontents |= CONTENTSQ2_PLAYERCLIP;
4246         if (supercontents & SUPERCONTENTS_MONSTERCLIP)
4247                 nativecontents |= CONTENTSQ2_MONSTERCLIP;
4248         if (!(supercontents & SUPERCONTENTS_OPAQUE))
4249                 nativecontents |= CONTENTSQ2_TRANSLUCENT;
4250         return nativecontents;
4251 }
4252
4253 static void Mod_Q2BSP_LoadVisibility(sizebuf_t *sb)
4254 {
4255         int i, count;
4256         loadmodel->brushq1.num_compressedpvs = 0;
4257         loadmodel->brushq1.data_compressedpvs = NULL;
4258         loadmodel->brush.num_pvsclusters = 0;
4259         loadmodel->brush.num_pvsclusterbytes = 0;
4260         loadmodel->brush.data_pvsclusters = NULL;
4261
4262         if (!sb->cursize)
4263                 return;
4264
4265         count = MSG_ReadLittleLong(sb);
4266         loadmodel->brush.num_pvsclusters = count;
4267         loadmodel->brush.num_pvsclusterbytes = (count+7)>>3;
4268         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*loadmodel->brush.num_pvsclusterbytes);
4269         for (i = 0;i < count;i++)
4270         {
4271                 int pvsofs = MSG_ReadLittleLong(sb);
4272                 /*int phsofs = */MSG_ReadLittleLong(sb);
4273                 // decompress the vis data for this cluster
4274                 // (note this accesses the underlying data store of sb, which is kind of evil)
4275                 Mod_BSP_DecompressVis(sb->data + pvsofs, sb->data + sb->cursize, loadmodel->brush.data_pvsclusters + i * loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.data_pvsclusters + (i+1) * loadmodel->brush.num_pvsclusterbytes);
4276         }
4277         // hush the loading error check later - we had to do random access on this lump, so we didn't read to the end
4278         sb->readcount = sb->cursize;
4279 }
4280
4281 static void Mod_Q2BSP_LoadNodes(sizebuf_t *sb)
4282 {
4283         int                     i, j, count, p, child[2];
4284         mnode_t         *out;
4285         int structsize = 28;
4286
4287         if (sb->cursize % structsize)
4288                 Host_Error("Mod_Q2BSP_LoadNodes: funny lump size in %s",loadmodel->name);
4289         count = sb->cursize / structsize;
4290         if (count == 0)
4291                 Host_Error("Mod_Q2BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
4292         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4293
4294         loadmodel->brush.data_nodes = out;
4295         loadmodel->brush.num_nodes = count;
4296
4297         for ( i=0 ; i<count ; i++, out++)
4298         {
4299                 p = MSG_ReadLittleLong(sb);
4300                 out->plane = loadmodel->brush.data_planes + p;
4301                 child[0] = MSG_ReadLittleLong(sb);
4302                 child[1] = MSG_ReadLittleLong(sb);
4303                 out->mins[0] = MSG_ReadLittleShort(sb);
4304                 out->mins[1] = MSG_ReadLittleShort(sb);
4305                 out->mins[2] = MSG_ReadLittleShort(sb);
4306                 out->maxs[0] = MSG_ReadLittleShort(sb);
4307                 out->maxs[1] = MSG_ReadLittleShort(sb);
4308                 out->maxs[2] = MSG_ReadLittleShort(sb);
4309                 out->firstsurface = (unsigned short)MSG_ReadLittleShort(sb);
4310                 out->numsurfaces = (unsigned short)MSG_ReadLittleShort(sb);
4311                 if (out->firstsurface + out->numsurfaces > (unsigned int)loadmodel->num_surfaces)
4312                 {
4313                         Con_Printf("Mod_Q2BSP_LoadNodes: invalid surface index range %i+%i (file has only %i surfaces)\n", out->firstsurface, out->numsurfaces, loadmodel->num_surfaces);
4314                         out->firstsurface = 0;
4315                         out->numsurfaces = 0;
4316                 }
4317                 for (j=0 ; j<2 ; j++)
4318                 {
4319                         p = child[j];
4320                         if (p >= 0)
4321                         {
4322                                 if (p < loadmodel->brush.num_nodes)
4323                                         out->children[j] = loadmodel->brush.data_nodes + p;
4324                                 else
4325                                 {
4326                                         Con_Printf("Mod_Q2BSP_LoadNodes: invalid node index %i (file has only %i nodes)\n", p, loadmodel->brush.num_nodes);
4327                                         // map it to the solid leaf
4328                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4329                                 }
4330                         }
4331                         else
4332                         {
4333                                 // get leaf index as a positive value starting at 0 (-1 becomes 0, -2 becomes 1, etc)
4334                                 p = -(p+1);
4335                                 if (p < loadmodel->brush.num_leafs)
4336                                         out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + p);
4337                                 else
4338                                 {
4339                                         Con_Printf("Mod_Q2BSP_LoadNodes: invalid leaf index %i (file has only %i leafs)\n", p, loadmodel->brush.num_leafs);
4340                                         // map it to the solid leaf
4341                                         out->children[j] = (mnode_t *)loadmodel->brush.data_leafs;
4342                                 }
4343                         }
4344                 }
4345         }
4346
4347         Mod_BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);        // sets nodes and leafs
4348 }
4349
4350 static void Mod_Q2BSP_LoadTexinfo(sizebuf_t *sb)
4351 {
4352         mtexinfo_t *out;
4353         int i, l, count;
4354         int structsize = 76;
4355         int maxtextures = 1024; // hardcoded limit of quake2 engine, so we may as well use it as an upper bound
4356         char filename[MAX_QPATH];
4357
4358         if (sb->cursize % structsize)
4359                 Host_Error("Mod_Q2BSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
4360         count = sb->cursize / structsize;
4361         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4362         loadmodel->brushq1.texinfo = out;
4363         loadmodel->brushq1.numtexinfo = count;
4364         loadmodel->num_texturesperskin = 0;
4365         loadmodel->data_textures = (texture_t*)Mem_Alloc(loadmodel->mempool, maxtextures * sizeof(texture_t));
4366
4367         for (i = 0;i < count;i++, out++)
4368         {
4369                 int j, k;
4370                 for (k = 0;k < 2;k++)
4371                         for (j = 0;j < 4;j++)
4372                                 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
4373
4374                 out->q2flags = MSG_ReadLittleLong(sb);
4375                 out->q2value = MSG_ReadLittleLong(sb);
4376                 MSG_ReadBytes(sb, 32, (unsigned char*)out->q2texture);
4377                 out->q2texture[31] = 0; // make absolutely sure it is terminated
4378                 out->q2nexttexinfo = MSG_ReadLittleLong(sb);
4379
4380                 // find an existing match for the texture if possible
4381                 dpsnprintf(filename, sizeof(filename), "textures/%s.wal", out->q2texture);
4382                 for (j = 0;j < loadmodel->num_texturesperskin;j++)
4383                         if (!strcmp(filename, loadmodel->data_textures[j].name)
4384                          && out->q2flags == loadmodel->data_textures[j].q2flags
4385                          && out->q2value == loadmodel->data_textures[j].q2value)
4386                                 break;
4387                 // if we don't find the texture, store the new texture
4388                 if (j == loadmodel->num_texturesperskin)
4389                 {
4390                         if (loadmodel->num_texturesperskin < maxtextures)
4391                         {
4392                                 texture_t *tx = loadmodel->data_textures + j;
4393                                 int q2flags = out->q2flags;
4394                                 unsigned char *walfile = NULL;
4395                                 fs_offset_t walfilesize = 0;
4396                                 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, tx, filename, true, true, TEXF_ALPHA | TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL);
4397                                 // now read the .wal file to get metadata (even if a .tga was overriding it, we still need the wal data)
4398                                 walfile = FS_LoadFile(filename, tempmempool, true, &walfilesize);
4399                                 if (walfile)
4400                                 {
4401                                         int w, h;
4402                                         LoadWAL_GetMetadata(walfile, (int)walfilesize, &w, &h, NULL, NULL, &tx->q2contents, NULL);
4403                                         tx->width = w;
4404                                         tx->height = h;
4405                                         Mem_Free(walfile);
4406                                 }
4407                                 else
4408                                 {
4409                                         tx->width = 16;
4410                                         tx->height = 16;
4411                                 }
4412                                 tx->q2flags = out->q2flags;
4413                                 tx->q2value = out->q2value;
4414                                 // also modify the texture to have the correct contents and such based on flags
4415                                 // note that we create multiple texture_t structures if q2flags differs
4416                                 if (q2flags & Q2SURF_LIGHT)
4417                                 {
4418                                         // doesn't mean anything to us
4419                                 }
4420                                 if (q2flags & Q2SURF_SLICK)
4421                                 {
4422                                         // would be nice to support...
4423                                 }
4424                                 if (q2flags & Q2SURF_SKY)
4425                                 {
4426                                         // sky is a rather specific thing
4427                                         q2flags &= ~Q2SURF_NODRAW; // quake2 had a slightly different meaning than we have in mind here...
4428                                         tx->basematerialflags = MATERIALFLAG_SKY;
4429                                         tx->supercontents = SUPERCONTENTS_SKY | SUPERCONTENTS_NODROP | SUPERCONTENTS_OPAQUE;
4430                                         tx->surfaceflags = Q3SURFACEFLAG_SKY | Q3SURFACEFLAG_NOIMPACT | Q3SURFACEFLAG_NOMARKS | Q3SURFACEFLAG_NODLIGHT | Q3SURFACEFLAG_NOLIGHTMAP;
4431                                 }
4432                                 if (q2flags & Q2SURF_WARP)
4433                                 {
4434                                         // we use a scroll instead of a warp
4435                                         tx->basematerialflags |= MATERIALFLAG_WATERSCROLL | MATERIALFLAG_FULLBRIGHT;
4436                                         // if it's also transparent, we can enable the WATERSHADER
4437                                         // but we do not set the WATERALPHA flag because we don't
4438                                         // want to honor r_wateralpha in q2bsp
4439                                         // (it would go against the artistic intent)
4440                                         if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66))
4441                                                 tx->basematerialflags |= MATERIALFLAG_WATERSHADER;
4442                                 }
4443                                 if (q2flags & Q2SURF_TRANS33)
4444                                 {
4445                                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4446                                         tx->basealpha = 1.0f / 3.0f;
4447                                         tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4448                                         if (tx->q2contents & Q2CONTENTS_SOLID)
4449                                                 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4450                                 }
4451                                 if (q2flags & Q2SURF_TRANS66)
4452                                 {
4453                                         tx->basematerialflags |= MATERIALFLAG_ALPHA | MATERIALFLAG_BLENDED;
4454                                         tx->basealpha = 2.0f / 3.0f;
4455                                         tx->supercontents &= ~SUPERCONTENTS_OPAQUE;
4456                                         if (tx->q2contents & Q2CONTENTS_SOLID)
4457                                                 tx->q2contents = (tx->q2contents & ~Q2CONTENTS_SOLID) | Q2CONTENTS_WINDOW;
4458                                 }
4459                                 if ((q2flags & Q2SURF_FLOWING) && tx->materialshaderpass != NULL)
4460                                 {
4461                                         tx->materialshaderpass->tcmods[0].tcmod = Q3TCMOD_SCROLL;
4462                                         if (q2flags & Q2SURF_WARP)
4463                                                 tx->materialshaderpass->tcmods[0].parms[0] = -0.5f;
4464                                         else
4465                                                 tx->materialshaderpass->tcmods[0].parms[0] = -1.6f;
4466                                         tx->materialshaderpass->tcmods[0].parms[1] = 0.0f;
4467                                 }
4468                                 if (q2flags & Q2SURF_ALPHATEST)
4469                                 {
4470                                         // KMQUAKE2 and other modded engines added this flag for lit alpha tested surfaces
4471                                         tx->basematerialflags |= MATERIALFLAG_ALPHATEST | MATERIALFLAG_NOSHADOW;
4472                                 }
4473                                 else if (q2flags & (Q2SURF_TRANS33 | Q2SURF_TRANS66 | Q2SURF_WARP))
4474                                 {
4475                                         if (!mod_q2bsp_littransparentsurfaces.integer)
4476                                                 tx->basematerialflags |= MATERIALFLAG_FULLBRIGHT;
4477                                 }
4478                                 if (q2flags & Q2SURF_NODRAW)
4479                                 {
4480                                         tx->basematerialflags = MATERIALFLAG_NODRAW | MATERIALFLAG_NOSHADOW;
4481                                 }
4482                                 if (tx->q2contents & (Q2CONTENTS_TRANSLUCENT | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_PLAYERCLIP))
4483                                         tx->q2contents |= Q2CONTENTS_DETAIL;
4484                                 if (!(tx->q2contents & (Q2CONTENTS_SOLID | Q2CONTENTS_WINDOW | Q2CONTENTS_AUX | Q2CONTENTS_LAVA | Q2CONTENTS_SLIME | Q2CONTENTS_WATER | Q2CONTENTS_MIST | Q2CONTENTS_PLAYERCLIP | Q2CONTENTS_MONSTERCLIP | Q2CONTENTS_MIST)))
4485                                         tx->q2contents |= Q2CONTENTS_SOLID;
4486                                 if (tx->q2flags & (Q2SURF_HINT | Q2SURF_SKIP))
4487                                         tx->q2contents = 0;
4488                                 tx->supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(tx->q2contents);
4489                                 // set the current values to the base values
4490                                 tx->currentframe = tx;
4491                                 tx->currentskinframe = tx->materialshaderpass != NULL ? tx->materialshaderpass->skinframes[0] : NULL;
4492                                 tx->currentmaterialflags = tx->basematerialflags;
4493                                 loadmodel->num_texturesperskin++;
4494                                 loadmodel->num_textures = loadmodel->num_texturesperskin;
4495                         }
4496                         else
4497                         {
4498                                 Con_Printf("Mod_Q2BSP_LoadTexinfo: max textures reached (%i)\n", maxtextures);
4499                                 j = 0; // use first texture and give up
4500                         }
4501                 }
4502                 // store the index we found for this texture
4503                 out->textureindex = j;
4504         }
4505
4506         // realloc the textures array now that we know how many we actually need
4507         loadmodel->data_textures = (texture_t*)Mem_Realloc(loadmodel->mempool, loadmodel->data_textures, loadmodel->num_texturesperskin * sizeof(texture_t));
4508
4509         // now assemble the texture chains
4510         // if we encounter the textures out of order, the later ones won't mark the earlier ones in a sequence, so the earlier 
4511         for (i = 0, out = loadmodel->brushq1.texinfo;i < count;i++, out++)
4512         {
4513                 int j, k;
4514                 texture_t *t = loadmodel->data_textures + out->textureindex;
4515                 t->currentframe = t; // fix the reallocated pointer
4516
4517                 // if this is not animated, skip it
4518                 // if this is already processed, skip it (part of an existing sequence)
4519                 if (out->q2nexttexinfo == 0 || t->animated)
4520                         continue;
4521
4522                 // store the array of frames to use
4523                 t->animated = 2; // q2bsp animation
4524                 t->anim_total[0] = 0;
4525                 t->anim_total[1] = 0;
4526                 // gather up to 10 frames (we don't support more)
4527                 for (j = i;j >= 0 && t->anim_total[0] < (int)(sizeof(t->anim_frames[0])/sizeof(t->anim_frames[0][0]));j = loadmodel->brushq1.texinfo[j].q2nexttexinfo)
4528                 {
4529                         // detect looping and stop there
4530                         if (t->anim_total[0] && loadmodel->brushq1.texinfo[j].textureindex == out->textureindex)
4531                                 break;
4532                         t->anim_frames[0][t->anim_total[0]++] = &loadmodel->data_textures[loadmodel->brushq1.texinfo[j].textureindex];
4533                 }
4534                 // we could look for the +a sequence here if this is the +0 sequence,
4535                 // but it seems that quake2 did not implement that (even though the
4536                 // files exist in the baseq2 content)
4537
4538                 // write the frame sequence to all the textures involved (just like
4539                 // in the q1bsp loader)
4540                 //
4541                 // note that this can overwrite the rest of the sequence - so if the
4542                 // start of a sequence is found later than the other parts of the
4543                 // sequence, it will go back and rewrite them correctly.
4544                 for (k = 0;k < t->anim_total[0];k++)
4545                 {
4546                         texture_t *txk = t->anim_frames[0][k];
4547                         txk->animated = t->animated;
4548                         txk->anim_total[0] = t->anim_total[0];
4549                         for (l = 0;l < t->anim_total[0];l++)
4550                                 txk->anim_frames[0][l] = t->anim_frames[0][l];
4551                 }
4552         }
4553 }
4554
4555 static void Mod_Q2BSP_LoadLighting(sizebuf_t *sb)
4556 {
4557         // LadyHavoc: this fits exactly the same format that we use in .lit files
4558         loadmodel->brushq1.lightdata = (unsigned char *)Mem_Alloc(loadmodel->mempool, sb->cursize);
4559         MSG_ReadBytes(sb, sb->cursize, loadmodel->brushq1.lightdata);
4560 }
4561
4562 static void Mod_Q2BSP_LoadLeafs(sizebuf_t *sb)
4563 {
4564         mleaf_t *out;
4565         int i, j, count, firstmarksurface, nummarksurfaces, firstmarkbrush, nummarkbrushes;
4566         int structsize = 28;
4567
4568         if (sb->cursize % structsize)
4569                 Host_Error("Mod_Q2BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
4570         count = sb->cursize / structsize;
4571         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
4572
4573         loadmodel->brush.data_leafs = out;
4574         loadmodel->brush.num_leafs = count;
4575
4576         // FIXME: this function could really benefit from some error checking
4577         for ( i=0 ; i<count ; i++, out++)
4578         {
4579                 out->contents = MSG_ReadLittleLong(sb);
4580                 out->clusterindex = MSG_ReadLittleShort(sb);
4581                 out->areaindex = MSG_ReadLittleShort(sb);
4582                 out->mins[0] = MSG_ReadLittleShort(sb);
4583                 out->mins[1] = MSG_ReadLittleShort(sb);
4584                 out->mins[2] = MSG_ReadLittleShort(sb);
4585                 out->maxs[0] = MSG_ReadLittleShort(sb);
4586                 out->maxs[1] = MSG_ReadLittleShort(sb);
4587                 out->maxs[2] = MSG_ReadLittleShort(sb);
4588         
4589                 firstmarksurface = (unsigned short)MSG_ReadLittleShort(sb);
4590                 nummarksurfaces  = (unsigned short)MSG_ReadLittleShort(sb);
4591                 firstmarkbrush = (unsigned short)MSG_ReadLittleShort(sb);
4592                 nummarkbrushes  = (unsigned short)MSG_ReadLittleShort(sb);
4593
4594                 for (j = 0;j < 4;j++)
4595                         out->ambient_sound_level[j] = 0;
4596
4597                 if (out->clusterindex >= loadmodel->brush.num_pvsclusters)
4598                 {
4599                         Con_Print("Mod_Q2BSP_LoadLeafs: invalid clusterindex\n");
4600                         out->clusterindex = -1;
4601                 }
4602
4603                 if (firstmarksurface >= 0 && firstmarksurface + nummarksurfaces <= loadmodel->brush.num_leafsurfaces)
4604                 {
4605                         out->firstleafsurface = loadmodel->brush.data_leafsurfaces + firstmarksurface;
4606                         out->numleafsurfaces = nummarksurfaces;
4607                 }
4608                 else
4609                 {
4610                         Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafsurface range %i:%i outside range %i:%i\n", firstmarksurface, firstmarksurface+nummarksurfaces, 0, loadmodel->brush.num_leafsurfaces);
4611                         out->firstleafsurface = NULL;
4612                         out->numleafsurfaces = 0;
4613                 }
4614
4615                 if (firstmarkbrush >= 0 && firstmarkbrush + nummarkbrushes <= loadmodel->brush.num_leafbrushes)
4616                 {
4617                         out->firstleafbrush = loadmodel->brush.data_leafbrushes + firstmarkbrush;
4618                         out->numleafbrushes = nummarkbrushes;
4619                 }
4620                 else
4621                 {
4622                         Con_Printf("Mod_Q2BSP_LoadLeafs: invalid leafbrush range %i:%i outside range %i:%i\n", firstmarkbrush, firstmarkbrush+nummarkbrushes, 0, loadmodel->brush.num_leafbrushes);
4623                         out->firstleafbrush = NULL;
4624                         out->numleafbrushes = 0;
4625                 }
4626         }
4627 }
4628
4629 static void Mod_Q2BSP_LoadLeafBrushes(sizebuf_t *sb)
4630 {
4631         int i, j;
4632         int structsize = 2;
4633
4634         if (sb->cursize % structsize)
4635                 Host_Error("Mod_Q2BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
4636         loadmodel->brush.num_leafbrushes = sb->cursize / structsize;
4637         loadmodel->brush.data_leafbrushes = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafbrushes * sizeof(int));
4638
4639         for (i = 0;i < loadmodel->brush.num_leafbrushes;i++)
4640         {
4641                 j = (unsigned short) MSG_ReadLittleShort(sb);
4642                 if (j >= loadmodel->brush.num_brushes)
4643                         Host_Error("Mod_Q1BSP_LoadLeafBrushes: bad brush number");
4644                 loadmodel->brush.data_leafbrushes[i] = j;
4645         }
4646 }
4647
4648 static void Mod_Q2BSP_LoadBrushSides(sizebuf_t *sb)
4649 {
4650         q3mbrushside_t *out;
4651         int i, n, count;
4652         int structsize = 4;
4653
4654         if (sb->cursize % structsize)
4655                 Host_Error("Mod_Q2BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
4656         count = sb->cursize / structsize;
4657         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4658
4659         loadmodel->brush.data_brushsides = out;
4660         loadmodel->brush.num_brushsides = count;
4661
4662         for (i = 0;i < count;i++, out++)
4663         {
4664                 n = (unsigned short)MSG_ReadLittleShort(sb);
4665                 if (n < 0 || n >= loadmodel->brush.num_planes)
4666                         Host_Error("Mod_Q2BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
4667                 out->plane = loadmodel->brush.data_planes + n;
4668                 n = MSG_ReadLittleShort(sb);
4669                 if (n >= 0)
4670                 {
4671                         if (n >= loadmodel->brushq1.numtexinfo)
4672                                 Host_Error("Mod_Q2BSP_LoadBrushSides: invalid texinfo index %i (%i texinfos)", n, loadmodel->brushq1.numtexinfo);
4673                         out->texture = loadmodel->data_textures + loadmodel->brushq1.texinfo[n].textureindex;
4674                 }
4675                 else
4676                 {
4677                         //Con_Printf("Mod_Q2BSP_LoadBrushSides: brushside %i has texinfo index %i < 0, changing to generic texture!\n", i, n);
4678                         out->texture = &mod_q1bsp_texture_solid;
4679                 }
4680         }
4681 }
4682
4683 static void Mod_Q2BSP_LoadBrushes(sizebuf_t *sb)
4684 {
4685         q3mbrush_t *out;
4686         int i, j, firstside, numsides, contents, count, maxplanes, q3surfaceflags, supercontents;
4687         colplanef_t *planes;
4688         int structsize = 12;
4689         qbool brushmissingtextures;
4690         int numbrushesmissingtextures = 0;
4691         int numcreatedtextures = 0;
4692
4693         if (sb->cursize % structsize)
4694                 Host_Error("Mod_Q2BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
4695         count = sb->cursize / structsize;
4696         out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
4697
4698         loadmodel->brush.data_brushes = out;
4699         loadmodel->brush.num_brushes = count;
4700
4701         maxplanes = 0;
4702         planes = NULL;
4703
4704         for (i = 0; i < count; i++, out++)
4705         {
4706                 firstside = MSG_ReadLittleLong(sb);
4707                 numsides = MSG_ReadLittleLong(sb);
4708                 contents = MSG_ReadLittleLong(sb);
4709                 if (firstside < 0 || firstside + numsides > loadmodel->brush.num_brushsides)
4710                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", firstside, firstside + numsides, loadmodel->brush.num_brushsides);
4711
4712                 out->firstbrushside = loadmodel->brush.data_brushsides + firstside;
4713                 out->numbrushsides = numsides;
4714                 // convert the contents to our values
4715                 supercontents = Mod_Q2BSP_SuperContentsFromNativeContents(contents);
4716
4717                 // problem: q2bsp brushes have contents but not a texture
4718                 // problem: q2bsp brushsides *may* have a texture or may not
4719                 // problem: all brushsides and brushes must have a texture for trace_hittexture functionality to work, and the collision code is engineered around this assumption
4720                 // solution: nasty hacks
4721                 brushmissingtextures = false;
4722                 out->texture = NULL;
4723                 for (j = 0; j < out->numbrushsides; j++)
4724                 {
4725                         if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4726                                 brushmissingtextures = true;
4727                         else
4728                         {
4729                                 // if we can find a matching texture on a brush side we can use it instead of creating one
4730                                 if (out->firstbrushside[j].texture->supercontents == supercontents)
4731                                         out->texture = out->firstbrushside[j].texture;
4732                         }
4733                 }
4734                 if (brushmissingtextures || out->texture == NULL)
4735                 {
4736                         numbrushesmissingtextures++;
4737                         // if we didn't find any appropriate texture (matching contents), we'll have to create one
4738                         // we could search earlier ones for a matching one but that can be slow
4739                         if (out->texture == NULL)
4740                         {
4741                                 texture_t *validtexture;
4742                                 validtexture = (texture_t *)Mem_Alloc(loadmodel->mempool, sizeof(texture_t));
4743                                 dpsnprintf(validtexture->name, sizeof(validtexture->name), "brushcollision%i", numcreatedtextures);
4744                                 validtexture->surfaceflags = 0;
4745                                 validtexture->supercontents = supercontents;
4746                                 numcreatedtextures++;
4747                                 out->texture = validtexture;
4748                         }
4749                         // out->texture now contains a texture with appropriate contents, copy onto any missing sides
4750                         for (j = 0; j < out->numbrushsides; j++)
4751                                 if (out->firstbrushside[j].texture == &mod_q1bsp_texture_solid)
4752                                         out->firstbrushside[j].texture = out->texture;
4753                 }
4754
4755                 // make a colbrush from the brush
4756                 q3surfaceflags = 0;
4757                 // make a list of mplane_t structs to construct a colbrush from
4758                 if (maxplanes < out->numbrushsides)
4759                 {
4760                         maxplanes = out->numbrushsides;
4761                         if (planes)
4762                                 Mem_Free(planes);
4763                         planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
4764                 }
4765                 for (j = 0;j < out->numbrushsides;j++)
4766                 {
4767                         VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
4768                         planes[j].dist = out->firstbrushside[j].plane->dist;
4769                         planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
4770                         planes[j].texture = out->firstbrushside[j].texture;
4771                         q3surfaceflags |= planes[j].q3surfaceflags;
4772                 }
4773                 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
4774
4775                 // this whole loop can take a while (e.g. on redstarrepublic4)
4776                 CL_KeepaliveMessage(false);
4777         }
4778         if (planes)
4779                 Mem_Free(planes);
4780         if (numcreatedtextures)
4781                 Con_DPrintf("Mod_Q2BSP_LoadBrushes: %i brushes own sides that lack textures or have differing contents from the brush, %i textures have been created to describe these contents.\n", numbrushesmissingtextures, numcreatedtextures);
4782 }
4783
4784 static void Mod_Q2BSP_LoadPOP(sizebuf_t *sb)
4785 {
4786         // this is probably a "proof of purchase" lump of some sort, it seems to be 0 size in most bsp files (but not q2dm1.bsp for instance)
4787         sb->readcount = sb->cursize;
4788 }
4789
4790 static void Mod_Q2BSP_LoadAreas(sizebuf_t *sb)
4791 {
4792         // we currently don't use areas, they represent closable doors as vis blockers
4793         sb->readcount = sb->cursize;
4794 }
4795
4796 static void Mod_Q2BSP_LoadAreaPortals(sizebuf_t *sb)
4797 {
4798         // we currently don't use areas, they represent closable doors as vis blockers
4799         sb->readcount = sb->cursize;
4800 }
4801
4802 static void Mod_Q2BSP_FindSubmodelBrushRange_r(model_t *mod, mnode_t *node, int *first, int *last)
4803 {
4804         int i;
4805         mleaf_t *leaf;
4806         while (node->plane)
4807         {
4808                 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, node->children[0], first, last);
4809                 node = node->children[1];
4810         }
4811         leaf = (mleaf_t*)node;
4812         for (i = 0;i < leaf->numleafbrushes;i++)
4813         {
4814                 int brushnum = leaf->firstleafbrush[i];
4815                 if (*first > brushnum)
4816                         *first = brushnum;
4817                 if (*last < brushnum)
4818                         *last = brushnum;
4819         }
4820 }
4821
4822 static void Mod_Q2BSP_Load(model_t *mod, void *buffer, void *bufferend)
4823 {
4824         int i, j, k;
4825         sizebuf_t lumpsb[Q2HEADER_LUMPS];
4826         mmodel_t *bm;
4827         float dist, modelyawradius, modelradius;
4828         msurface_t *surface;
4829         int totalstylesurfaces, totalstyles, stylecounts[256], remapstyles[256];
4830         model_brush_lightstyleinfo_t styleinfo[256];
4831         int *datapointer;
4832         model_brush_lightstyleinfo_t *lsidatapointer;
4833         sizebuf_t sb;
4834
4835         MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
4836
4837         mod->type = mod_brushq2;
4838
4839         mod->brush.ishlbsp = false;
4840         mod->brush.isbsp2rmqe = false;
4841         mod->brush.isbsp2 = false;
4842         mod->brush.isq2bsp = true; // q1bsp loaders mostly work but we need a few tweaks
4843         mod->brush.isq3bsp = false;
4844         mod->brush.skymasking = true;
4845         mod->modeldatatypestring = "Q2BSP";
4846
4847         i = MSG_ReadLittleLong(&sb);
4848         if (i != Q2BSPMAGIC)
4849                 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4850
4851         i = MSG_ReadLittleLong(&sb);
4852         if (i != Q2BSPVERSION)
4853                 Host_Error("Mod_Q2BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q2BSPVERSION);
4854
4855 // read lumps
4856         for (i = 0; i < Q2HEADER_LUMPS; i++)
4857         {
4858                 int offset = MSG_ReadLittleLong(&sb);
4859                 int size = MSG_ReadLittleLong(&sb);
4860                 if (offset < 0 || offset + size > sb.cursize)
4861                         Host_Error("Mod_Q2BSP_Load: %s has invalid lump %i (offset %i, size %i, file size %i)\n", mod->name, i, offset, size, (int)sb.cursize);
4862                 MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
4863         }
4864
4865         mod->soundfromcenter = true;
4866         mod->TracePoint = Mod_CollisionBIH_TracePoint;
4867         mod->TraceLine = Mod_CollisionBIH_TraceLine;
4868         mod->TraceBox = Mod_CollisionBIH_TraceBox;
4869         mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
4870         mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
4871         mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
4872         mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
4873         mod->brush.SuperContentsFromNativeContents = Mod_Q2BSP_SuperContentsFromNativeContents;
4874         mod->brush.NativeContentsFromSuperContents = Mod_Q2BSP_NativeContentsFromSuperContents;
4875         mod->brush.GetPVS = Mod_BSP_GetPVS;
4876         mod->brush.FatPVS = Mod_BSP_FatPVS;
4877         mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
4878         mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
4879         mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
4880         mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
4881         mod->brush.LightPoint = Mod_BSP_LightPoint;
4882         mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
4883         mod->brush.AmbientSoundLevelsForPoint = NULL;
4884         mod->brush.RoundUpToHullSize = NULL;
4885         mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
4886         mod->Draw = R_Mod_Draw;
4887         mod->DrawDepth = R_Mod_DrawDepth;
4888         mod->DrawDebug = R_Mod_DrawDebug;
4889         mod->DrawPrepass = R_Mod_DrawPrepass;
4890         mod->GetLightInfo = R_Mod_GetLightInfo;
4891         mod->CompileShadowMap = R_Mod_CompileShadowMap;
4892         mod->DrawShadowMap = R_Mod_DrawShadowMap;
4893         mod->DrawLight = R_Mod_DrawLight;
4894
4895 // load into heap
4896
4897         mod->brush.qw_md4sum = 0;
4898         mod->brush.qw_md4sum2 = 0;
4899         for (i = 0;i < Q2HEADER_LUMPS;i++)
4900         {
4901                 int temp;
4902                 if (i == Q2LUMP_ENTITIES)
4903                         continue;
4904                 temp = Com_BlockChecksum(lumpsb[i].data, lumpsb[i].cursize);
4905                 mod->brush.qw_md4sum ^= LittleLong(temp);
4906                 if (i == Q2LUMP_VISIBILITY || i == Q2LUMP_LEAFS || i == Q2LUMP_NODES)
4907                         continue;
4908                 mod->brush.qw_md4sum2 ^= LittleLong(temp);
4909         }
4910
4911         // many of these functions are identical to Q1 loaders, so we use those where possible
4912         Mod_Q1BSP_LoadEntities(&lumpsb[Q2LUMP_ENTITIES]);
4913         Mod_Q1BSP_LoadVertexes(&lumpsb[Q2LUMP_VERTEXES]);
4914         Mod_Q1BSP_LoadEdges(&lumpsb[Q2LUMP_EDGES]);
4915         Mod_Q1BSP_LoadSurfedges(&lumpsb[Q2LUMP_SURFEDGES]);
4916         Mod_Q2BSP_LoadLighting(&lumpsb[Q2LUMP_LIGHTING]);
4917         Mod_Q1BSP_LoadPlanes(&lumpsb[Q2LUMP_PLANES]);
4918         Mod_Q2BSP_LoadTexinfo(&lumpsb[Q2LUMP_TEXINFO]);
4919         Mod_Q2BSP_LoadBrushSides(&lumpsb[Q2LUMP_BRUSHSIDES]);
4920         Mod_Q2BSP_LoadBrushes(&lumpsb[Q2LUMP_BRUSHES]);
4921         Mod_Q1BSP_LoadFaces(&lumpsb[Q2LUMP_FACES]);
4922         Mod_Q1BSP_LoadLeaffaces(&lumpsb[Q2LUMP_LEAFFACES]);
4923         Mod_Q2BSP_LoadLeafBrushes(&lumpsb[Q2LUMP_LEAFBRUSHES]);
4924         Mod_Q2BSP_LoadVisibility(&lumpsb[Q2LUMP_VISIBILITY]);
4925         Mod_Q2BSP_LoadPOP(&lumpsb[Q2LUMP_POP]);
4926         Mod_Q2BSP_LoadAreas(&lumpsb[Q2LUMP_AREAS]);
4927         Mod_Q2BSP_LoadAreaPortals(&lumpsb[Q2LUMP_AREAPORTALS]);
4928         Mod_Q2BSP_LoadLeafs(&lumpsb[Q2LUMP_LEAFS]);
4929         Mod_Q2BSP_LoadNodes(&lumpsb[Q2LUMP_NODES]);
4930         Mod_BSP_LoadSubmodels(&lumpsb[Q2LUMP_MODELS], NULL);
4931
4932         for (i = 0; i < Q2HEADER_LUMPS; i++)
4933                 if (lumpsb[i].readcount != lumpsb[i].cursize)
4934                         Host_Error("Lump %i incorrectly loaded (readcount %i, size %i)\n", i, lumpsb[i].readcount, lumpsb[i].cursize);
4935
4936         // we don't actually set MATERIALFLAG_WATERALPHA on anything, so this
4937         // doesn't enable the cvar, just indicates that transparent water is OK
4938         loadmodel->brush.supportwateralpha = true;
4939
4940         // we don't need the compressed pvs data anymore
4941         if (mod->brushq1.data_compressedpvs)
4942                 Mem_Free(mod->brushq1.data_compressedpvs);
4943         mod->brushq1.data_compressedpvs = NULL;
4944         mod->brushq1.num_compressedpvs = 0;
4945
4946         // the MakePortals code works fine on the q2bsp data as well
4947         if (mod_bsp_portalize.integer && cls.state != ca_dedicated)
4948                 Mod_BSP_MakePortals();
4949
4950         mod->numframes = 0;             // q2bsp animations are kind of special, frame is unbounded...
4951         mod->numskins = 1;
4952
4953         if (loadmodel->brush.numsubmodels)
4954                 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
4955
4956         totalstylesurfaces = 0;
4957         totalstyles = 0;
4958         for (i = 0;i < mod->brush.numsubmodels;i++)
4959         {
4960                 memset(stylecounts, 0, sizeof(stylecounts));
4961                 for (k = 0;k < mod->brushq1.submodels[i].numfaces;k++)
4962                 {
4963                         surface = mod->data_surfaces + mod->brushq1.submodels[i].firstface + k;
4964                         for (j = 0;j < MAXLIGHTMAPS;j++)
4965                                 stylecounts[surface->lightmapinfo->styles[j]]++;
4966                 }
4967                 for (k = 0;k < 255;k++)
4968                 {
4969                         totalstyles++;
4970                         if (stylecounts[k])
4971                                 totalstylesurfaces += stylecounts[k];
4972                 }
4973         }
4974         // bones_was_here: using a separate allocation for model_brush_lightstyleinfo_t
4975         // because on a 64-bit machine it no longer has the same alignment requirement as int.
4976         lsidatapointer = Mem_AllocType(mod->mempool, model_brush_lightstyleinfo_t, totalstyles * sizeof(model_brush_lightstyleinfo_t));
4977         datapointer = Mem_AllocType(mod->mempool, int, mod->num_surfaces * sizeof(int) + totalstylesurfaces * sizeof(int));
4978         mod->modelsurfaces_sorted = datapointer; datapointer += mod->num_surfaces;
4979         // set up the world model, then on each submodel copy from the world model
4980         // and set up the submodel with the respective model info.
4981         mod = loadmodel;
4982         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
4983         {
4984                 mnode_t *rootnode = NULL;
4985                 int firstbrush = loadmodel->brush.num_brushes, lastbrush = 0;
4986                 if (i > 0)
4987                 {
4988                         char name[10];
4989                         // duplicate the basic information
4990                         dpsnprintf(name, sizeof(name), "*%i", i);
4991                         mod = Mod_FindName(name, loadmodel->name);
4992                         // copy the base model to this one
4993                         *mod = *loadmodel;
4994                         // rename the clone back to its proper name
4995                         dp_strlcpy(mod->name, name, sizeof(mod->name));
4996                         mod->brush.parentmodel = loadmodel;
4997                         // textures and memory belong to the main model
4998                         mod->texturepool = NULL;
4999                         mod->mempool = NULL;
5000                         mod->brush.GetPVS = NULL;
5001                         mod->brush.FatPVS = NULL;
5002                         mod->brush.BoxTouchingPVS = NULL;
5003                         mod->brush.BoxTouchingLeafPVS = NULL;
5004                         mod->brush.BoxTouchingVisibleLeafs = NULL;
5005                         mod->brush.FindBoxClusters = NULL;
5006                         mod->brush.LightPoint = NULL;
5007                         mod->brush.AmbientSoundLevelsForPoint = NULL;
5008                 }
5009                 mod->brush.submodel = i;
5010                 if (loadmodel->brush.submodels)
5011                         loadmodel->brush.submodels[i] = mod;
5012
5013                 bm = &mod->brushq1.submodels[i];
5014
5015                 // we store the headnode (there's only one in Q2BSP) as if it were the first hull
5016                 mod->brushq1.hulls[0].firstclipnode = bm->headnode[0];
5017
5018                 mod->submodelsurfaces_start = bm->firstface;
5019                 mod->submodelsurfaces_end = bm->firstface + bm->numfaces;
5020
5021                 // set node/leaf parents for this submodel
5022                 // note: if the root of this submodel is a leaf (headnode[0] < 0) then there is nothing to do...
5023                 // (this happens in base3.bsp)
5024                 if (bm->headnode[0] >= 0)
5025                         rootnode = mod->brush.data_nodes + bm->headnode[0];
5026                 else
5027                         rootnode = (mnode_t*)(mod->brush.data_leafs + -1 - bm->headnode[0]);
5028                 Mod_BSP_LoadNodes_RecursiveSetParent(rootnode, NULL);
5029
5030                 // make the model surface list (used by shadowing/lighting)
5031                 Mod_Q2BSP_FindSubmodelBrushRange_r(mod, rootnode, &firstbrush, &lastbrush);
5032                 if (firstbrush <= lastbrush)
5033                 {
5034                         mod->firstmodelbrush = firstbrush;
5035                         mod->nummodelbrushes = lastbrush + 1 - firstbrush;
5036                 }
5037                 else
5038                 {
5039                         mod->firstmodelbrush = 0;
5040                         mod->nummodelbrushes = 0;
5041                 }
5042
5043                 VectorCopy(bm->mins, mod->normalmins);
5044                 VectorCopy(bm->maxs, mod->normalmaxs);
5045                 dist = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
5046                 modelyawradius = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
5047                 modelyawradius = dist*dist+modelyawradius*modelyawradius;
5048                 modelradius = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
5049                 modelradius = modelyawradius + modelradius * modelradius;
5050                 modelyawradius = sqrt(modelyawradius);
5051                 modelradius = sqrt(modelradius);
5052                 mod->yawmins[0] = mod->yawmins[1] = -modelyawradius;
5053                 mod->yawmins[2] = mod->normalmins[2];
5054                 mod->yawmaxs[0] = mod->yawmaxs[1] =  modelyawradius;
5055                 mod->yawmaxs[2] = mod->normalmaxs[2];
5056                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
5057                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] =  modelradius;
5058                 mod->radius = modelradius;
5059                 mod->radius2 = modelradius * modelradius;
5060
5061                 Mod_SetDrawSkyAndWater(mod);
5062
5063                 // build lightstyle lists for quick marking of dirty lightmaps when lightstyles flicker
5064                 if (mod->submodelsurfaces_start < mod->submodelsurfaces_end)
5065                 {
5066                         // build lightstyle update chains
5067                         // (used to rapidly mark lightmapupdateflags on many surfaces
5068                         // when d_lightstylevalue changes)
5069                         memset(stylecounts, 0, sizeof(stylecounts));
5070                         for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
5071                                 for (j = 0;j < MAXLIGHTMAPS;j++)
5072                                         stylecounts[mod->data_surfaces[k].lightmapinfo->styles[j]]++;
5073                         mod->brushq1.num_lightstyles = 0;
5074                         for (k = 0;k < 255;k++)
5075                         {
5076                                 if (stylecounts[k])
5077                                 {
5078                                         styleinfo[mod->brushq1.num_lightstyles].style = k;
5079                                         styleinfo[mod->brushq1.num_lightstyles].value = 0;
5080                                         styleinfo[mod->brushq1.num_lightstyles].numsurfaces = 0;
5081                                         styleinfo[mod->brushq1.num_lightstyles].surfacelist = datapointer;datapointer += stylecounts[k];
5082                                         remapstyles[k] = mod->brushq1.num_lightstyles;
5083                                         mod->brushq1.num_lightstyles++;
5084                                 }
5085                         }
5086                         for (k = mod->submodelsurfaces_start;k < mod->submodelsurfaces_end;k++)
5087                         {
5088                                 surface = mod->data_surfaces + k;
5089                                 for (j = 0;j < MAXLIGHTMAPS;j++)
5090                                 {
5091                                         if (surface->lightmapinfo->styles[j] != 255)
5092                                         {
5093                                                 int r = remapstyles[surface->lightmapinfo->styles[j]];
5094                                                 styleinfo[r].surfacelist[styleinfo[r].numsurfaces++] = k;
5095                                         }
5096                                 }
5097                         }
5098                         mod->brushq1.data_lightstyleinfo = lsidatapointer;lsidatapointer += mod->brushq1.num_lightstyles;
5099                         memcpy(mod->brushq1.data_lightstyleinfo, styleinfo, mod->brushq1.num_lightstyles * sizeof(model_brush_lightstyleinfo_t));
5100                 }
5101                 else
5102                 {
5103                         Con_Printf(CON_WARN "warning: empty submodel *%i in %s\n", i+1, loadmodel->name);
5104                 }
5105                 //mod->brushq1.num_visleafs = bm->visleafs;
5106
5107                 // build a Bounding Interval Hierarchy for culling triangles in light rendering
5108                 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
5109
5110                 // build a Bounding Interval Hierarchy for culling brushes in collision detection
5111                 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
5112
5113                 // generate VBOs and other shared data before cloning submodels
5114                 if (i == 0)
5115                         Mod_BuildVBOs();
5116         }
5117         mod = loadmodel;
5118
5119         // make the model surface list (used by shadowing/lighting)
5120         Mod_MakeSortedSurfaces(loadmodel);
5121
5122         Con_DPrintf("Stats for q2bsp model \"%s\": %i faces, %i nodes, %i leafs, %i clusters, %i clusterportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
5123 }
5124
5125 static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents);
5126 static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents);
5127
5128 static void Mod_Q3BSP_LoadEntities(lump_t *l)
5129 {
5130         const char *data;
5131         char key[128], value[MAX_INPUTLINE];
5132         float v[3];
5133         loadmodel->brushq3.num_lightgrid_cellsize[0] = 64;
5134         loadmodel->brushq3.num_lightgrid_cellsize[1] = 64;
5135         loadmodel->brushq3.num_lightgrid_cellsize[2] = 128;
5136         if (!l->filelen)
5137                 return;
5138         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, l->filelen + 1);
5139         memcpy(loadmodel->brush.entities, mod_base + l->fileofs, l->filelen);
5140         loadmodel->brush.entities[l->filelen] = 0;
5141         data = loadmodel->brush.entities;
5142         // some Q3 maps override the lightgrid_cellsize with a worldspawn key
5143         // VorteX: q3map2 FS-R generates tangentspace deluxemaps for q3bsp and sets 'deluxeMaps' key
5144         loadmodel->brushq3.deluxemapping = false;
5145         if (data && COM_ParseToken_Simple(&data, false, false, true) && com_token[0] == '{')
5146         {
5147                 while (1)
5148                 {
5149                         if (!COM_ParseToken_Simple(&data, false, false, true))
5150                                 break; // error
5151                         if (com_token[0] == '}')
5152                                 break; // end of worldspawn
5153                         if (com_token[0] == '_')
5154                                 dp_strlcpy(key, com_token + 1, sizeof(key));
5155                         else
5156                                 dp_strlcpy(key, com_token, sizeof(key));
5157                         while (key[strlen(key)-1] == ' ') // remove trailing spaces
5158                                 key[strlen(key)-1] = 0;
5159                         if (!COM_ParseToken_Simple(&data, false, false, true))
5160                                 break; // error
5161                         dp_strlcpy(value, com_token, sizeof(value));
5162                         if (!strcasecmp("gridsize", key)) // this one is case insensitive to 100% match q3map2
5163                         {
5164 #if _MSC_VER >= 1400
5165 #define sscanf sscanf_s
5166 #endif
5167 #if 0
5168                                 if (sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) == 3 && v[0] != 0 && v[1] != 0 && v[2] != 0)
5169                                         VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5170 #else
5171                                 VectorSet(v, 64, 64, 128);
5172                                 if(sscanf(value, "%f %f %f", &v[0], &v[1], &v[2]) != 3)
5173                                         Con_Printf("Mod_Q3BSP_LoadEntities: funny gridsize \"%s\" in %s, interpreting as \"%f %f %f\" to match q3map2's parsing\n", value, loadmodel->name, v[0], v[1], v[2]);
5174                                 if (v[0] != 0 && v[1] != 0 && v[2] != 0)
5175                                         VectorCopy(v, loadmodel->brushq3.num_lightgrid_cellsize);
5176 #endif
5177                         }
5178                         else if (!strcmp("deluxeMaps", key))
5179                         {
5180                                 if (!strcmp(com_token, "1"))
5181                                 {
5182                                         loadmodel->brushq3.deluxemapping = true;
5183                                         loadmodel->brushq3.deluxemapping_modelspace = true;
5184                                 }
5185                                 else if (!strcmp(com_token, "2"))
5186                                 {
5187                                         loadmodel->brushq3.deluxemapping = true;
5188                                         loadmodel->brushq3.deluxemapping_modelspace = false;
5189                                 }
5190                         }
5191                 }
5192         }
5193 }
5194
5195 static void Mod_Q3BSP_LoadTextures(lump_t *l)
5196 {
5197         q3dtexture_t *in;
5198         texture_t *out;
5199         int i, count;
5200
5201         in = (q3dtexture_t *)(mod_base + l->fileofs);
5202         if (l->filelen % sizeof(*in))
5203                 Host_Error("Mod_Q3BSP_LoadTextures: funny lump size in %s",loadmodel->name);
5204         count = l->filelen / sizeof(*in);
5205         out = (texture_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5206
5207         loadmodel->data_textures = out;
5208         loadmodel->num_textures = count;
5209         loadmodel->num_texturesperskin = loadmodel->num_textures;
5210
5211         for (i = 0;i < count;i++)
5212         {
5213                 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5214                 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
5215                 Mod_LoadTextureFromQ3Shader(loadmodel->mempool, loadmodel->name, out + i, in[i].name, true, true, TEXF_MIPMAP | TEXF_ISWORLD | TEXF_PICMIP | TEXF_COMPRESS, MATERIALFLAG_WALL);
5216                 // restore the surfaceflags and supercontents
5217                 out[i].surfaceflags = LittleLong(in[i].surfaceflags);
5218                 out[i].supercontents = Mod_Q3BSP_SuperContentsFromNativeContents(LittleLong(in[i].contents));
5219         }
5220 }
5221
5222 static void Mod_Q3BSP_LoadPlanes(lump_t *l)
5223 {
5224         q3dplane_t *in;
5225         mplane_t *out;
5226         int i, count;
5227
5228         in = (q3dplane_t *)(mod_base + l->fileofs);
5229         if (l->filelen % sizeof(*in))
5230                 Host_Error("Mod_Q3BSP_LoadPlanes: funny lump size in %s",loadmodel->name);
5231         count = l->filelen / sizeof(*in);
5232         out = (mplane_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5233
5234         loadmodel->brush.data_planes = out;
5235         loadmodel->brush.num_planes = count;
5236
5237         for (i = 0;i < count;i++, in++, out++)
5238         {
5239                 out->normal[0] = LittleFloat(in->normal[0]);
5240                 out->normal[1] = LittleFloat(in->normal[1]);
5241                 out->normal[2] = LittleFloat(in->normal[2]);
5242                 out->dist = LittleFloat(in->dist);
5243                 PlaneClassify(out);
5244         }
5245 }
5246
5247 static void Mod_Q3BSP_LoadBrushSides(lump_t *l)
5248 {
5249         q3dbrushside_t *in;
5250         q3mbrushside_t *out;
5251         int i, n, count;
5252
5253         in = (q3dbrushside_t *)(mod_base + l->fileofs);
5254         if (l->filelen % sizeof(*in))
5255                 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5256         count = l->filelen / sizeof(*in);
5257         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5258
5259         loadmodel->brush.data_brushsides = out;
5260         loadmodel->brush.num_brushsides = count;
5261
5262         for (i = 0;i < count;i++, in++, out++)
5263         {
5264                 n = LittleLong(in->planeindex);
5265                 if (n < 0 || n >= loadmodel->brush.num_planes)
5266                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5267                 out->plane = loadmodel->brush.data_planes + n;
5268                 n = LittleLong(in->textureindex);
5269                 if (n < 0 || n >= loadmodel->num_textures)
5270                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5271                 out->texture = loadmodel->data_textures + n;
5272         }
5273 }
5274
5275 static void Mod_Q3BSP_LoadBrushSides_IG(lump_t *l)
5276 {
5277         q3dbrushside_ig_t *in;
5278         q3mbrushside_t *out;
5279         int i, n, count;
5280
5281         in = (q3dbrushside_ig_t *)(mod_base + l->fileofs);
5282         if (l->filelen % sizeof(*in))
5283                 Host_Error("Mod_Q3BSP_LoadBrushSides: funny lump size in %s",loadmodel->name);
5284         count = l->filelen / sizeof(*in);
5285         out = (q3mbrushside_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5286
5287         loadmodel->brush.data_brushsides = out;
5288         loadmodel->brush.num_brushsides = count;
5289
5290         for (i = 0;i < count;i++, in++, out++)
5291         {
5292                 n = LittleLong(in->planeindex);
5293                 if (n < 0 || n >= loadmodel->brush.num_planes)
5294                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
5295                 out->plane = loadmodel->brush.data_planes + n;
5296                 n = LittleLong(in->textureindex);
5297                 if (n < 0 || n >= loadmodel->num_textures)
5298                         Host_Error("Mod_Q3BSP_LoadBrushSides: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5299                 out->texture = loadmodel->data_textures + n;
5300         }
5301 }
5302
5303 static void Mod_Q3BSP_LoadBrushes(lump_t *l)
5304 {
5305         q3dbrush_t *in;
5306         q3mbrush_t *out;
5307         int i, j, n, c, count, maxplanes, q3surfaceflags;
5308         colplanef_t *planes;
5309
5310         in = (q3dbrush_t *)(mod_base + l->fileofs);
5311         if (l->filelen % sizeof(*in))
5312                 Host_Error("Mod_Q3BSP_LoadBrushes: funny lump size in %s",loadmodel->name);
5313         count = l->filelen / sizeof(*in);
5314         out = (q3mbrush_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5315
5316         loadmodel->brush.data_brushes = out;
5317         loadmodel->brush.num_brushes = count;
5318
5319         maxplanes = 0;
5320         planes = NULL;
5321
5322         for (i = 0;i < count;i++, in++, out++)
5323         {
5324                 n = LittleLong(in->firstbrushside);
5325                 c = LittleLong(in->numbrushsides);
5326                 if (n < 0 || n + c > loadmodel->brush.num_brushsides)
5327                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid brushside range %i : %i (%i brushsides)", n, n + c, loadmodel->brush.num_brushsides);
5328                 out->firstbrushside = loadmodel->brush.data_brushsides + n;
5329                 out->numbrushsides = c;
5330                 n = LittleLong(in->textureindex);
5331                 if (n < 0 || n >= loadmodel->num_textures)
5332                         Host_Error("Mod_Q3BSP_LoadBrushes: invalid textureindex %i (%i textures)", n, loadmodel->num_textures);
5333                 out->texture = loadmodel->data_textures + n;
5334
5335                 // make a list of mplane_t structs to construct a colbrush from
5336                 if (maxplanes < out->numbrushsides)
5337                 {
5338                         maxplanes = out->numbrushsides;
5339                         if (planes)
5340                                 Mem_Free(planes);
5341                         planes = (colplanef_t *)Mem_Alloc(tempmempool, sizeof(colplanef_t) * maxplanes);
5342                 }
5343                 q3surfaceflags = 0;
5344                 for (j = 0;j < out->numbrushsides;j++)
5345                 {
5346                         VectorCopy(out->firstbrushside[j].plane->normal, planes[j].normal);
5347                         planes[j].dist = out->firstbrushside[j].plane->dist;
5348                         planes[j].q3surfaceflags = out->firstbrushside[j].texture->surfaceflags;
5349                         planes[j].texture = out->firstbrushside[j].texture;
5350                         q3surfaceflags |= planes[j].q3surfaceflags;
5351                 }
5352                 // make the colbrush from the planes
5353                 out->colbrushf = Collision_NewBrushFromPlanes(loadmodel->mempool, out->numbrushsides, planes, out->texture->supercontents, q3surfaceflags, out->texture, true);
5354
5355                 // this whole loop can take a while (e.g. on redstarrepublic4)
5356                 CL_KeepaliveMessage(false);
5357         }
5358         if (planes)
5359                 Mem_Free(planes);
5360 }
5361
5362 static void Mod_Q3BSP_LoadEffects(lump_t *l)
5363 {
5364         q3deffect_t *in;
5365         q3deffect_t *out;
5366         int i, n, count;
5367
5368         in = (q3deffect_t *)(mod_base + l->fileofs);
5369         if (l->filelen % sizeof(*in))
5370                 Host_Error("Mod_Q3BSP_LoadEffects: funny lump size in %s",loadmodel->name);
5371         count = l->filelen / sizeof(*in);
5372         out = (q3deffect_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5373
5374         loadmodel->brushq3.data_effects = out;
5375         loadmodel->brushq3.num_effects = count;
5376
5377         for (i = 0;i < count;i++, in++, out++)
5378         {
5379                 dp_strlcpy (out->shadername, in->shadername, sizeof (out->shadername));
5380                 n = LittleLong(in->brushindex);
5381                 if (n >= loadmodel->brush.num_brushes)
5382                 {
5383                         Con_Printf("Mod_Q3BSP_LoadEffects: invalid brushindex %i (%i brushes), setting to -1\n", n, loadmodel->brush.num_brushes);
5384                         n = -1;
5385                 }
5386                 out->brushindex = n;
5387                 out->unknown = LittleLong(in->unknown);
5388         }
5389 }
5390
5391 static void Mod_Q3BSP_LoadVertices(lump_t *l)
5392 {
5393         q3dvertex_t *in;
5394         int i, count;
5395
5396         in = (q3dvertex_t *)(mod_base + l->fileofs);
5397         if (l->filelen % sizeof(*in))
5398                 Host_Error("Mod_Q3BSP_LoadVertices: funny lump size in %s",loadmodel->name);
5399         loadmodel->brushq3.num_vertices = count = l->filelen / sizeof(*in);
5400         loadmodel->brushq3.data_vertex3f = (float *)Mem_Alloc(loadmodel->mempool, count * (sizeof(float) * (3 + 3 + 2 + 2 + 4)));
5401         loadmodel->brushq3.data_normal3f = loadmodel->brushq3.data_vertex3f + count * 3;
5402         loadmodel->brushq3.data_texcoordtexture2f = loadmodel->brushq3.data_normal3f + count * 3;
5403         loadmodel->brushq3.data_texcoordlightmap2f = loadmodel->brushq3.data_texcoordtexture2f + count * 2;
5404         loadmodel->brushq3.data_color4f = loadmodel->brushq3.data_texcoordlightmap2f + count * 2;
5405
5406         for (i = 0;i < count;i++, in++)
5407         {
5408                 loadmodel->brushq3.data_vertex3f[i * 3 + 0] = LittleFloat(in->origin3f[0]);
5409                 loadmodel->brushq3.data_vertex3f[i * 3 + 1] = LittleFloat(in->origin3f[1]);
5410                 loadmodel->brushq3.data_vertex3f[i * 3 + 2] = LittleFloat(in->origin3f[2]);
5411                 loadmodel->brushq3.data_normal3f[i * 3 + 0] = LittleFloat(in->normal3f[0]);
5412                 loadmodel->brushq3.data_normal3f[i * 3 + 1] = LittleFloat(in->normal3f[1]);
5413                 loadmodel->brushq3.data_normal3f[i * 3 + 2] = LittleFloat(in->normal3f[2]);
5414                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 0] = LittleFloat(in->texcoord2f[0]);
5415                 loadmodel->brushq3.data_texcoordtexture2f[i * 2 + 1] = LittleFloat(in->texcoord2f[1]);
5416                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 0] = LittleFloat(in->lightmap2f[0]);
5417                 loadmodel->brushq3.data_texcoordlightmap2f[i * 2 + 1] = LittleFloat(in->lightmap2f[1]);
5418                 // svector/tvector are calculated later in face loading
5419                 if(mod_q3bsp_sRGBlightmaps.integer)
5420                 {
5421                         // if lightmaps are sRGB, vertex colors are sRGB too, so we need to linearize them
5422                         // note: when this is in use, lightmap color 128 is no longer neutral, but "sRGB half power" is
5423                         // working like this may be odd, but matches q3map2 -gamma 2.2
5424                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5425                         {
5426                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5427                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5428                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5429                                 // we fix the brightness consistently via lightmapscale
5430                         }
5431                         else
5432                         {
5433                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_LinearFloatFromsRGB(in->color4ub[0]);
5434                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_LinearFloatFromsRGB(in->color4ub[1]);
5435                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_LinearFloatFromsRGB(in->color4ub[2]);
5436                         }
5437                 }
5438                 else
5439                 {
5440                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5441                         {
5442                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[0]);
5443                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[1]);
5444                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = Image_sRGBFloatFromLinear_Lightmap(in->color4ub[2]);
5445                         }
5446                         else
5447                         {
5448                                 loadmodel->brushq3.data_color4f[i * 4 + 0] = in->color4ub[0] * (1.0f / 255.0f);
5449                                 loadmodel->brushq3.data_color4f[i * 4 + 1] = in->color4ub[1] * (1.0f / 255.0f);
5450                                 loadmodel->brushq3.data_color4f[i * 4 + 2] = in->color4ub[2] * (1.0f / 255.0f);
5451                         }
5452                 }
5453                 loadmodel->brushq3.data_color4f[i * 4 + 3] = in->color4ub[3] * (1.0f / 255.0f);
5454                 if(in->color4ub[0] != 255 || in->color4ub[1] != 255 || in->color4ub[2] != 255)
5455                         loadmodel->lit = true;
5456         }
5457 }
5458
5459 static void Mod_Q3BSP_LoadTriangles(lump_t *l)
5460 {
5461         int *in;
5462         int *out;
5463         int i, count;
5464
5465         in = (int *)(mod_base + l->fileofs);
5466         if (l->filelen % sizeof(int[3]))
5467                 Host_Error("Mod_Q3BSP_LoadTriangles: funny lump size in %s",loadmodel->name);
5468         count = l->filelen / sizeof(*in);
5469
5470         if(!loadmodel->brushq3.num_vertices)
5471         {
5472                 if (count)
5473                         Con_Printf("Mod_Q3BSP_LoadTriangles: %s has triangles but no vertexes, broken compiler, ignoring problem\n", loadmodel->name);
5474                 loadmodel->brushq3.num_triangles = 0;
5475                 return;
5476         }
5477
5478         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5479         loadmodel->brushq3.num_triangles = count / 3;
5480         loadmodel->brushq3.data_element3i = out;
5481
5482         for (i = 0;i < count;i++, in++, out++)
5483         {
5484                 *out = LittleLong(*in);
5485                 if (*out < 0 || *out >= loadmodel->brushq3.num_vertices)
5486                 {
5487                         Con_Printf("Mod_Q3BSP_LoadTriangles: invalid vertexindex %i (%i vertices), setting to 0\n", *out, loadmodel->brushq3.num_vertices);
5488                         *out = 0;
5489                 }
5490         }
5491 }
5492
5493 static void Mod_Q3BSP_LoadLightmaps(lump_t *l, lump_t *faceslump)
5494 {
5495         q3dlightmap_t *input_pointer;
5496         int i;
5497         int j;
5498         int k;
5499         int count;
5500         int powerx;
5501         int powery;
5502         int powerxy;
5503         int powerdxy;
5504         int endlightmap;
5505         int mergegoal;
5506         int lightmapindex;
5507         int realcount;
5508         int realindex;
5509         int mergedwidth;
5510         int mergedheight;
5511         int mergedcolumns;
5512         int mergedrows;
5513         int mergedrowsxcolumns;
5514         int size;
5515         int bytesperpixel;
5516         int rgbmap[3];
5517         unsigned char *c;
5518         unsigned char *mergedpixels;
5519         unsigned char *mergeddeluxepixels;
5520         unsigned char *mergebuf;
5521         char mapname[MAX_QPATH];
5522         qbool external;
5523         unsigned char *inpixels[10000]; // max count q3map2 can output (it uses 4 digits)
5524         char vabuf[1024];
5525
5526         // defaults for q3bsp
5527         size = 128;
5528         bytesperpixel = 3;
5529         rgbmap[0] = 2;
5530         rgbmap[1] = 1;
5531         rgbmap[2] = 0;
5532         external = false;
5533         loadmodel->brushq3.lightmapsize = 128;
5534
5535         if (cls.state == ca_dedicated)
5536                 return;
5537
5538         if(mod_q3bsp_nolightmaps.integer)
5539         {
5540                 return;
5541         }
5542         else if(l->filelen)
5543         {
5544                 // prefer internal LMs for compatibility (a BSP contains no info on whether external LMs exist)
5545                 if (developer_loading.integer)
5546                         Con_Printf("Using internal lightmaps\n");
5547                 input_pointer = (q3dlightmap_t *)(mod_base + l->fileofs);
5548                 if (l->filelen % sizeof(*input_pointer))
5549                         Host_Error("Mod_Q3BSP_LoadLightmaps: funny lump size in %s",loadmodel->name);
5550                 count = l->filelen / sizeof(*input_pointer);
5551                 for(i = 0; i < count; ++i)
5552                         inpixels[i] = input_pointer[i].rgb;
5553         }
5554         else
5555         {
5556                 // no internal lightmaps
5557                 // try external lightmaps
5558                 FS_StripExtension(loadmodel->name, mapname, sizeof(mapname));
5559                 inpixels[0] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, 0), false, false, false, NULL);
5560                 if(!inpixels[0])
5561                         return;
5562                 else
5563                         Con_Printf("Using external lightmaps\n");
5564
5565                 // using EXTERNAL lightmaps instead
5566                 if(image_width != (int) CeilPowerOf2(image_width) || image_width != image_height)
5567                         Con_Printf("Mod_Q3BSP_LoadLightmaps: irregularly sized external lightmap in %s",loadmodel->name);
5568
5569                 size = image_width;
5570                 bytesperpixel = 4;
5571                 rgbmap[0] = 0;
5572                 rgbmap[1] = 1;
5573                 rgbmap[2] = 2;
5574                 external = true;
5575
5576                 for(count = 1; ; ++count)
5577                 {
5578                         inpixels[count] = loadimagepixelsbgra(va(vabuf, sizeof(vabuf), "%s/lm_%04d", mapname, count), false, false, false, NULL);
5579                         if(!inpixels[count])
5580                                 break; // we got all of them
5581                         if(image_width != size || image_height != size)
5582                         {
5583                                 Mem_Free(inpixels[count]);
5584                                 inpixels[count] = NULL;
5585                                 Con_Printf("Mod_Q3BSP_LoadLightmaps: mismatched lightmap size in %s - external lightmap %s/lm_%04d does not match earlier ones\n", loadmodel->name, mapname, count);
5586                                 break;
5587                         }
5588                 }
5589         }
5590
5591         loadmodel->brushq3.lightmapsize = size;
5592         loadmodel->brushq3.num_originallightmaps = count;
5593
5594         // now check the surfaces to see if any of them index an odd numbered
5595         // lightmap, if so this is not a deluxemapped bsp file
5596         //
5597         // also check what lightmaps are actually used, because q3map2 sometimes
5598         // (always?) makes an unused one at the end, which
5599         // q3map2 sometimes (or always?) makes a second blank lightmap for no
5600         // reason when only one lightmap is used, which can throw off the
5601         // deluxemapping detection method, so check 2-lightmap bsp's specifically
5602         // to see if the second lightmap is blank, if so it is not deluxemapped.
5603         // VorteX: autodetect only if previous attempt to find "deluxeMaps" key
5604         // in Mod_Q3BSP_LoadEntities was failed
5605         if (!loadmodel->brushq3.deluxemapping)
5606         {
5607                 loadmodel->brushq3.deluxemapping = !(count & 1);
5608                 loadmodel->brushq3.deluxemapping_modelspace = true;
5609                 endlightmap = 0;
5610                 if (loadmodel->brushq3.deluxemapping)
5611                 {
5612                         int facecount = faceslump->filelen / sizeof(q3dface_t);
5613                         q3dface_t *faces = (q3dface_t *)(mod_base + faceslump->fileofs);
5614                         for (i = 0;i < facecount;i++)
5615                         {
5616                                 j = LittleLong(faces[i].lightmapindex);
5617                                 if (j >= 0)
5618                                 {
5619                                         endlightmap = max(endlightmap, j + 1);
5620                                         if ((j & 1) || j + 1 >= count)
5621                                         {
5622                                                 loadmodel->brushq3.deluxemapping = false;
5623                                                 break;
5624                                         }
5625                                 }
5626                         }
5627                 }
5628
5629                 // q3map2 sometimes (or always?) makes a second blank lightmap for no
5630                 // reason when only one lightmap is used, which can throw off the
5631                 // deluxemapping detection method, so check 2-lightmap bsp's specifically
5632                 // to see if the second lightmap is blank, if so it is not deluxemapped.
5633                 //
5634                 // further research has shown q3map2 sometimes creates a deluxemap and two
5635                 // blank lightmaps, which must be handled properly as well
5636                 if (endlightmap == 1 && count > 1)
5637                 {
5638                         c = inpixels[1];
5639                         for (i = 0;i < size*size;i++)
5640                         {
5641                                 if (c[bytesperpixel*i + rgbmap[0]])
5642                                         break;
5643                                 if (c[bytesperpixel*i + rgbmap[1]])
5644                                         break;
5645                                 if (c[bytesperpixel*i + rgbmap[2]])
5646                                         break;
5647                         }
5648                         if (i == size*size)
5649                         {
5650                                 // all pixels in the unused lightmap were black...
5651                                 loadmodel->brushq3.deluxemapping = false;
5652                         }
5653                 }
5654         }
5655
5656         Con_Printf("%s is %sdeluxemapped\n", loadmodel->name, loadmodel->brushq3.deluxemapping ? "" : "not ");
5657
5658         // figure out what the most reasonable merge power is within limits
5659
5660         // find the appropriate NxN dimensions to merge to, to avoid wasted space
5661         realcount = count >> (int)loadmodel->brushq3.deluxemapping;
5662
5663         // figure out how big the merged texture has to be
5664         mergegoal = 128<<bound(0, mod_q3bsp_lightmapmergepower.integer, 6);
5665         mergegoal = bound(size, mergegoal, (int)vid.maxtexturesize_2d);
5666         while (mergegoal > size && mergegoal * mergegoal / 4 >= size * size * realcount)
5667                 mergegoal /= 2;
5668         mergedwidth = mergegoal;
5669         mergedheight = mergegoal;
5670         // choose non-square size (2x1 aspect) if only half the space is used;
5671         // this really only happens when the entire set fits in one texture, if
5672         // there are multiple textures, we don't worry about shrinking the last
5673         // one to fit, because the driver prefers the same texture size on
5674         // consecutive draw calls...
5675         if (mergedwidth * mergedheight / 2 >= size*size*realcount)
5676                 mergedheight /= 2;
5677
5678         loadmodel->brushq3.num_lightmapmergedwidthpower = 0;
5679         loadmodel->brushq3.num_lightmapmergedheightpower = 0;
5680         while (mergedwidth > size<<loadmodel->brushq3.num_lightmapmergedwidthpower)
5681                 loadmodel->brushq3.num_lightmapmergedwidthpower++;
5682         while (mergedheight > size<<loadmodel->brushq3.num_lightmapmergedheightpower)
5683                 loadmodel->brushq3.num_lightmapmergedheightpower++;
5684         loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower = loadmodel->brushq3.num_lightmapmergedwidthpower + loadmodel->brushq3.num_lightmapmergedheightpower + (loadmodel->brushq3.deluxemapping ? 1 : 0);
5685
5686         powerx = loadmodel->brushq3.num_lightmapmergedwidthpower;
5687         powery = loadmodel->brushq3.num_lightmapmergedheightpower;
5688         powerxy = powerx+powery;
5689         powerdxy = loadmodel->brushq3.deluxemapping + powerxy;
5690
5691         mergedcolumns = 1 << powerx;
5692         mergedrows = 1 << powery;
5693         mergedrowsxcolumns = 1 << powerxy;
5694
5695         loadmodel->brushq3.num_mergedlightmaps = (realcount + (1 << powerxy) - 1) >> powerxy;
5696         loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5697         if (loadmodel->brushq3.deluxemapping)
5698                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brushq3.num_mergedlightmaps * sizeof(rtexture_t *));
5699
5700         mergedpixels = (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4);
5701         mergeddeluxepixels = loadmodel->brushq3.deluxemapping ? (unsigned char *) Mem_Alloc(tempmempool, mergedwidth * mergedheight * 4) : NULL;
5702         for (i = 0;i < count;i++)
5703         {
5704                 // figure out which merged lightmap texture this fits into
5705                 realindex = i >> (int)loadmodel->brushq3.deluxemapping;
5706                 lightmapindex = i >> powerdxy;
5707
5708                 // choose the destination address
5709                 mergebuf = (loadmodel->brushq3.deluxemapping && (i & 1)) ? mergeddeluxepixels : mergedpixels;
5710                 mergebuf += 4 * (realindex & (mergedcolumns-1))*size + 4 * ((realindex >> powerx) & (mergedrows-1))*mergedwidth*size;
5711                 if ((i & 1) == 0 || !loadmodel->brushq3.deluxemapping)
5712                         Con_DPrintf("copying original lightmap %i (%ix%i) to %i (at %i,%i)\n", i, size, size, lightmapindex, (realindex & (mergedcolumns-1))*size, ((realindex >> powerx) & (mergedrows-1))*size);
5713
5714                 // convert pixels from RGB or BGRA while copying them into the destination rectangle
5715                 for (j = 0;j < size;j++)
5716                 for (k = 0;k < size;k++)
5717                 {
5718                         mergebuf[(j*mergedwidth+k)*4+0] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[0]];
5719                         mergebuf[(j*mergedwidth+k)*4+1] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[1]];
5720                         mergebuf[(j*mergedwidth+k)*4+2] = inpixels[i][(j*size+k)*bytesperpixel+rgbmap[2]];
5721                         mergebuf[(j*mergedwidth+k)*4+3] = 255;
5722                 }
5723
5724                 // upload texture if this was the last tile being written to the texture
5725                 if (((realindex + 1) & (mergedrowsxcolumns - 1)) == 0 || (realindex + 1) == realcount)
5726                 {
5727                         if (loadmodel->brushq3.deluxemapping && (i & 1))
5728                                 loadmodel->brushq3.data_deluxemaps[lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "deluxemap%04i", lightmapindex), mergedwidth, mergedheight, mergeddeluxepixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bspdeluxemaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5729                         else
5730                         {
5731                                 if(mod_q3bsp_sRGBlightmaps.integer)
5732                                 {
5733                                         textype_t t;
5734                                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5735                                         {
5736                                                 t = TEXTYPE_BGRA; // in stupid fallback mode, we upload lightmaps in sRGB form and just fix their brightness
5737                                                 // we fix the brightness consistently via lightmapscale
5738                                         }
5739                                         else
5740                                                 t = TEXTYPE_SRGB_BGRA; // normally, we upload lightmaps in sRGB form (possibly downconverted to linear)
5741                                         loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%04i", lightmapindex), mergedwidth, mergedheight, mergedpixels, t, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5742                                 }
5743                                 else
5744                                 {
5745                                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
5746                                                 Image_MakesRGBColorsFromLinear_Lightmap(mergedpixels, mergedpixels, mergedwidth * mergedheight);
5747                                         loadmodel->brushq3.data_lightmaps [lightmapindex] = R_LoadTexture2D(loadmodel->texturepool, va(vabuf, sizeof(vabuf), "lightmap%04i", lightmapindex), mergedwidth, mergedheight, mergedpixels, TEXTYPE_BGRA, TEXF_FORCELINEAR | (gl_texturecompression_q3bsplightmaps.integer ? TEXF_COMPRESS : 0), -1, NULL);
5748                                 }
5749                         }
5750                 }
5751         }
5752
5753         if (mergeddeluxepixels)
5754                 Mem_Free(mergeddeluxepixels);
5755         Mem_Free(mergedpixels);
5756         if(external)
5757         {
5758                 for(i = 0; i < count; ++i)
5759                         Mem_Free(inpixels[i]);
5760         }
5761 }
5762
5763 typedef struct patchtess_s
5764 {
5765         patchinfo_t info;
5766
5767         // Auxiliary data used only by patch loading code in Mod_Q3BSP_LoadFaces
5768         int surface_id;
5769         float lodgroup[6];
5770         float *originalvertex3f;
5771 } patchtess_t;
5772
5773 #define PATCHTESS_SAME_LODGROUP(a,b) \
5774         ( \
5775                 (a).lodgroup[0] == (b).lodgroup[0] && \
5776                 (a).lodgroup[1] == (b).lodgroup[1] && \
5777                 (a).lodgroup[2] == (b).lodgroup[2] && \
5778                 (a).lodgroup[3] == (b).lodgroup[3] && \
5779                 (a).lodgroup[4] == (b).lodgroup[4] && \
5780                 (a).lodgroup[5] == (b).lodgroup[5] \
5781         )
5782
5783 static void Mod_Q3BSP_LoadFaces(lump_t *l)
5784 {
5785         q3dface_t *in, *oldin;
5786         msurface_t *out, *oldout;
5787         int i, oldi, j, n, count, invalidelements, patchsize[2], finalwidth, finalheight, xtess, ytess, finalvertices, finaltriangles, firstvertex, firstelement, type, oldnumtriangles, oldnumtriangles2, meshvertices, meshtriangles, collisionvertices, collisiontriangles, numvertices, numtriangles, cxtess, cytess;
5788         float lightmaptcbase[2], lightmaptcscale[2];
5789         //int *originalelement3i;
5790         float *originalvertex3f;
5791         //float *originalsvector3f;
5792         //float *originaltvector3f;
5793         float *originalnormal3f;
5794         float *originalcolor4f;
5795         float *originaltexcoordtexture2f;
5796         float *originaltexcoordlightmap2f;
5797         float *surfacecollisionvertex3f;
5798         int *surfacecollisionelement3i;
5799         float *v;
5800         patchtess_t *patchtess = NULL;
5801         int patchtesscount = 0;
5802         qbool again;
5803
5804         in = (q3dface_t *)(mod_base + l->fileofs);
5805         if (l->filelen % sizeof(*in))
5806                 Host_Error("Mod_Q3BSP_LoadFaces: funny lump size in %s",loadmodel->name);
5807         count = l->filelen / sizeof(*in);
5808         out = (msurface_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
5809
5810         loadmodel->data_surfaces = out;
5811         loadmodel->num_surfaces = count;
5812
5813         if(count > 0)
5814                 patchtess = (patchtess_t*) Mem_Alloc(tempmempool, count * sizeof(*patchtess));
5815
5816         i = 0;
5817         oldi = i;
5818         oldin = in;
5819         oldout = out;
5820         meshvertices = 0;
5821         meshtriangles = 0;
5822         for (;i < count;i++, in++, out++)
5823         {
5824                 // check face type first
5825                 type = LittleLong(in->type);
5826                 if (type != Q3FACETYPE_FLAT
5827                  && type != Q3FACETYPE_PATCH
5828                  && type != Q3FACETYPE_MESH
5829                  && type != Q3FACETYPE_FLARE)
5830                 {
5831                         Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: unknown face type %i\n", i, type);
5832                         continue;
5833                 }
5834
5835                 n = LittleLong(in->textureindex);
5836                 if (n < 0 || n >= loadmodel->num_textures)
5837                 {
5838                         Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i: invalid textureindex %i (%i textures)\n", i, n, loadmodel->num_textures);
5839                         continue;
5840                 }
5841                 out->texture = loadmodel->data_textures + n;
5842                 n = LittleLong(in->effectindex);
5843                 if (n < -1 || n >= loadmodel->brushq3.num_effects)
5844                 {
5845                         if (developer_extra.integer)
5846                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid effectindex %i (%i effects)\n", i, out->texture->name, n, loadmodel->brushq3.num_effects);
5847                         n = -1;
5848                 }
5849                 if (n == -1)
5850                         out->effect = NULL;
5851                 else
5852                         out->effect = loadmodel->brushq3.data_effects + n;
5853
5854                 if (cls.state != ca_dedicated)
5855                 {
5856                         out->lightmaptexture = NULL;
5857                         out->deluxemaptexture = r_texture_blanknormalmap;
5858                         n = LittleLong(in->lightmapindex);
5859                         if (n < 0)
5860                                 n = -1;
5861                         else if (n >= loadmodel->brushq3.num_originallightmaps)
5862                         {
5863                                 if(loadmodel->brushq3.num_originallightmaps != 0)
5864                                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid lightmapindex %i (%i lightmaps)\n", i, out->texture->name, n, loadmodel->brushq3.num_originallightmaps);
5865                                 n = -1;
5866                         }
5867                         else
5868                         {
5869                                 out->lightmaptexture = loadmodel->brushq3.data_lightmaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5870                                 if (loadmodel->brushq3.deluxemapping)
5871                                         out->deluxemaptexture = loadmodel->brushq3.data_deluxemaps[n >> loadmodel->brushq3.num_lightmapmergedwidthheightdeluxepower];
5872                                 loadmodel->lit = true;
5873                         }
5874                 }
5875
5876                 firstvertex = LittleLong(in->firstvertex);
5877                 numvertices = LittleLong(in->numvertices);
5878                 firstelement = LittleLong(in->firstelement);
5879                 numtriangles = LittleLong(in->numelements) / 3;
5880                 if (numtriangles * 3 != LittleLong(in->numelements))
5881                 {
5882                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): numelements %i is not a multiple of 3\n", i, out->texture->name, LittleLong(in->numelements));
5883                         continue;
5884                 }
5885                 if (firstvertex < 0 || firstvertex + numvertices > loadmodel->brushq3.num_vertices)
5886                 {
5887                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid vertex range %i : %i (%i vertices)\n", i, out->texture->name, firstvertex, firstvertex + numvertices, loadmodel->brushq3.num_vertices);
5888                         continue;
5889                 }
5890                 if (firstelement < 0 || firstelement + numtriangles * 3 > loadmodel->brushq3.num_triangles * 3)
5891                 {
5892                         Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid element range %i : %i (%i elements)\n", i, out->texture->name, firstelement, firstelement + numtriangles * 3, loadmodel->brushq3.num_triangles * 3);
5893                         continue;
5894                 }
5895                 switch(type)
5896                 {
5897                 case Q3FACETYPE_FLAT:
5898                 case Q3FACETYPE_MESH:
5899                         // no processing necessary
5900                         break;
5901                 case Q3FACETYPE_PATCH:
5902                         patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
5903                         patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
5904                         if (numvertices != (patchsize[0] * patchsize[1]) || patchsize[0] < 3 || patchsize[1] < 3 || !(patchsize[0] & 1) || !(patchsize[1] & 1) || patchsize[0] * patchsize[1] >= (cls.state == ca_dedicated ? mod_q3bsp_curves_subdivisions_maxvertices.integer : min(r_subdivisions_maxvertices.integer, mod_q3bsp_curves_subdivisions_maxvertices.integer)))
5905                         {
5906                                 Con_Printf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): invalid patchsize %ix%i\n", i, out->texture->name, patchsize[0], patchsize[1]);
5907                                 continue;
5908                         }
5909                         originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
5910
5911                         // convert patch to Q3FACETYPE_MESH
5912                         xtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5913                         ytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, r_subdivisions_tolerance.value);
5914                         // bound to user settings
5915                         xtess = bound(r_subdivisions_mintess.integer, xtess, r_subdivisions_maxtess.integer);
5916                         ytess = bound(r_subdivisions_mintess.integer, ytess, r_subdivisions_maxtess.integer);
5917                         // bound to sanity settings
5918                         xtess = bound(0, xtess, 1024);
5919                         ytess = bound(0, ytess, 1024);
5920
5921                         // lower quality collision patches! Same procedure as before, but different cvars
5922                         // convert patch to Q3FACETYPE_MESH
5923                         cxtess = Q3PatchTesselationOnX(patchsize[0], patchsize[1], 3, originalvertex3f, mod_q3bsp_curves_subdivisions_tolerance.value);
5924                         cytess = Q3PatchTesselationOnY(patchsize[0], patchsize[1], 3, originalvertex3f, mod_q3bsp_curves_subdivisions_tolerance.value);
5925                         // bound to user settings
5926                         cxtess = bound(mod_q3bsp_curves_subdivisions_mintess.integer, cxtess, mod_q3bsp_curves_subdivisions_maxtess.integer);
5927                         cytess = bound(mod_q3bsp_curves_subdivisions_mintess.integer, cytess, mod_q3bsp_curves_subdivisions_maxtess.integer);
5928                         // bound to sanity settings
5929                         cxtess = bound(0, cxtess, 1024);
5930                         cytess = bound(0, cytess, 1024);
5931
5932                         // store it for the LOD grouping step
5933                         patchtess[patchtesscount].info.xsize = patchsize[0];
5934                         patchtess[patchtesscount].info.ysize = patchsize[1];
5935                         patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].xtess = xtess;
5936                         patchtess[patchtesscount].info.lods[PATCH_LOD_VISUAL].ytess = ytess;
5937                         patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].xtess = cxtess;
5938                         patchtess[patchtesscount].info.lods[PATCH_LOD_COLLISION].ytess = cytess;
5939         
5940                         patchtess[patchtesscount].surface_id = i;
5941                         patchtess[patchtesscount].lodgroup[0] = LittleFloat(in->specific.patch.mins[0]);
5942                         patchtess[patchtesscount].lodgroup[1] = LittleFloat(in->specific.patch.mins[1]);
5943                         patchtess[patchtesscount].lodgroup[2] = LittleFloat(in->specific.patch.mins[2]);
5944                         patchtess[patchtesscount].lodgroup[3] = LittleFloat(in->specific.patch.maxs[0]);
5945                         patchtess[patchtesscount].lodgroup[4] = LittleFloat(in->specific.patch.maxs[1]);
5946                         patchtess[patchtesscount].lodgroup[5] = LittleFloat(in->specific.patch.maxs[2]);
5947                         patchtess[patchtesscount].originalvertex3f = originalvertex3f;
5948                         ++patchtesscount;
5949                         break;
5950                 case Q3FACETYPE_FLARE:
5951                         if (developer_extra.integer)
5952                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: face #%i (texture \"%s\"): Q3FACETYPE_FLARE not supported (yet)\n", i, out->texture->name);
5953                         // don't render it
5954                         continue;
5955                 }
5956                 out->num_vertices = numvertices;
5957                 out->num_triangles = numtriangles;
5958                 meshvertices += out->num_vertices;
5959                 meshtriangles += out->num_triangles;
5960         }
5961
5962         // Fix patches tesselations so that they make no seams
5963         do
5964         {
5965                 again = false;
5966                 for(i = 0; i < patchtesscount; ++i)
5967                 {
5968                         for(j = i+1; j < patchtesscount; ++j)
5969                         {
5970                                 if (!PATCHTESS_SAME_LODGROUP(patchtess[i], patchtess[j]))
5971                                         continue;
5972
5973                                 if (Q3PatchAdjustTesselation(3, &patchtess[i].info, patchtess[i].originalvertex3f, &patchtess[j].info, patchtess[j].originalvertex3f) )
5974                                         again = true;
5975                         }
5976                 }
5977         }
5978         while (again);
5979
5980         // Calculate resulting number of triangles
5981         collisionvertices = 0;
5982         collisiontriangles = 0;
5983         for(i = 0; i < patchtesscount; ++i)
5984         {
5985                 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_VISUAL].xtess);
5986                 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_VISUAL].ytess);
5987                 numvertices = finalwidth * finalheight;
5988                 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5989
5990                 oldout[patchtess[i].surface_id].num_vertices = numvertices;
5991                 oldout[patchtess[i].surface_id].num_triangles = numtriangles;
5992                 meshvertices += oldout[patchtess[i].surface_id].num_vertices;
5993                 meshtriangles += oldout[patchtess[i].surface_id].num_triangles;
5994
5995                 finalwidth = Q3PatchDimForTess(patchtess[i].info.xsize, patchtess[i].info.lods[PATCH_LOD_COLLISION].xtess);
5996                 finalheight = Q3PatchDimForTess(patchtess[i].info.ysize,patchtess[i].info.lods[PATCH_LOD_COLLISION].ytess);
5997                 numvertices = finalwidth * finalheight;
5998                 numtriangles = (finalwidth - 1) * (finalheight - 1) * 2;
5999
6000                 oldout[patchtess[i].surface_id].num_collisionvertices = numvertices;
6001                 oldout[patchtess[i].surface_id].num_collisiontriangles = numtriangles;
6002                 collisionvertices += oldout[patchtess[i].surface_id].num_collisionvertices;
6003                 collisiontriangles += oldout[patchtess[i].surface_id].num_collisiontriangles;
6004         }
6005
6006         i = oldi;
6007         in = oldin;
6008         out = oldout;
6009         Mod_AllocSurfMesh(loadmodel->mempool, meshvertices, meshtriangles, false, true);
6010         if (collisiontriangles)
6011         {
6012                 loadmodel->brush.data_collisionvertex3f = (float *)Mem_Alloc(loadmodel->mempool, collisionvertices * sizeof(float[3]));
6013                 loadmodel->brush.data_collisionelement3i = (int *)Mem_Alloc(loadmodel->mempool, collisiontriangles * sizeof(int[3]));
6014         }
6015         meshvertices = 0;
6016         meshtriangles = 0;
6017         collisionvertices = 0;
6018         collisiontriangles = 0;
6019         for (;i < count && meshvertices + out->num_vertices <= loadmodel->surfmesh.num_vertices;i++, in++, out++)
6020         {
6021                 if (out->num_vertices < 3 || out->num_triangles < 1)
6022                         continue;
6023
6024                 type = LittleLong(in->type);
6025                 firstvertex = LittleLong(in->firstvertex);
6026                 firstelement = LittleLong(in->firstelement);
6027                 out->num_firstvertex = meshvertices;
6028                 out->num_firsttriangle = meshtriangles;
6029                 out->num_firstcollisiontriangle = collisiontriangles;
6030                 switch(type)
6031                 {
6032                 case Q3FACETYPE_FLAT:
6033                 case Q3FACETYPE_MESH:
6034                         // no processing necessary, except for lightmap merging
6035                         for (j = 0;j < out->num_vertices;j++)
6036                         {
6037                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 0];
6038                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 1];
6039                                 (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_vertex3f[(firstvertex + j) * 3 + 2];
6040                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 0] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 0];
6041                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 1] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 1];
6042                                 (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex)[j * 3 + 2] = loadmodel->brushq3.data_normal3f[(firstvertex + j) * 3 + 2];
6043                                 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 0];
6044                                 (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordtexture2f[(firstvertex + j) * 2 + 1];
6045                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 0] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 0];
6046                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex)[j * 2 + 1] = loadmodel->brushq3.data_texcoordlightmap2f[(firstvertex + j) * 2 + 1];
6047                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 0] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 0];
6048                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 1] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 1];
6049                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 2] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 2];
6050                                 (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex)[j * 4 + 3] = loadmodel->brushq3.data_color4f[(firstvertex + j) * 4 + 3];
6051                         }
6052                         for (j = 0;j < out->num_triangles*3;j++)
6053                                 (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = loadmodel->brushq3.data_element3i[firstelement + j] + out->num_firstvertex;
6054                         break;
6055                 case Q3FACETYPE_PATCH:
6056                         patchsize[0] = LittleLong(in->specific.patch.patchsize[0]);
6057                         patchsize[1] = LittleLong(in->specific.patch.patchsize[1]);
6058                         originalvertex3f = loadmodel->brushq3.data_vertex3f + firstvertex * 3;
6059                         originalnormal3f = loadmodel->brushq3.data_normal3f + firstvertex * 3;
6060                         originaltexcoordtexture2f = loadmodel->brushq3.data_texcoordtexture2f + firstvertex * 2;
6061                         originaltexcoordlightmap2f = loadmodel->brushq3.data_texcoordlightmap2f + firstvertex * 2;
6062                         originalcolor4f = loadmodel->brushq3.data_color4f + firstvertex * 4;
6063
6064                         xtess = ytess = cxtess = cytess = -1;
6065                         for(j = 0; j < patchtesscount; ++j)
6066                                 if(patchtess[j].surface_id == i)
6067                                 {
6068                                         xtess = patchtess[j].info.lods[PATCH_LOD_VISUAL].xtess;
6069                                         ytess = patchtess[j].info.lods[PATCH_LOD_VISUAL].ytess;
6070                                         cxtess = patchtess[j].info.lods[PATCH_LOD_COLLISION].xtess;
6071                                         cytess = patchtess[j].info.lods[PATCH_LOD_COLLISION].ytess;
6072                                         break;
6073                                 }
6074                         if(xtess == -1)
6075                         {
6076                                 Con_Printf(CON_ERROR "ERROR: patch %d isn't preprocessed?!?\n", i);
6077                                 xtess = ytess = cxtess = cytess = 0;
6078                         }
6079
6080                         finalwidth = Q3PatchDimForTess(patchsize[0],xtess); //((patchsize[0] - 1) * xtess) + 1;
6081                         finalheight = Q3PatchDimForTess(patchsize[1],ytess); //((patchsize[1] - 1) * ytess) + 1;
6082                         finalvertices = finalwidth * finalheight;
6083                         oldnumtriangles = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6084                         type = Q3FACETYPE_MESH;
6085                         // generate geometry
6086                         // (note: normals are skipped because they get recalculated)
6087                         Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, xtess, ytess);
6088                         Q3PatchTesselateFloat(3, sizeof(float[3]), (loadmodel->surfmesh.data_normal3f + 3 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[3]), originalnormal3f, xtess, ytess);
6089                         Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordtexture2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordtexture2f, xtess, ytess);
6090                         Q3PatchTesselateFloat(2, sizeof(float[2]), (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[2]), originaltexcoordlightmap2f, xtess, ytess);
6091                         Q3PatchTesselateFloat(4, sizeof(float[4]), (loadmodel->surfmesh.data_lightmapcolor4f + 4 * out->num_firstvertex), patchsize[0], patchsize[1], sizeof(float[4]), originalcolor4f, xtess, ytess);
6092                         Q3PatchTriangleElements((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), finalwidth, finalheight, out->num_firstvertex);
6093
6094                         out->num_triangles = Mod_RemoveDegenerateTriangles(out->num_triangles, (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle), loadmodel->surfmesh.data_vertex3f);
6095
6096                         if (developer_extra.integer)
6097                         {
6098                                 if (out->num_triangles < finaltriangles)
6099                                         Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles, %i degenerate triangles removed (leaving %i)\n", patchsize[0], patchsize[1], out->num_vertices, finaltriangles, finaltriangles - out->num_triangles, out->num_triangles);
6100                                 else
6101                                         Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve subdivided to %i vertices / %i triangles\n", patchsize[0], patchsize[1], out->num_vertices, out->num_triangles);
6102                         }
6103                         // q3map does not put in collision brushes for curves... ugh
6104                         // build the lower quality collision geometry
6105                         finalwidth = Q3PatchDimForTess(patchsize[0],cxtess); //((patchsize[0] - 1) * cxtess) + 1;
6106                         finalheight = Q3PatchDimForTess(patchsize[1],cytess); //((patchsize[1] - 1) * cytess) + 1;
6107                         finalvertices = finalwidth * finalheight;
6108                         oldnumtriangles2 = finaltriangles = (finalwidth - 1) * (finalheight - 1) * 2;
6109
6110                         // store collision geometry for BIH collision tree
6111                         out->num_collisionvertices = finalvertices;
6112                         out->num_collisiontriangles = finaltriangles;
6113                         surfacecollisionvertex3f = loadmodel->brush.data_collisionvertex3f + collisionvertices * 3;
6114                         surfacecollisionelement3i = loadmodel->brush.data_collisionelement3i + collisiontriangles * 3;
6115                         Q3PatchTesselateFloat(3, sizeof(float[3]), surfacecollisionvertex3f, patchsize[0], patchsize[1], sizeof(float[3]), originalvertex3f, cxtess, cytess);
6116                         Q3PatchTriangleElements(surfacecollisionelement3i, finalwidth, finalheight, collisionvertices);
6117                         Mod_SnapVertices(3, finalvertices, surfacecollisionvertex3f, 1);
6118                         out->num_collisiontriangles = Mod_RemoveDegenerateTriangles(finaltriangles, surfacecollisionelement3i, surfacecollisionelement3i, loadmodel->brush.data_collisionvertex3f);
6119
6120                         if (developer_extra.integer)
6121                                 Con_DPrintf("Mod_Q3BSP_LoadFaces: %ix%i curve became %i:%i vertices / %i:%i triangles (%i:%i degenerate)\n", patchsize[0], patchsize[1], out->num_vertices, out->num_collisionvertices, oldnumtriangles, oldnumtriangles2, oldnumtriangles - out->num_triangles, oldnumtriangles2 - out->num_collisiontriangles);
6122
6123                         collisionvertices += finalvertices;
6124                         collisiontriangles += out->num_collisiontriangles;
6125                         break;
6126                 default:
6127                         break;
6128                 }
6129                 meshvertices += out->num_vertices;
6130                 meshtriangles += out->num_triangles;
6131                 for (j = 0, invalidelements = 0;j < out->num_triangles * 3;j++)
6132                         if ((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
6133                                 invalidelements++;
6134                 if (invalidelements)
6135                 {
6136                         Con_Printf(CON_WARN "Mod_Q3BSP_LoadFaces: Warning: face #%i has %i invalid elements, type = %i, texture->name = \"%s\", texture->surfaceflags = %i, firstvertex = %i, numvertices = %i, firstelement = %i, numelements = %i, elements list:\n", i, invalidelements, type, out->texture->name, out->texture->surfaceflags, firstvertex, out->num_vertices, firstelement, out->num_triangles * 3);
6137                         for (j = 0;j < out->num_triangles * 3;j++)
6138                         {
6139                                 Con_Printf(" %i", (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] - out->num_firstvertex);
6140                                 if ((loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] < out->num_firstvertex || (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] >= out->num_firstvertex + out->num_vertices)
6141                                         (loadmodel->surfmesh.data_element3i + 3 * out->num_firsttriangle)[j] = out->num_firstvertex;
6142                         }
6143                         Con_Print("\n");
6144                 }
6145                 // calculate a bounding box
6146                 VectorClear(out->mins);
6147                 VectorClear(out->maxs);
6148                 if (out->num_vertices)
6149                 {
6150                         if (cls.state != ca_dedicated && out->lightmaptexture)
6151                         {
6152                                 // figure out which part of the merged lightmap this fits into
6153                                 int lightmapindex = LittleLong(in->lightmapindex) >> (loadmodel->brushq3.deluxemapping ? 1 : 0);
6154                                 int mergewidth = R_TextureWidth(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6155                                 int mergeheight = R_TextureHeight(out->lightmaptexture) / loadmodel->brushq3.lightmapsize;
6156                                 lightmapindex &= mergewidth * mergeheight - 1;
6157                                 lightmaptcscale[0] = 1.0f / mergewidth;
6158                                 lightmaptcscale[1] = 1.0f / mergeheight;
6159                                 lightmaptcbase[0] = (lightmapindex % mergewidth) * lightmaptcscale[0];
6160                                 lightmaptcbase[1] = (lightmapindex / mergewidth) * lightmaptcscale[1];
6161                                 // modify the lightmap texcoords to match this region of the merged lightmap
6162                                 for (j = 0, v = loadmodel->surfmesh.data_texcoordlightmap2f + 2 * out->num_firstvertex;j < out->num_vertices;j++, v += 2)
6163                                 {
6164                                         v[0] = v[0] * lightmaptcscale[0] + lightmaptcbase[0];
6165                                         v[1] = v[1] * lightmaptcscale[1] + lightmaptcbase[1];
6166                                 }
6167                         }
6168                         VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->mins);
6169                         VectorCopy((loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex), out->maxs);
6170                         for (j = 1, v = (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex) + 3;j < out->num_vertices;j++, v += 3)
6171                         {
6172                                 out->mins[0] = min(out->mins[0], v[0]);
6173                                 out->maxs[0] = max(out->maxs[0], v[0]);
6174                                 out->mins[1] = min(out->mins[1], v[1]);
6175                                 out->maxs[1] = max(out->maxs[1], v[1]);
6176                                 out->mins[2] = min(out->mins[2], v[2]);
6177                                 out->maxs[2] = max(out->maxs[2], v[2]);
6178                         }
6179                         out->mins[0] -= 1.0f;
6180                         out->mins[1] -= 1.0f;
6181                         out->mins[2] -= 1.0f;
6182                         out->maxs[0] += 1.0f;
6183                         out->maxs[1] += 1.0f;
6184                         out->maxs[2] += 1.0f;
6185                 }
6186                 // set lightmap styles for consistency with q1bsp
6187                 //out->lightmapinfo->styles[0] = 0;
6188                 //out->lightmapinfo->styles[1] = 255;
6189                 //out->lightmapinfo->styles[2] = 255;
6190                 //out->lightmapinfo->styles[3] = 255;
6191         }
6192
6193         i = oldi;
6194         out = oldout;
6195         for (;i < count;i++, out++)
6196         {
6197                 if(out->num_vertices && out->num_triangles)
6198                         continue;
6199                 if(out->num_vertices == 0)
6200                 {
6201                         Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no vertices, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6202                         if(out->num_triangles == 0)
6203                                 Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)");
6204                 }
6205                 else if(out->num_triangles == 0)
6206                         Con_Printf("Mod_Q3BSP_LoadFaces: surface %d (texture %s, near %f %f %f) has no triangles, ignoring\n", i, out->texture ? out->texture->name : "(none)",
6207                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[0 * 3 + 0],
6208                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[1 * 3 + 0],
6209                                         (loadmodel->surfmesh.data_vertex3f + 3 * out->num_firstvertex)[2 * 3 + 0]);
6210         }
6211
6212         // for per pixel lighting
6213         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
6214
6215         // generate ushort elements array if possible
6216         if (loadmodel->surfmesh.data_element3s)
6217                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
6218                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
6219
6220         // free the no longer needed vertex data
6221         loadmodel->brushq3.num_vertices = 0;
6222         if (loadmodel->brushq3.data_vertex3f)
6223                 Mem_Free(loadmodel->brushq3.data_vertex3f);
6224         loadmodel->brushq3.data_vertex3f = NULL;
6225         loadmodel->brushq3.data_normal3f = NULL;
6226         loadmodel->brushq3.data_texcoordtexture2f = NULL;
6227         loadmodel->brushq3.data_texcoordlightmap2f = NULL;
6228         loadmodel->brushq3.data_color4f = NULL;
6229         // free the no longer needed triangle data
6230         loadmodel->brushq3.num_triangles = 0;
6231         if (loadmodel->brushq3.data_element3i)
6232                 Mem_Free(loadmodel->brushq3.data_element3i);
6233         loadmodel->brushq3.data_element3i = NULL;
6234
6235         if(patchtess)
6236                 Mem_Free(patchtess);
6237 }
6238
6239 static void Mod_Q3BSP_LoadModels(lump_t *l)
6240 {
6241         q3dmodel_t *in;
6242         q3dmodel_t *out;
6243         int i, j, n, c, count;
6244
6245         in = (q3dmodel_t *)(mod_base + l->fileofs);
6246         if (l->filelen % sizeof(*in))
6247                 Host_Error("Mod_Q3BSP_LoadModels: funny lump size in %s",loadmodel->name);
6248         count = l->filelen / sizeof(*in);
6249         out = (q3dmodel_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6250
6251         loadmodel->brushq3.data_models = out;
6252         loadmodel->brushq3.num_models = count;
6253
6254         for (i = 0;i < count;i++, in++, out++)
6255         {
6256                 for (j = 0;j < 3;j++)
6257                 {
6258                         out->mins[j] = LittleFloat(in->mins[j]);
6259                         out->maxs[j] = LittleFloat(in->maxs[j]);
6260                 }
6261                 n = LittleLong(in->firstface);
6262                 c = LittleLong(in->numfaces);
6263                 if (n < 0 || n + c > loadmodel->num_surfaces)
6264                         Host_Error("Mod_Q3BSP_LoadModels: invalid face range %i : %i (%i faces)", n, n + c, loadmodel->num_surfaces);
6265                 out->firstface = n;
6266                 out->numfaces = c;
6267                 n = LittleLong(in->firstbrush);
6268                 c = LittleLong(in->numbrushes);
6269                 if (n < 0 || n + c > loadmodel->brush.num_brushes)
6270                         Host_Error("Mod_Q3BSP_LoadModels: invalid brush range %i : %i (%i brushes)", n, n + c, loadmodel->brush.num_brushes);
6271                 out->firstbrush = n;
6272                 out->numbrushes = c;
6273         }
6274 }
6275
6276 static void Mod_Q3BSP_LoadLeafBrushes(lump_t *l)
6277 {
6278         int *in;
6279         int *out;
6280         int i, n, count;
6281
6282         in = (int *)(mod_base + l->fileofs);
6283         if (l->filelen % sizeof(*in))
6284                 Host_Error("Mod_Q3BSP_LoadLeafBrushes: funny lump size in %s",loadmodel->name);
6285         count = l->filelen / sizeof(*in);
6286         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6287
6288         loadmodel->brush.data_leafbrushes = out;
6289         loadmodel->brush.num_leafbrushes = count;
6290
6291         for (i = 0;i < count;i++, in++, out++)
6292         {
6293                 n = LittleLong(*in);
6294                 if (n < 0 || n >= loadmodel->brush.num_brushes)
6295                         Host_Error("Mod_Q3BSP_LoadLeafBrushes: invalid brush index %i (%i brushes)", n, loadmodel->brush.num_brushes);
6296                 *out = n;
6297         }
6298 }
6299
6300 static void Mod_Q3BSP_LoadLeafFaces(lump_t *l)
6301 {
6302         int *in;
6303         int *out;
6304         int i, n, count;
6305
6306         in = (int *)(mod_base + l->fileofs);
6307         if (l->filelen % sizeof(*in))
6308                 Host_Error("Mod_Q3BSP_LoadLeafFaces: funny lump size in %s",loadmodel->name);
6309         count = l->filelen / sizeof(*in);
6310         out = (int *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6311
6312         loadmodel->brush.data_leafsurfaces = out;
6313         loadmodel->brush.num_leafsurfaces = count;
6314
6315         for (i = 0;i < count;i++, in++, out++)
6316         {
6317                 n = LittleLong(*in);
6318                 if (n < 0 || n >= loadmodel->num_surfaces)
6319                         Host_Error("Mod_Q3BSP_LoadLeafFaces: invalid face index %i (%i faces)", n, loadmodel->num_surfaces);
6320                 *out = n;
6321         }
6322 }
6323
6324 static void Mod_Q3BSP_LoadLeafs(lump_t *l)
6325 {
6326         q3dleaf_t *in;
6327         mleaf_t *out;
6328         int i, j, n, c, count;
6329
6330         in = (q3dleaf_t *)(mod_base + l->fileofs);
6331         if (l->filelen % sizeof(*in))
6332                 Host_Error("Mod_Q3BSP_LoadLeafs: funny lump size in %s",loadmodel->name);
6333         count = l->filelen / sizeof(*in);
6334         out = (mleaf_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6335
6336         loadmodel->brush.data_leafs = out;
6337         loadmodel->brush.num_leafs = count;
6338
6339         for (i = 0;i < count;i++, in++, out++)
6340         {
6341                 out->parent = NULL;
6342                 out->plane = NULL;
6343                 out->clusterindex = LittleLong(in->clusterindex);
6344                 out->areaindex = LittleLong(in->areaindex);
6345                 for (j = 0;j < 3;j++)
6346                 {
6347                         // yes the mins/maxs are ints
6348                         out->mins[j] = LittleLong(in->mins[j]) - 1;
6349                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6350                 }
6351                 n = LittleLong(in->firstleafface);
6352                 c = LittleLong(in->numleaffaces);
6353                 if (n < 0 || n + c > loadmodel->brush.num_leafsurfaces)
6354                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafsurface range %i : %i (%i leafsurfaces)", n, n + c, loadmodel->brush.num_leafsurfaces);
6355                 out->firstleafsurface = loadmodel->brush.data_leafsurfaces + n;
6356                 out->numleafsurfaces = c;
6357                 n = LittleLong(in->firstleafbrush);
6358                 c = LittleLong(in->numleafbrushes);
6359                 if (n < 0 || n + c > loadmodel->brush.num_leafbrushes)
6360                         Host_Error("Mod_Q3BSP_LoadLeafs: invalid leafbrush range %i : %i (%i leafbrushes)", n, n + c, loadmodel->brush.num_leafbrushes);
6361                 out->firstleafbrush = loadmodel->brush.data_leafbrushes + n;
6362                 out->numleafbrushes = c;
6363         }
6364 }
6365
6366 static void Mod_Q3BSP_LoadNodes(lump_t *l)
6367 {
6368         q3dnode_t *in;
6369         mnode_t *out;
6370         int i, j, n, count;
6371
6372         in = (q3dnode_t *)(mod_base + l->fileofs);
6373         if (l->filelen % sizeof(*in))
6374                 Host_Error("Mod_Q3BSP_LoadNodes: funny lump size in %s",loadmodel->name);
6375         count = l->filelen / sizeof(*in);
6376         if (count == 0)
6377                 Host_Error("Mod_Q3BSP_LoadNodes: missing BSP tree in %s",loadmodel->name);
6378         out = (mnode_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6379
6380         loadmodel->brush.data_nodes = out;
6381         loadmodel->brush.num_nodes = count;
6382
6383         for (i = 0;i < count;i++, in++, out++)
6384         {
6385                 out->parent = NULL;
6386                 n = LittleLong(in->planeindex);
6387                 if (n < 0 || n >= loadmodel->brush.num_planes)
6388                         Host_Error("Mod_Q3BSP_LoadNodes: invalid planeindex %i (%i planes)", n, loadmodel->brush.num_planes);
6389                 out->plane = loadmodel->brush.data_planes + n;
6390                 for (j = 0;j < 2;j++)
6391                 {
6392                         n = LittleLong(in->childrenindex[j]);
6393                         if (n >= 0)
6394                         {
6395                                 if (n >= loadmodel->brush.num_nodes)
6396                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child node index %i (%i nodes)", n, loadmodel->brush.num_nodes);
6397                                 out->children[j] = loadmodel->brush.data_nodes + n;
6398                         }
6399                         else
6400                         {
6401                                 n = -1 - n;
6402                                 if (n >= loadmodel->brush.num_leafs)
6403                                         Host_Error("Mod_Q3BSP_LoadNodes: invalid child leaf index %i (%i leafs)", n, loadmodel->brush.num_leafs);
6404                                 out->children[j] = (mnode_t *)(loadmodel->brush.data_leafs + n);
6405                         }
6406                 }
6407                 for (j = 0;j < 3;j++)
6408                 {
6409                         // yes the mins/maxs are ints
6410                         out->mins[j] = LittleLong(in->mins[j]) - 1;
6411                         out->maxs[j] = LittleLong(in->maxs[j]) + 1;
6412                 }
6413         }
6414
6415         // set the parent pointers
6416         Mod_BSP_LoadNodes_RecursiveSetParent(loadmodel->brush.data_nodes, NULL);
6417 }
6418
6419 static void Mod_Q3BSP_LoadLightGrid(lump_t *l)
6420 {
6421         q3dlightgrid_t *in;
6422         q3dlightgrid_t *out;
6423         int count;
6424         int i;
6425         int texturesize[3];
6426         unsigned char *texturergba, *texturelayer[3], *texturepadding[2];
6427         double lightgridmatrix[4][4];
6428
6429         in = (q3dlightgrid_t *)(mod_base + l->fileofs);
6430         if (l->filelen % sizeof(*in))
6431                 Host_Error("Mod_Q3BSP_LoadLightGrid: funny lump size in %s",loadmodel->name);
6432         loadmodel->brushq3.num_lightgrid_scale[0] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[0];
6433         loadmodel->brushq3.num_lightgrid_scale[1] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[1];
6434         loadmodel->brushq3.num_lightgrid_scale[2] = 1.0f / loadmodel->brushq3.num_lightgrid_cellsize[2];
6435         loadmodel->brushq3.num_lightgrid_imins[0] = (int)ceil(loadmodel->brushq3.data_models->mins[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6436         loadmodel->brushq3.num_lightgrid_imins[1] = (int)ceil(loadmodel->brushq3.data_models->mins[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6437         loadmodel->brushq3.num_lightgrid_imins[2] = (int)ceil(loadmodel->brushq3.data_models->mins[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6438         loadmodel->brushq3.num_lightgrid_imaxs[0] = (int)floor(loadmodel->brushq3.data_models->maxs[0] * loadmodel->brushq3.num_lightgrid_scale[0]);
6439         loadmodel->brushq3.num_lightgrid_imaxs[1] = (int)floor(loadmodel->brushq3.data_models->maxs[1] * loadmodel->brushq3.num_lightgrid_scale[1]);
6440         loadmodel->brushq3.num_lightgrid_imaxs[2] = (int)floor(loadmodel->brushq3.data_models->maxs[2] * loadmodel->brushq3.num_lightgrid_scale[2]);
6441         loadmodel->brushq3.num_lightgrid_isize[0] = loadmodel->brushq3.num_lightgrid_imaxs[0] - loadmodel->brushq3.num_lightgrid_imins[0] + 1;
6442         loadmodel->brushq3.num_lightgrid_isize[1] = loadmodel->brushq3.num_lightgrid_imaxs[1] - loadmodel->brushq3.num_lightgrid_imins[1] + 1;
6443         loadmodel->brushq3.num_lightgrid_isize[2] = loadmodel->brushq3.num_lightgrid_imaxs[2] - loadmodel->brushq3.num_lightgrid_imins[2] + 1;
6444         count = loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2];
6445         Matrix4x4_CreateScale3(&loadmodel->brushq3.num_lightgrid_indexfromworld, loadmodel->brushq3.num_lightgrid_scale[0], loadmodel->brushq3.num_lightgrid_scale[1], loadmodel->brushq3.num_lightgrid_scale[2]);
6446         Matrix4x4_ConcatTranslate(&loadmodel->brushq3.num_lightgrid_indexfromworld, -loadmodel->brushq3.num_lightgrid_imins[0] * loadmodel->brushq3.num_lightgrid_cellsize[0], -loadmodel->brushq3.num_lightgrid_imins[1] * loadmodel->brushq3.num_lightgrid_cellsize[1], -loadmodel->brushq3.num_lightgrid_imins[2] * loadmodel->brushq3.num_lightgrid_cellsize[2]);
6447
6448         // if lump is empty there is nothing to load, we can deal with that in the LightPoint code
6449         if (l->filelen)
6450         {
6451                 if (l->filelen < count * (int)sizeof(*in))
6452                 {
6453                         Con_Printf(CON_ERROR "Mod_Q3BSP_LoadLightGrid: invalid lightgrid lump size %i bytes, should be %i bytes (%ix%ix%i)", l->filelen, (int)(count * sizeof(*in)), loadmodel->brushq3.num_lightgrid_isize[0], loadmodel->brushq3.num_lightgrid_isize[1], loadmodel->brushq3.num_lightgrid_isize[2]);
6454                         return; // ignore the grid if we cannot understand it
6455                 }
6456                 if (l->filelen != count * (int)sizeof(*in))
6457                         Con_Printf(CON_WARN "Mod_Q3BSP_LoadLightGrid: Warning: calculated lightgrid size %i bytes does not match lump size %i\n", (int)(count * sizeof(*in)), l->filelen);
6458                 out = (q3dlightgrid_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
6459                 loadmodel->brushq3.data_lightgrid = out;
6460                 loadmodel->brushq3.num_lightgrid = count;
6461                 // no swapping or validation necessary
6462                 memcpy(out, in, count * (int)sizeof(*out));
6463
6464                 if(mod_q3bsp_sRGBlightmaps.integer)
6465                 {
6466                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6467                         {
6468                                 // we fix the brightness consistently via lightmapscale
6469                         }
6470                         else
6471                         {
6472                                 for(i = 0; i < count; ++i)
6473                                 {
6474                                         out[i].ambientrgb[0] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6475                                         out[i].ambientrgb[1] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6476                                         out[i].ambientrgb[2] = floor(Image_LinearFloatFromsRGB(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6477                                         out[i].diffusergb[0] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[0]) * 255.0f + 0.5f);
6478                                         out[i].diffusergb[1] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[1]) * 255.0f + 0.5f);
6479                                         out[i].diffusergb[2] = floor(Image_LinearFloatFromsRGB(out[i].diffusergb[2]) * 255.0f + 0.5f);
6480                                 }
6481                         }
6482                 }
6483                 else
6484                 {
6485                         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
6486                         {
6487                                 for(i = 0; i < count; ++i)
6488                                 {
6489                                         out[i].ambientrgb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[0]) * 255.0f + 0.5f);
6490                                         out[i].ambientrgb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[1]) * 255.0f + 0.5f);
6491                                         out[i].ambientrgb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].ambientrgb[2]) * 255.0f + 0.5f);
6492                                         out[i].diffusergb[0] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[0]) * 255.0f + 0.5f);
6493                                         out[i].diffusergb[1] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[1]) * 255.0f + 0.5f);
6494                                         out[i].diffusergb[2] = floor(Image_sRGBFloatFromLinear_Lightmap(out[i].diffusergb[2]) * 255.0f + 0.5f);
6495                                 }
6496                         }
6497                         else
6498                         {
6499                                 // all is good
6500                         }
6501                 }
6502
6503                 if (mod_q3bsp_lightgrid_texture.integer)
6504                 {
6505                         // build a texture to hold the data for per-pixel sampling
6506                         // this has 3 different kinds of data stacked in it:
6507                         // ambient color
6508                         // bent-normal light color
6509                         // bent-normal light dir
6510
6511                         texturesize[0] = loadmodel->brushq3.num_lightgrid_isize[0];
6512                         texturesize[1] = loadmodel->brushq3.num_lightgrid_isize[1];
6513                         texturesize[2] = (loadmodel->brushq3.num_lightgrid_isize[2] + 2) * 3;
6514                         texturergba = (unsigned char*)Mem_Alloc(loadmodel->mempool, texturesize[0] * texturesize[1] * texturesize[2] * sizeof(char[4]));
6515                         texturelayer[0] = texturergba + loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * 4;
6516                         texturelayer[1] = texturelayer[0] + (loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * (loadmodel->brushq3.num_lightgrid_isize[2] + 2)) * 4;
6517                         texturelayer[2] = texturelayer[1] + (loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * (loadmodel->brushq3.num_lightgrid_isize[2] + 2)) * 4;
6518                         // the light dir layer needs padding above/below it that is a neutral unsigned normal (127,127,127,255)
6519                         texturepadding[0] = texturelayer[2] - loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * 4;
6520                         texturepadding[1] = texturelayer[2] + loadmodel->brushq3.num_lightgrid_isize[0] * loadmodel->brushq3.num_lightgrid_isize[1] * loadmodel->brushq3.num_lightgrid_isize[2] * 4;
6521                         for (i = 0; i < texturesize[0] * texturesize[1]; i++)
6522                         {
6523                                 texturepadding[0][i * 4] = texturepadding[1][i * 4] = 127;
6524                                 texturepadding[0][i * 4 + 1] = texturepadding[1][i * 4 + 1] = 127;
6525                                 texturepadding[0][i * 4 + 2] = texturepadding[1][i * 4 + 2] = 127;
6526                                 texturepadding[0][i * 4 + 3] = texturepadding[1][i * 4 + 3] = 255;
6527                         }
6528                         for (i = 0; i < count; i++)
6529                         {
6530                                 texturelayer[0][i * 4 + 0] = out[i].ambientrgb[0];
6531                                 texturelayer[0][i * 4 + 1] = out[i].ambientrgb[1];
6532                                 texturelayer[0][i * 4 + 2] = out[i].ambientrgb[2];
6533                                 texturelayer[0][i * 4 + 3] = 255;
6534                                 texturelayer[1][i * 4 + 0] = out[i].diffusergb[0];
6535                                 texturelayer[1][i * 4 + 1] = out[i].diffusergb[1];
6536                                 texturelayer[1][i * 4 + 2] = out[i].diffusergb[2];
6537                                 texturelayer[1][i * 4 + 3] = 255;
6538                                 // this uses the mod_md3_sin table because the values are
6539                                 // already in the 0-255 range, the 64+ bias fetches a cosine
6540                                 // instead of a sine value
6541                                 texturelayer[2][i * 4 + 0] = (char)((mod_md3_sin[64 + out[i].diffuseyaw] * mod_md3_sin[out[i].diffusepitch]) * 127 + 127);
6542                                 texturelayer[2][i * 4 + 1] = (char)((mod_md3_sin[out[i].diffuseyaw] * mod_md3_sin[out[i].diffusepitch]) * 127 + 127);
6543                                 texturelayer[2][i * 4 + 2] = (char)((mod_md3_sin[64 + out[i].diffusepitch]) * 127 + 127);
6544                                 texturelayer[2][i * 4 + 3] = 255;
6545                         }
6546 #if 0
6547                         // debugging hack
6548                         int x, y, z;
6549                         for (z = 0; z < loadmodel->brushq3.num_lightgrid_isize[2]; z++)
6550                         {
6551                                 for (y = 0; y < loadmodel->brushq3.num_lightgrid_isize[1]; y++)
6552                                 {
6553                                         for (x = 0; x < loadmodel->brushq3.num_lightgrid_isize[0]; x++)
6554                                         {
6555                                                 i = (z * texturesize[1] + y) * texturesize[0] + x;
6556                                                 texturelayer[0][i * 4 + 0] = x * 256 / loadmodel->brushq3.num_lightgrid_isize[0];
6557                                                 texturelayer[0][i * 4 + 1] = y * 256 / loadmodel->brushq3.num_lightgrid_isize[1];
6558                                                 texturelayer[0][i * 4 + 2] = z * 256 / loadmodel->brushq3.num_lightgrid_isize[2];
6559                                         }
6560                                 }
6561                         }
6562 #endif
6563                         loadmodel->brushq3.lightgridtexturesize[0] = texturesize[0];
6564                         loadmodel->brushq3.lightgridtexturesize[1] = texturesize[1];
6565                         loadmodel->brushq3.lightgridtexturesize[2] = texturesize[2];
6566                         memset(lightgridmatrix[0], 0, sizeof(lightgridmatrix));
6567                         lightgridmatrix[0][0] = loadmodel->brushq3.num_lightgrid_scale[0] / texturesize[0];
6568                         lightgridmatrix[1][1] = loadmodel->brushq3.num_lightgrid_scale[1] / texturesize[1];
6569                         lightgridmatrix[2][2] = loadmodel->brushq3.num_lightgrid_scale[2] / texturesize[2];
6570                         lightgridmatrix[0][3] = -(loadmodel->brushq3.num_lightgrid_imins[0] - 0.5f) / texturesize[0];
6571                         lightgridmatrix[1][3] = -(loadmodel->brushq3.num_lightgrid_imins[1] - 0.5f) / texturesize[1];
6572                         lightgridmatrix[2][3] = -(loadmodel->brushq3.num_lightgrid_imins[2] - 1.5f) / texturesize[2];
6573                         lightgridmatrix[3][3] = 1;
6574                         Matrix4x4_FromArrayDoubleD3D(&loadmodel->brushq3.lightgridworldtotexturematrix, lightgridmatrix);
6575                         loadmodel->brushq3.lightgridtexture = R_LoadTexture3D(loadmodel->texturepool, "lightgrid", texturesize[0], texturesize[1], texturesize[2], texturergba, TEXTYPE_RGBA, TEXF_CLAMP, 0, NULL);
6576                         Mem_Free(texturergba);
6577                 }
6578         }
6579 }
6580
6581 static void Mod_Q3BSP_LoadPVS(lump_t *l)
6582 {
6583         q3dpvs_t *in;
6584         int totalchains;
6585
6586         if (l->filelen == 0)
6587         {
6588                 int i;
6589                 // unvised maps often have cluster indices even without pvs, so check
6590                 // leafs to find real number of clusters
6591                 loadmodel->brush.num_pvsclusters = 1;
6592                 for (i = 0;i < loadmodel->brush.num_leafs;i++)
6593                         loadmodel->brush.num_pvsclusters = max(loadmodel->brush.num_pvsclusters, loadmodel->brush.data_leafs[i].clusterindex + 1);
6594
6595                 // create clusters
6596                 loadmodel->brush.num_pvsclusterbytes = (loadmodel->brush.num_pvsclusters + 7) / 8;
6597                 totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6598                 loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6599                 memset(loadmodel->brush.data_pvsclusters, 0xFF, totalchains);
6600                 return;
6601         }
6602
6603         in = (q3dpvs_t *)(mod_base + l->fileofs);
6604         if (l->filelen < 9)
6605                 Host_Error("Mod_Q3BSP_LoadPVS: funny lump size in %s",loadmodel->name);
6606
6607         loadmodel->brush.num_pvsclusters = LittleLong(in->numclusters);
6608         loadmodel->brush.num_pvsclusterbytes = LittleLong(in->chainlength);
6609         if (loadmodel->brush.num_pvsclusterbytes < ((loadmodel->brush.num_pvsclusters + 7) / 8))
6610                 Host_Error("Mod_Q3BSP_LoadPVS: (chainlength = %i) < ((numclusters = %i) + 7) / 8", loadmodel->brush.num_pvsclusterbytes, loadmodel->brush.num_pvsclusters);
6611         totalchains = loadmodel->brush.num_pvsclusterbytes * loadmodel->brush.num_pvsclusters;
6612         if (l->filelen < totalchains + (int)sizeof(*in))
6613                 Host_Error("Mod_Q3BSP_LoadPVS: lump too small ((numclusters = %i) * (chainlength = %i) + sizeof(q3dpvs_t) == %i bytes, lump is %i bytes)", loadmodel->brush.num_pvsclusters, loadmodel->brush.num_pvsclusterbytes, (int)(totalchains + sizeof(*in)), l->filelen);
6614
6615         loadmodel->brush.data_pvsclusters = (unsigned char *)Mem_Alloc(loadmodel->mempool, totalchains);
6616         memcpy(loadmodel->brush.data_pvsclusters, (unsigned char *)(in + 1), totalchains);
6617 }
6618
6619 static void Mod_Q3BSP_LightPoint(model_t *model, const vec3_t p, vec3_t ambientcolor, vec3_t diffusecolor, vec3_t diffusenormal)
6620 {
6621         int i, j, k, index[3];
6622         float transformed[3], blend1, blend2, blend, stylescale = 1;
6623         q3dlightgrid_t *a, *s;
6624
6625         // scale lighting by lightstyle[0] so that darkmode in dpmod works properly
6626         // LadyHavoc: FIXME: is this true?
6627         stylescale = 1; // added while render
6628         //stylescale = r_refdef.scene.rtlightstylevalue[0];
6629
6630         if (!model->brushq3.num_lightgrid)
6631         {
6632                 ambientcolor[0] = stylescale;
6633                 ambientcolor[1] = stylescale;
6634                 ambientcolor[2] = stylescale;
6635                 return;
6636         }
6637
6638         Matrix4x4_Transform(&model->brushq3.num_lightgrid_indexfromworld, p, transformed);
6639         //Matrix4x4_Print(&model->brushq3.num_lightgrid_indexfromworld);
6640         //Con_Printf("%f %f %f transformed %f %f %f clamped ", p[0], p[1], p[2], transformed[0], transformed[1], transformed[2]);
6641         transformed[0] = bound(0, transformed[0], model->brushq3.num_lightgrid_isize[0] - 1);
6642         transformed[1] = bound(0, transformed[1], model->brushq3.num_lightgrid_isize[1] - 1);
6643         transformed[2] = bound(0, transformed[2], model->brushq3.num_lightgrid_isize[2] - 1);
6644         index[0] = (int)floor(transformed[0]);
6645         index[1] = (int)floor(transformed[1]);
6646         index[2] = (int)floor(transformed[2]);
6647         //Con_Printf("%f %f %f index %i %i %i:\n", transformed[0], transformed[1], transformed[2], index[0], index[1], index[2]);
6648
6649         // now lerp the values
6650         VectorClear(diffusenormal);
6651         a = &model->brushq3.data_lightgrid[(index[2] * model->brushq3.num_lightgrid_isize[1] + index[1]) * model->brushq3.num_lightgrid_isize[0] + index[0]];
6652         for (k = 0;k < 2;k++)
6653         {
6654                 blend1 = (k ? (transformed[2] - index[2]) : (1 - (transformed[2] - index[2])));
6655                 if (blend1 < 0.001f || index[2] + k >= model->brushq3.num_lightgrid_isize[2])
6656                         continue;
6657                 for (j = 0;j < 2;j++)
6658                 {
6659                         blend2 = blend1 * (j ? (transformed[1] - index[1]) : (1 - (transformed[1] - index[1])));
6660                         if (blend2 < 0.001f || index[1] + j >= model->brushq3.num_lightgrid_isize[1])
6661                                 continue;
6662                         for (i = 0;i < 2;i++)
6663                         {
6664                                 blend = blend2 * (i ? (transformed[0] - index[0]) : (1 - (transformed[0] - index[0]))) * stylescale;
6665                                 if (blend < 0.001f || index[0] + i >= model->brushq3.num_lightgrid_isize[0])
6666                                         continue;
6667                                 s = a + (k * model->brushq3.num_lightgrid_isize[1] + j) * model->brushq3.num_lightgrid_isize[0] + i;
6668                                 VectorMA(ambientcolor, blend * (1.0f / 128.0f), s->ambientrgb, ambientcolor);
6669                                 VectorMA(diffusecolor, blend * (1.0f / 128.0f), s->diffusergb, diffusecolor);
6670                                 // this uses the mod_md3_sin table because the values are
6671                                 // already in the 0-255 range, the 64+ bias fetches a cosine
6672                                 // instead of a sine value
6673                                 diffusenormal[0] += blend * (mod_md3_sin[64 + s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6674                                 diffusenormal[1] += blend * (mod_md3_sin[     s->diffuseyaw] * mod_md3_sin[s->diffusepitch]);
6675                                 diffusenormal[2] += blend * (mod_md3_sin[64 + s->diffusepitch]);
6676                                 //Con_Printf("blend %f: ambient %i %i %i, diffuse %i %i %i, diffusepitch %i diffuseyaw %i (%f %f, normal %f %f %f)\n", blend, s->ambientrgb[0], s->ambientrgb[1], s->ambientrgb[2], s->diffusergb[0], s->diffusergb[1], s->diffusergb[2], s->diffusepitch, s->diffuseyaw, pitch, yaw, (cos(yaw) * cospitch), (sin(yaw) * cospitch), (-sin(pitch)));
6677                         }
6678                 }
6679         }
6680
6681         // normalize the light direction before turning
6682         VectorNormalize(diffusenormal);
6683         //Con_Printf("result: ambient %f %f %f diffuse %f %f %f diffusenormal %f %f %f\n", ambientcolor[0], ambientcolor[1], ambientcolor[2], diffusecolor[0], diffusecolor[1], diffusecolor[2], diffusenormal[0], diffusenormal[1], diffusenormal[2]);
6684 }
6685
6686 static int Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(mnode_t *node, double p1[3], double p2[3], double endpos[3])
6687 {
6688         double t1, t2;
6689         double midf, mid[3];
6690         int ret, side;
6691
6692         // check for empty
6693         while (node->plane)
6694         {
6695                 // find the point distances
6696                 mplane_t *plane = node->plane;
6697                 if (plane->type < 3)
6698                 {
6699                         t1 = p1[plane->type] - plane->dist;
6700                         t2 = p2[plane->type] - plane->dist;
6701                 }
6702                 else
6703                 {
6704                         t1 = DotProduct (plane->normal, p1) - plane->dist;
6705                         t2 = DotProduct (plane->normal, p2) - plane->dist;
6706                 }
6707
6708                 if (t1 < 0)
6709                 {
6710                         if (t2 < 0)
6711                         {
6712                                 node = node->children[1];
6713                                 continue;
6714                         }
6715                         side = 1;
6716                 }
6717                 else
6718                 {
6719                         if (t2 >= 0)
6720                         {
6721                                 node = node->children[0];
6722                                 continue;
6723                         }
6724                         side = 0;
6725                 }
6726
6727                 midf = t1 / (t1 - t2);
6728                 VectorLerp(p1, midf, p2, mid);
6729
6730                 // recurse both sides, front side first
6731                 // return 2 if empty is followed by solid (hit something)
6732                 // do not return 2 if both are solid or both empty,
6733                 // or if start is solid and end is empty
6734                 // as these degenerate cases usually indicate the eye is in solid and
6735                 // should see the target point anyway
6736                 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side    ], p1, mid, endpos);
6737                 if (ret != 0)
6738                         return ret;
6739                 ret = Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(node->children[side ^ 1], mid, p2, endpos);
6740                 if (ret != 1)
6741                         return ret;
6742                 VectorCopy(mid, endpos);
6743                 return 2;
6744         }
6745         return ((mleaf_t *)node)->clusterindex < 0;
6746 }
6747
6748 static qbool Mod_Q3BSP_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
6749 {
6750         if (model->brush.submodel || mod_q3bsp_tracelineofsight_brushes.integer)
6751         {
6752                 trace_t trace;
6753                 model->TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
6754                 return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
6755         }
6756         else
6757         {
6758                 double tracestart[3], traceend[3], traceendpos[3];
6759                 VectorCopy(start, tracestart);
6760                 VectorCopy(end, traceend);
6761                 VectorCopy(end, traceendpos);
6762                 Mod_Q3BSP_TraceLineOfSight_RecursiveNodeCheck(model->brush.data_nodes, tracestart, traceend, traceendpos);
6763                 return BoxesOverlap(traceendpos, traceendpos, acceptmins, acceptmaxs);
6764         }
6765 }
6766
6767 void Mod_CollisionBIH_TracePoint(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
6768 {
6769         const bih_t *bih;
6770         const bih_leaf_t *leaf;
6771         const bih_node_t *node;
6772         const colbrushf_t *brush;
6773         int axis;
6774         int nodenum;
6775         int nodestackpos = 0;
6776         int nodestack[1024];
6777
6778         memset(trace, 0, sizeof(*trace));
6779         trace->fraction = 1;
6780         trace->hitsupercontentsmask = hitsupercontentsmask;
6781         trace->skipsupercontentsmask = skipsupercontentsmask;
6782         trace->skipmaterialflagsmask = skipmaterialflagsmask;
6783
6784         bih = &model->collision_bih;
6785         if(!bih->nodes)
6786                 return;
6787
6788         nodenum = bih->rootnode;
6789         nodestack[nodestackpos++] = nodenum;
6790         while (nodestackpos)
6791         {
6792                 nodenum = nodestack[--nodestackpos];
6793                 node = bih->nodes + nodenum;
6794 #if 1
6795                 if (!BoxesOverlap(start, start, node->mins, node->maxs))
6796                         continue;
6797 #endif
6798                 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6799                 {
6800                         axis = node->type - BIH_SPLITX;
6801                         if (start[axis] >= node->frontmin)
6802                                 nodestack[nodestackpos++] = node->front;
6803                         if (start[axis] <= node->backmax)
6804                                 nodestack[nodestackpos++] = node->back;
6805                 }
6806                 else if (node->type == BIH_UNORDERED)
6807                 {
6808                         for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6809                         {
6810                                 leaf = bih->leafs + node->children[axis];
6811 #if 1
6812                                 if (!BoxesOverlap(start, start, leaf->mins, leaf->maxs))
6813                                         continue;
6814 #endif
6815                                 switch(leaf->type)
6816                                 {
6817                                 case BIH_BRUSH:
6818                                         brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6819                                         Collision_TracePointBrushFloat(trace, start, brush);
6820                                         break;
6821                                 case BIH_COLLISIONTRIANGLE:
6822                                         // collision triangle - skipped because they have no volume
6823                                         break;
6824                                 case BIH_RENDERTRIANGLE:
6825                                         // render triangle - skipped because they have no volume
6826                                         break;
6827                                 }
6828                         }
6829                 }
6830         }
6831 }
6832
6833 static void Mod_CollisionBIH_TraceLineShared(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask, const bih_t *bih)
6834 {
6835         const bih_leaf_t *leaf;
6836         const bih_node_t *node;
6837         const colbrushf_t *brush;
6838         const int *e;
6839         const texture_t *texture;
6840         vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6841         vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6842         int axis, nodenum, nodestackpos = 0, nodestack[1024];
6843
6844         if(!bih->nodes)
6845                 return;
6846
6847         if (VectorCompare(start, end))
6848         {
6849                 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6850                 return;
6851         }
6852
6853         nodenum = bih->rootnode;
6854
6855         memset(trace, 0, sizeof(*trace));
6856         trace->fraction = 1;
6857         trace->hitsupercontentsmask = hitsupercontentsmask;
6858         trace->skipsupercontentsmask = skipsupercontentsmask;
6859         trace->skipmaterialflagsmask = skipmaterialflagsmask;
6860
6861         // push first node
6862         nodestackline[nodestackpos][0] = start[0];
6863         nodestackline[nodestackpos][1] = start[1];
6864         nodestackline[nodestackpos][2] = start[2];
6865         nodestackline[nodestackpos][3] = end[0];
6866         nodestackline[nodestackpos][4] = end[1];
6867         nodestackline[nodestackpos][5] = end[2];
6868         nodestack[nodestackpos++] = nodenum;
6869         while (nodestackpos)
6870         {
6871                 nodenum = nodestack[--nodestackpos];
6872                 node = bih->nodes + nodenum;
6873                 VectorCopy(nodestackline[nodestackpos], nodestart);
6874                 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
6875                 sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6876                 sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6877                 sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6878                 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6879                 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6880                 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6881                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs) && !collision_bih_fullrecursion.integer)
6882                         continue;
6883                 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
6884                 {
6885                         // recurse children of the split
6886                         axis = node->type - BIH_SPLITX;
6887                         d1 = node->backmax - nodestart[axis];
6888                         d2 = node->backmax - nodeend[axis];
6889                         d3 = nodestart[axis] - node->frontmin;
6890                         d4 = nodeend[axis] - node->frontmin;
6891                         if (collision_bih_fullrecursion.integer)
6892                                 d1 = d2 = d3 = d4 = 1; // force full recursion
6893                         switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
6894                         {
6895                         case  0: /* >>>> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6896                         case  1: /* <>>> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6897                         case  2: /* ><>> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6898                         case  3: /* <<>> */                                                                                                                                                                                                                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6899                         case  4: /* >><> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6900                         case  5: /* <><> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6901                         case  6: /* ><<> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6902                         case  7: /* <<<> */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6903                         case  8: /* >>>< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6904                         case  9: /* <>>< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6905                         case 10: /* ><>< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6906                         case 11: /* <<>< */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
6907                         case 12: /* >><< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6908                         case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6909                         case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
6910                         case 15: /* <<<< */                                                                                                                                                                                                                                                                                                                                                                                                   break;
6911                         }
6912                 }
6913                 else if (node->type == BIH_UNORDERED)
6914                 {
6915                         // calculate sweep bounds for this node
6916                         // copy node bounds into local variables
6917                         VectorCopy(node->mins, nodebigmins);
6918                         VectorCopy(node->maxs, nodebigmaxs);
6919                         // clip line to this node bounds
6920                         axis = 0; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6921                         axis = 1; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6922                         axis = 2; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
6923                         // some of the line intersected the enlarged node box
6924                         // calculate sweep bounds for this node
6925                         sweepnodemins[0] = min(nodestart[0], nodeend[0]) - 1;
6926                         sweepnodemins[1] = min(nodestart[1], nodeend[1]) - 1;
6927                         sweepnodemins[2] = min(nodestart[2], nodeend[2]) - 1;
6928                         sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + 1;
6929                         sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + 1;
6930                         sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + 1;
6931                         for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
6932                         {
6933                                 leaf = bih->leafs + node->children[axis];
6934                                 // TODO: This is very expensive in Steel Storm. Framerate halved during even light combat.
6935                                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
6936                                         continue;
6937                                 switch(leaf->type)
6938                                 {
6939                                 case BIH_BRUSH:
6940                                         brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
6941                                         Collision_TraceLineBrushFloat(trace, start, end, brush, brush);
6942                                         break;
6943                                 case BIH_COLLISIONTRIANGLE:
6944                                         if (!mod_q3bsp_curves_collisions.integer)
6945                                                 continue;
6946                                         e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
6947                                         texture = model->data_textures + leaf->textureindex;
6948                                         Collision_TraceLineTriangleFloat(trace, start, end, model->brush.data_collisionvertex3f + e[0] * 3, model->brush.data_collisionvertex3f + e[1] * 3, model->brush.data_collisionvertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6949                                         break;
6950                                 case BIH_RENDERTRIANGLE:
6951                                         e = model->surfmesh.data_element3i + 3*leaf->itemindex;
6952                                         texture = model->data_textures + leaf->textureindex;
6953                                         Collision_TraceLineTriangleFloat(trace, start, end, model->surfmesh.data_vertex3f + e[0] * 3, model->surfmesh.data_vertex3f + e[1] * 3, model->surfmesh.data_vertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
6954                                         break;
6955                                 }
6956                         }
6957                 }
6958         }
6959 }
6960
6961 void Mod_CollisionBIH_TraceLine(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
6962 {
6963         if (VectorCompare(start, end))
6964         {
6965                 Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, start, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6966                 return;
6967         }
6968         Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->collision_bih);
6969 }
6970
6971 void Mod_CollisionBIH_TraceBrush(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, colbrushf_t *thisbrush_start, colbrushf_t *thisbrush_end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
6972 {
6973         const bih_t *bih;
6974         const bih_leaf_t *leaf;
6975         const bih_node_t *node;
6976         const colbrushf_t *brush;
6977         const int *e;
6978         const texture_t *texture;
6979         vec3_t start, end, startmins, startmaxs, endmins, endmaxs, mins, maxs;
6980         vec3_t nodebigmins, nodebigmaxs, nodestart, nodeend, sweepnodemins, sweepnodemaxs;
6981         vec_t d1, d2, d3, d4, f, nodestackline[1024][6];
6982         int axis, nodenum, nodestackpos = 0, nodestack[1024];
6983
6984         if (mod_q3bsp_optimizedtraceline.integer && VectorCompare(thisbrush_start->mins, thisbrush_start->maxs) && VectorCompare(thisbrush_end->mins, thisbrush_end->maxs))
6985         {
6986                 if (VectorCompare(thisbrush_start->mins, thisbrush_end->mins))
6987                         Mod_CollisionBIH_TracePoint(model, frameblend, skeleton, trace, thisbrush_start->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6988                 else
6989                         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, thisbrush_start->mins, thisbrush_end->mins, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
6990                 return;
6991         }
6992
6993         bih = &model->collision_bih;
6994         if(!bih->nodes)
6995                 return;
6996         nodenum = bih->rootnode;
6997
6998         // box trace, performed as brush trace
6999         memset(trace, 0, sizeof(*trace));
7000         trace->fraction = 1;
7001         trace->hitsupercontentsmask = hitsupercontentsmask;
7002         trace->skipsupercontentsmask = skipsupercontentsmask;
7003         trace->skipmaterialflagsmask = skipmaterialflagsmask;
7004
7005         // calculate tracebox-like parameters for efficient culling
7006         VectorMAM(0.5f, thisbrush_start->mins, 0.5f, thisbrush_start->maxs, start);
7007         VectorMAM(0.5f, thisbrush_end->mins, 0.5f, thisbrush_end->maxs, end);
7008         VectorSubtract(thisbrush_start->mins, start, startmins);
7009         VectorSubtract(thisbrush_start->maxs, start, startmaxs);
7010         VectorSubtract(thisbrush_end->mins, end, endmins);
7011         VectorSubtract(thisbrush_end->maxs, end, endmaxs);
7012         mins[0] = min(startmins[0], endmins[0]);
7013         mins[1] = min(startmins[1], endmins[1]);
7014         mins[2] = min(startmins[2], endmins[2]);
7015         maxs[0] = max(startmaxs[0], endmaxs[0]);
7016         maxs[1] = max(startmaxs[1], endmaxs[1]);
7017         maxs[2] = max(startmaxs[2], endmaxs[2]);
7018
7019         // push first node
7020         nodestackline[nodestackpos][0] = start[0];
7021         nodestackline[nodestackpos][1] = start[1];
7022         nodestackline[nodestackpos][2] = start[2];
7023         nodestackline[nodestackpos][3] = end[0];
7024         nodestackline[nodestackpos][4] = end[1];
7025         nodestackline[nodestackpos][5] = end[2];
7026         nodestack[nodestackpos++] = nodenum;
7027         while (nodestackpos)
7028         {
7029                 nodenum = nodestack[--nodestackpos];
7030                 node = bih->nodes + nodenum;
7031                 VectorCopy(nodestackline[nodestackpos], nodestart);
7032                 VectorCopy(nodestackline[nodestackpos] + 3, nodeend);
7033                 sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7034                 sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7035                 sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7036                 sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7037                 sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7038                 sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7039                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, node->mins, node->maxs))
7040                         continue;
7041                 if (node->type <= BIH_SPLITZ && nodestackpos+2 <= 1024)
7042                 {
7043                         // recurse children of the split
7044                         axis = node->type - BIH_SPLITX;
7045                         d1 = node->backmax - nodestart[axis] - mins[axis];
7046                         d2 = node->backmax - nodeend[axis] - mins[axis];
7047                         d3 = nodestart[axis] - node->frontmin + maxs[axis];
7048                         d4 = nodeend[axis] - node->frontmin + maxs[axis];
7049                         switch((d1 < 0) | ((d2 < 0) << 1) | ((d3 < 0) << 2) | ((d4 < 0) << 3))
7050                         {
7051                         case  0: /* >>>> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7052                         case  1: /* <>>> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7053                         case  2: /* ><>> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7054                         case  3: /* <<>> */                                                                                                                                                                                                                      VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7055                         case  4: /* >><> */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7056                         case  5: /* <><> */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7057                         case  6: /* ><<> */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7058                         case  7: /* <<<> */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7059                         case  8: /* >>>< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7060                         case  9: /* <>>< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7061                         case 10: /* ><>< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7062                         case 11: /* <<>< */                                                                                                                                                                                                  f = d3 / (d3 - d4); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->front; break;
7063                         case 12: /* >><< */                     VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
7064                         case 13: /* <><< */ f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos]); VectorCopy(              nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
7065                         case 14: /* ><<< */ f = d1 / (d1 - d2); VectorCopy(nodestart,             nodestackline[nodestackpos]); VectorLerp(nodestart, f, nodeend, nodestackline[nodestackpos] + 3); nodestack[nodestackpos++] = node->back;                                                                                                                                                                                                   break;
7066                         case 15: /* <<<< */                                                                                                                                                                                                                                                                                                                                                                                                   break;
7067                         }
7068                 }
7069                 else if (node->type == BIH_UNORDERED)
7070                 {
7071                         // calculate sweep bounds for this node
7072                         // copy node bounds into local variables and expand to get Minkowski Sum of the two shapes
7073                         VectorSubtract(node->mins, maxs, nodebigmins);
7074                         VectorSubtract(node->maxs, mins, nodebigmaxs);
7075                         // clip line to this node bounds
7076                         axis = 0; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
7077                         axis = 1; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
7078                         axis = 2; d1 = nodestart[axis] - nodebigmins[axis]; d2 = nodeend[axis] - nodebigmins[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); } d1 = nodebigmaxs[axis] - nodestart[axis]; d2 = nodebigmaxs[axis] - nodeend[axis]; if (d1 < 0) { if (d2 < 0) continue; f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodestart); } else if (d2 < 0) { f = d1 / (d1 - d2); VectorLerp(nodestart, f, nodeend, nodeend); }
7079                         // some of the line intersected the enlarged node box
7080                         // calculate sweep bounds for this node
7081                         sweepnodemins[0] = min(nodestart[0], nodeend[0]) + mins[0] - 1;
7082                         sweepnodemins[1] = min(nodestart[1], nodeend[1]) + mins[1] - 1;
7083                         sweepnodemins[2] = min(nodestart[2], nodeend[2]) + mins[2] - 1;
7084                         sweepnodemaxs[0] = max(nodestart[0], nodeend[0]) + maxs[0] + 1;
7085                         sweepnodemaxs[1] = max(nodestart[1], nodeend[1]) + maxs[1] + 1;
7086                         sweepnodemaxs[2] = max(nodestart[2], nodeend[2]) + maxs[2] + 1;
7087                         for (axis = 0;axis < BIH_MAXUNORDEREDCHILDREN && node->children[axis] >= 0;axis++)
7088                         {
7089                                 leaf = bih->leafs + node->children[axis];
7090                                 if (!BoxesOverlap(sweepnodemins, sweepnodemaxs, leaf->mins, leaf->maxs))
7091                                         continue;
7092                                 switch(leaf->type)
7093                                 {
7094                                 case BIH_BRUSH:
7095                                         brush = model->brush.data_brushes[leaf->itemindex].colbrushf;
7096                                         Collision_TraceBrushBrushFloat(trace, thisbrush_start, thisbrush_end, brush, brush);
7097                                         break;
7098                                 case BIH_COLLISIONTRIANGLE:
7099                                         if (!mod_q3bsp_curves_collisions.integer)
7100                                                 continue;
7101                                         e = model->brush.data_collisionelement3i + 3*leaf->itemindex;
7102                                         texture = model->data_textures + leaf->textureindex;
7103                                         Collision_TraceBrushTriangleFloat(trace, thisbrush_start, thisbrush_end, model->brush.data_collisionvertex3f + e[0] * 3, model->brush.data_collisionvertex3f + e[1] * 3, model->brush.data_collisionvertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
7104                                         break;
7105                                 case BIH_RENDERTRIANGLE:
7106                                         e = model->surfmesh.data_element3i + 3*leaf->itemindex;
7107                                         texture = model->data_textures + leaf->textureindex;
7108                                         Collision_TraceBrushTriangleFloat(trace, thisbrush_start, thisbrush_end, model->surfmesh.data_vertex3f + e[0] * 3, model->surfmesh.data_vertex3f + e[1] * 3, model->surfmesh.data_vertex3f + e[2] * 3, texture->supercontents, texture->surfaceflags, texture);
7109                                         break;
7110                                 }
7111                         }
7112                 }
7113         }
7114 }
7115
7116 void Mod_CollisionBIH_TraceBox(model_t *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, int skipsupercontentsmask, int skipmaterialflagsmask)
7117 {
7118         colboxbrushf_t thisbrush_start, thisbrush_end;
7119         vec3_t boxstartmins, boxstartmaxs, boxendmins, boxendmaxs;
7120
7121         // box trace, performed as brush trace
7122         VectorAdd(start, boxmins, boxstartmins);
7123         VectorAdd(start, boxmaxs, boxstartmaxs);
7124         VectorAdd(end, boxmins, boxendmins);
7125         VectorAdd(end, boxmaxs, boxendmaxs);
7126         Collision_BrushForBox(&thisbrush_start, boxstartmins, boxstartmaxs, 0, 0, NULL);
7127         Collision_BrushForBox(&thisbrush_end, boxendmins, boxendmaxs, 0, 0, NULL);
7128         Mod_CollisionBIH_TraceBrush(model, frameblend, skeleton, trace, &thisbrush_start.brush, &thisbrush_end.brush, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7129 }
7130
7131
7132 int Mod_CollisionBIH_PointSuperContents(struct model_s *model, int frame, const vec3_t point)
7133 {
7134         trace_t trace;
7135         Mod_CollisionBIH_TracePoint(model, NULL, NULL, &trace, point, 0, 0, 0);
7136         return trace.startsupercontents;
7137 }
7138
7139 qbool Mod_CollisionBIH_TraceLineOfSight(struct model_s *model, const vec3_t start, const vec3_t end, const vec3_t acceptmins, const vec3_t acceptmaxs)
7140 {
7141         trace_t trace;
7142         Mod_CollisionBIH_TraceLine(model, NULL, NULL, &trace, start, end, SUPERCONTENTS_VISBLOCKERMASK, 0, MATERIALFLAGMASK_TRANSLUCENT);
7143         return trace.fraction == 1 || BoxesOverlap(trace.endpos, trace.endpos, acceptmins, acceptmaxs);
7144 }
7145
7146 void Mod_CollisionBIH_TracePoint_Mesh(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
7147 {
7148 #if 0
7149         // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7150         vec3_t end;
7151         int hitsupercontents;
7152         VectorSet(end, start[0], start[1], model->normalmins[2]);
7153 #endif
7154         memset(trace, 0, sizeof(*trace));
7155         trace->fraction = 1;
7156         trace->hitsupercontentsmask = hitsupercontentsmask;
7157         trace->skipsupercontentsmask = skipsupercontentsmask;
7158         trace->skipmaterialflagsmask = skipmaterialflagsmask;
7159 #if 0
7160         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7161         hitsupercontents = trace->hitsupercontents;
7162         memset(trace, 0, sizeof(*trace));
7163         trace->fraction = 1;
7164         trace->hitsupercontentsmask = hitsupercontentsmask;
7165         trace->skipsupercontentsmask = skipsupercontentsmask;
7166         trace->skipmaterialflagsmask = skipmaterialflagsmask;
7167         trace->startsupercontents = hitsupercontents;
7168 #endif
7169 }
7170
7171 int Mod_CollisionBIH_PointSuperContents_Mesh(struct model_s *model, int frame, const vec3_t start)
7172 {
7173 #if 0
7174         // broken - needs to be modified to count front faces and backfaces to figure out if it is in solid
7175         trace_t trace;
7176         vec3_t end;
7177         VectorSet(end, start[0], start[1], model->normalmins[2]);
7178         memset(&trace, 0, sizeof(trace));
7179         trace.fraction = 1;
7180         trace.hitsupercontentsmask = hitsupercontentsmask;
7181         trace.skipsupercontentsmask = skipsupercontentsmask;
7182         trace.skipmaterialflagsmask = skipmaterialflagsmask;
7183         Mod_CollisionBIH_TraceLine(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask);
7184         return trace.hitsupercontents;
7185 #else
7186         return 0;
7187 #endif
7188 }
7189
7190 void Mod_CollisionBIH_TraceLineAgainstSurfaces(model_t *model, const frameblend_t *frameblend, const skeleton_t *skeleton, trace_t *trace, const vec3_t start, const vec3_t end, int hitsupercontentsmask, int skipsupercontentsmask, int skipmaterialflagsmask)
7191 {
7192         Mod_CollisionBIH_TraceLineShared(model, frameblend, skeleton, trace, start, end, hitsupercontentsmask, skipsupercontentsmask, skipmaterialflagsmask, &model->render_bih);
7193 }
7194
7195
7196 bih_t *Mod_MakeCollisionBIH(model_t *model, qbool userendersurfaces, bih_t *out)
7197 {
7198         int j;
7199         int bihnumleafs;
7200         int bihmaxnodes;
7201         int brushindex;
7202         int triangleindex;
7203         int bihleafindex;
7204         int nummodelbrushes = model->nummodelbrushes;
7205         const int *e;
7206         const int *collisionelement3i;
7207         const float *collisionvertex3f;
7208         const int *renderelement3i;
7209         const float *rendervertex3f;
7210         bih_leaf_t *bihleafs;
7211         bih_node_t *bihnodes;
7212         int *temp_leafsort;
7213         int *temp_leafsortscratch;
7214         const msurface_t *surface;
7215         const q3mbrush_t *brush;
7216
7217         // find out how many BIH leaf nodes we need
7218         bihnumleafs = 0;
7219         if (userendersurfaces)
7220         {
7221                 for (j = model->submodelsurfaces_start;j < model->submodelsurfaces_end;j++)
7222                         bihnumleafs += model->data_surfaces[j].num_triangles;
7223         }
7224         else
7225         {
7226                 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7227                         if (brush->colbrushf)
7228                                 bihnumleafs++;
7229                 for (j = model->submodelsurfaces_start;j < model->submodelsurfaces_end;j++)
7230                 {
7231                         if (model->data_surfaces[j].texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS)
7232                                 bihnumleafs += model->data_surfaces[j].num_triangles + model->data_surfaces[j].num_collisiontriangles;
7233                         else
7234                                 bihnumleafs += model->data_surfaces[j].num_collisiontriangles;
7235                 }
7236         }
7237
7238         if (!bihnumleafs)
7239                 return NULL;
7240
7241         // allocate the memory for the BIH leaf nodes
7242         bihleafs = (bih_leaf_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_leaf_t) * bihnumleafs);
7243
7244         // now populate the BIH leaf nodes
7245         bihleafindex = 0;
7246
7247         // add render surfaces
7248         renderelement3i = model->surfmesh.data_element3i;
7249         rendervertex3f = model->surfmesh.data_vertex3f;
7250         for (j = model->submodelsurfaces_start; j < model->submodelsurfaces_end; j++)
7251         {
7252                 surface = model->data_surfaces + j;
7253                 for (triangleindex = 0, e = renderelement3i + 3*surface->num_firsttriangle;triangleindex < surface->num_triangles;triangleindex++, e += 3)
7254                 {
7255                         if (!userendersurfaces && !(surface->texture->basematerialflags & MATERIALFLAG_MESHCOLLISIONS))
7256                                 continue;
7257                         bihleafs[bihleafindex].type = BIH_RENDERTRIANGLE;
7258                         bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7259                         bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7260                         bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firsttriangle;
7261                         bihleafs[bihleafindex].mins[0] = min(rendervertex3f[3*e[0]+0], min(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) - 1;
7262                         bihleafs[bihleafindex].mins[1] = min(rendervertex3f[3*e[0]+1], min(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) - 1;
7263                         bihleafs[bihleafindex].mins[2] = min(rendervertex3f[3*e[0]+2], min(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) - 1;
7264                         bihleafs[bihleafindex].maxs[0] = max(rendervertex3f[3*e[0]+0], max(rendervertex3f[3*e[1]+0], rendervertex3f[3*e[2]+0])) + 1;
7265                         bihleafs[bihleafindex].maxs[1] = max(rendervertex3f[3*e[0]+1], max(rendervertex3f[3*e[1]+1], rendervertex3f[3*e[2]+1])) + 1;
7266                         bihleafs[bihleafindex].maxs[2] = max(rendervertex3f[3*e[0]+2], max(rendervertex3f[3*e[1]+2], rendervertex3f[3*e[2]+2])) + 1;
7267                         bihleafindex++;
7268                 }
7269         }
7270
7271         if (!userendersurfaces)
7272         {
7273                 // add collision brushes
7274                 for (brushindex = 0, brush = model->brush.data_brushes + brushindex+model->firstmodelbrush;brushindex < nummodelbrushes;brushindex++, brush++)
7275                 {
7276                         if (!brush->colbrushf)
7277                                 continue;
7278                         bihleafs[bihleafindex].type = BIH_BRUSH;
7279                         bihleafs[bihleafindex].textureindex = brush->texture - model->data_textures;
7280                         bihleafs[bihleafindex].surfaceindex = -1;
7281                         bihleafs[bihleafindex].itemindex = brushindex+model->firstmodelbrush;
7282                         VectorCopy(brush->colbrushf->mins, bihleafs[bihleafindex].mins);
7283                         VectorCopy(brush->colbrushf->maxs, bihleafs[bihleafindex].maxs);
7284                         bihleafindex++;
7285                 }
7286
7287                 // add collision surfaces
7288                 collisionelement3i = model->brush.data_collisionelement3i;
7289                 collisionvertex3f = model->brush.data_collisionvertex3f;
7290                 for (j = model->submodelsurfaces_start; j < model->submodelsurfaces_end; j++)
7291                 {
7292                         surface = model->data_surfaces + j;
7293                         for (triangleindex = 0, e = collisionelement3i + 3*surface->num_firstcollisiontriangle;triangleindex < surface->num_collisiontriangles;triangleindex++, e += 3)
7294                         {
7295                                 bihleafs[bihleafindex].type = BIH_COLLISIONTRIANGLE;
7296                                 bihleafs[bihleafindex].textureindex = surface->texture - model->data_textures;
7297                                 bihleafs[bihleafindex].surfaceindex = surface - model->data_surfaces;
7298                                 bihleafs[bihleafindex].itemindex = triangleindex+surface->num_firstcollisiontriangle;
7299                                 bihleafs[bihleafindex].mins[0] = min(collisionvertex3f[3*e[0]+0], min(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) - 1;
7300                                 bihleafs[bihleafindex].mins[1] = min(collisionvertex3f[3*e[0]+1], min(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) - 1;
7301                                 bihleafs[bihleafindex].mins[2] = min(collisionvertex3f[3*e[0]+2], min(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) - 1;
7302                                 bihleafs[bihleafindex].maxs[0] = max(collisionvertex3f[3*e[0]+0], max(collisionvertex3f[3*e[1]+0], collisionvertex3f[3*e[2]+0])) + 1;
7303                                 bihleafs[bihleafindex].maxs[1] = max(collisionvertex3f[3*e[0]+1], max(collisionvertex3f[3*e[1]+1], collisionvertex3f[3*e[2]+1])) + 1;
7304                                 bihleafs[bihleafindex].maxs[2] = max(collisionvertex3f[3*e[0]+2], max(collisionvertex3f[3*e[1]+2], collisionvertex3f[3*e[2]+2])) + 1;
7305                                 bihleafindex++;
7306                         }
7307                 }
7308         }
7309
7310         // allocate buffers for the produced and temporary data
7311         bihmaxnodes = bihnumleafs + 1;
7312         bihnodes = (bih_node_t *)Mem_Alloc(loadmodel->mempool, sizeof(bih_node_t) * bihmaxnodes);
7313         temp_leafsort = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * bihnumleafs * 2);
7314         temp_leafsortscratch = temp_leafsort + bihnumleafs;
7315
7316         // now build it
7317         BIH_Build(out, bihnumleafs, bihleafs, bihmaxnodes, bihnodes, temp_leafsort, temp_leafsortscratch);
7318
7319         // we're done with the temporary data
7320         Mem_Free(temp_leafsort);
7321
7322         // resize the BIH nodes array if it over-allocated
7323         if (out->maxnodes > out->numnodes)
7324         {
7325                 out->maxnodes = out->numnodes;
7326                 out->nodes = (bih_node_t *)Mem_Realloc(loadmodel->mempool, out->nodes, out->numnodes * sizeof(bih_node_t));
7327         }
7328
7329         return out;
7330 }
7331
7332 static int Mod_Q3BSP_SuperContentsFromNativeContents(int nativecontents)
7333 {
7334         int supercontents = 0;
7335         if (nativecontents & CONTENTSQ3_SOLID)
7336                 supercontents |= SUPERCONTENTS_SOLID;
7337         if (nativecontents & CONTENTSQ3_WATER)
7338                 supercontents |= SUPERCONTENTS_WATER;
7339         if (nativecontents & CONTENTSQ3_SLIME)
7340                 supercontents |= SUPERCONTENTS_SLIME;
7341         if (nativecontents & CONTENTSQ3_LAVA)
7342                 supercontents |= SUPERCONTENTS_LAVA;
7343         if (nativecontents & CONTENTSQ3_BODY)
7344                 supercontents |= SUPERCONTENTS_BODY;
7345         if (nativecontents & CONTENTSQ3_CORPSE)
7346                 supercontents |= SUPERCONTENTS_CORPSE;
7347         if (nativecontents & CONTENTSQ3_NODROP)
7348                 supercontents |= SUPERCONTENTS_NODROP;
7349         if (nativecontents & CONTENTSQ3_PLAYERCLIP)
7350                 supercontents |= SUPERCONTENTS_PLAYERCLIP;
7351         if (nativecontents & CONTENTSQ3_MONSTERCLIP)
7352                 supercontents |= SUPERCONTENTS_MONSTERCLIP;
7353         if (nativecontents & CONTENTSQ3_DONOTENTER)
7354                 supercontents |= SUPERCONTENTS_DONOTENTER;
7355         if (nativecontents & CONTENTSQ3_BOTCLIP)
7356                 supercontents |= SUPERCONTENTS_BOTCLIP;
7357         if (!(nativecontents & CONTENTSQ3_TRANSLUCENT))
7358                 supercontents |= SUPERCONTENTS_OPAQUE;
7359         return supercontents;
7360 }
7361
7362 static int Mod_Q3BSP_NativeContentsFromSuperContents(int supercontents)
7363 {
7364         int nativecontents = 0;
7365         if (supercontents & SUPERCONTENTS_SOLID)
7366                 nativecontents |= CONTENTSQ3_SOLID;
7367         if (supercontents & SUPERCONTENTS_WATER)
7368                 nativecontents |= CONTENTSQ3_WATER;
7369         if (supercontents & SUPERCONTENTS_SLIME)
7370                 nativecontents |= CONTENTSQ3_SLIME;
7371         if (supercontents & SUPERCONTENTS_LAVA)
7372                 nativecontents |= CONTENTSQ3_LAVA;
7373         if (supercontents & SUPERCONTENTS_BODY)
7374                 nativecontents |= CONTENTSQ3_BODY;
7375         if (supercontents & SUPERCONTENTS_CORPSE)
7376                 nativecontents |= CONTENTSQ3_CORPSE;
7377         if (supercontents & SUPERCONTENTS_NODROP)
7378                 nativecontents |= CONTENTSQ3_NODROP;
7379         if (supercontents & SUPERCONTENTS_PLAYERCLIP)
7380                 nativecontents |= CONTENTSQ3_PLAYERCLIP;
7381         if (supercontents & SUPERCONTENTS_MONSTERCLIP)
7382                 nativecontents |= CONTENTSQ3_MONSTERCLIP;
7383         if (supercontents & SUPERCONTENTS_DONOTENTER)
7384                 nativecontents |= CONTENTSQ3_DONOTENTER;
7385         if (supercontents & SUPERCONTENTS_BOTCLIP)
7386                 nativecontents |= CONTENTSQ3_BOTCLIP;
7387         if (!(supercontents & SUPERCONTENTS_OPAQUE))
7388                 nativecontents |= CONTENTSQ3_TRANSLUCENT;
7389         return nativecontents;
7390 }
7391
7392 static void Mod_Q3BSP_RecursiveFindNumLeafs(mnode_t *node)
7393 {
7394         int numleafs;
7395         while (node->plane)
7396         {
7397                 Mod_Q3BSP_RecursiveFindNumLeafs(node->children[0]);
7398                 node = node->children[1];
7399         }
7400         numleafs = ((mleaf_t *)node - loadmodel->brush.data_leafs) + 1;
7401         if (loadmodel->brush.num_leafs < numleafs)
7402                 loadmodel->brush.num_leafs = numleafs;
7403 }
7404
7405 static void Mod_Q3BSP_Load(model_t *mod, void *buffer, void *bufferend)
7406 {
7407         int i, j, lumps;
7408         q3dheader_t *header;
7409         float corner[3], yawradius, modelradius;
7410
7411         mod->modeldatatypestring = "Q3BSP";
7412
7413         mod->type = mod_brushq3;
7414         mod->brush.ishlbsp = false;
7415         mod->brush.isbsp2rmqe = false;
7416         mod->brush.isbsp2 = false;
7417         mod->brush.isq2bsp = false;
7418         mod->brush.isq3bsp = true;
7419         mod->brush.skymasking = true;
7420         mod->numframes = 2; // although alternate textures are not supported it is annoying to complain about no such frame 1
7421         mod->numskins = 1;
7422
7423         header = (q3dheader_t *)buffer;
7424         if((char *) bufferend < (char *) buffer + sizeof(q3dheader_t))
7425                 Host_Error("Mod_Q3BSP_Load: %s is smaller than its header", mod->name);
7426
7427         i = LittleLong(header->version);
7428         if (i != Q3BSPVERSION && i != Q3BSPVERSION_IG && i != Q3BSPVERSION_LIVE)
7429                 Host_Error("Mod_Q3BSP_Load: %s has wrong version number (%i, should be %i)", mod->name, i, Q3BSPVERSION);
7430
7431         mod->soundfromcenter = true;
7432         mod->TraceBox = Mod_CollisionBIH_TraceBox;
7433         mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
7434         mod->TraceLine = Mod_CollisionBIH_TraceLine;
7435         mod->TracePoint = Mod_CollisionBIH_TracePoint;
7436         mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
7437         mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
7438         mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight;
7439         mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents;
7440         mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents;
7441         mod->brush.GetPVS = Mod_BSP_GetPVS;
7442         mod->brush.FatPVS = Mod_BSP_FatPVS;
7443         mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
7444         mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
7445         mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
7446         mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
7447         mod->brush.LightPoint = Mod_Q3BSP_LightPoint;
7448         mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
7449         mod->brush.AmbientSoundLevelsForPoint = NULL;
7450         mod->brush.RoundUpToHullSize = NULL;
7451         mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
7452         mod->Draw = R_Mod_Draw;
7453         mod->DrawDepth = R_Mod_DrawDepth;
7454         mod->DrawDebug = R_Mod_DrawDebug;
7455         mod->DrawPrepass = R_Mod_DrawPrepass;
7456         mod->GetLightInfo = R_Mod_GetLightInfo;
7457         mod->CompileShadowMap = R_Mod_CompileShadowMap;
7458         mod->DrawShadowMap = R_Mod_DrawShadowMap;
7459         mod->DrawLight = R_Mod_DrawLight;
7460
7461         mod_base = (unsigned char *)header;
7462
7463         // swap all the lumps
7464         header->ident = LittleLong(header->ident);
7465         header->version = LittleLong(header->version);
7466         lumps = (header->version == Q3BSPVERSION_LIVE) ? Q3HEADER_LUMPS_LIVE : Q3HEADER_LUMPS;
7467         for (i = 0;i < lumps;i++)
7468         {
7469                 j = (header->lumps[i].fileofs = LittleLong(header->lumps[i].fileofs));
7470                 if((char *) bufferend < (char *) buffer + j)
7471                         Host_Error("Mod_Q3BSP_Load: %s has a lump that starts outside the file!", mod->name);
7472                 j += (header->lumps[i].filelen = LittleLong(header->lumps[i].filelen));
7473                 if((char *) bufferend < (char *) buffer + j)
7474                         Host_Error("Mod_Q3BSP_Load: %s has a lump that ends outside the file!", mod->name);
7475         }
7476         /*
7477          * NO, do NOT clear them!
7478          * they contain actual data referenced by other stuff.
7479          * Instead, before using the advertisements lump, check header->versio
7480          * again!
7481          * Sorry, but otherwise it breaks memory of the first lump.
7482         for (i = lumps;i < Q3HEADER_LUMPS_MAX;i++)
7483         {
7484                 header->lumps[i].fileofs = 0;
7485                 header->lumps[i].filelen = 0;
7486         }
7487         */
7488
7489         mod->brush.qw_md4sum = 0;
7490         mod->brush.qw_md4sum2 = 0;
7491         for (i = 0;i < lumps;i++)
7492         {
7493                 if (i == Q3LUMP_ENTITIES)
7494                         continue;
7495                 mod->brush.qw_md4sum ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7496                 if (i == Q3LUMP_PVS || i == Q3LUMP_LEAFS || i == Q3LUMP_NODES)
7497                         continue;
7498                 mod->brush.qw_md4sum2 ^= Com_BlockChecksum(mod_base + header->lumps[i].fileofs, header->lumps[i].filelen);
7499
7500                 // all this checksumming can take a while, so let's send keepalives here too
7501                 CL_KeepaliveMessage(false);
7502         }
7503
7504         // allocate a texture pool if we need it
7505         if (mod->texturepool == NULL)
7506                 mod->texturepool = R_AllocTexturePool();
7507
7508         Mod_Q3BSP_LoadEntities(&header->lumps[Q3LUMP_ENTITIES]);
7509         Mod_Q3BSP_LoadTextures(&header->lumps[Q3LUMP_TEXTURES]);
7510         Mod_Q3BSP_LoadPlanes(&header->lumps[Q3LUMP_PLANES]);
7511         if (header->version == Q3BSPVERSION_IG)
7512                 Mod_Q3BSP_LoadBrushSides_IG(&header->lumps[Q3LUMP_BRUSHSIDES]);
7513         else
7514                 Mod_Q3BSP_LoadBrushSides(&header->lumps[Q3LUMP_BRUSHSIDES]);
7515         Mod_Q3BSP_LoadBrushes(&header->lumps[Q3LUMP_BRUSHES]);
7516         Mod_Q3BSP_LoadEffects(&header->lumps[Q3LUMP_EFFECTS]);
7517         Mod_Q3BSP_LoadVertices(&header->lumps[Q3LUMP_VERTICES]);
7518         Mod_Q3BSP_LoadTriangles(&header->lumps[Q3LUMP_TRIANGLES]);
7519         Mod_Q3BSP_LoadLightmaps(&header->lumps[Q3LUMP_LIGHTMAPS], &header->lumps[Q3LUMP_FACES]);
7520         Mod_Q3BSP_LoadFaces(&header->lumps[Q3LUMP_FACES]);
7521         Mod_Q3BSP_LoadModels(&header->lumps[Q3LUMP_MODELS]);
7522         Mod_Q3BSP_LoadLeafBrushes(&header->lumps[Q3LUMP_LEAFBRUSHES]);
7523         Mod_Q3BSP_LoadLeafFaces(&header->lumps[Q3LUMP_LEAFFACES]);
7524         Mod_Q3BSP_LoadLeafs(&header->lumps[Q3LUMP_LEAFS]);
7525         Mod_Q3BSP_LoadNodes(&header->lumps[Q3LUMP_NODES]);
7526         Mod_Q3BSP_LoadLightGrid(&header->lumps[Q3LUMP_LIGHTGRID]);
7527         Mod_Q3BSP_LoadPVS(&header->lumps[Q3LUMP_PVS]);
7528         loadmodel->brush.numsubmodels = loadmodel->brushq3.num_models;
7529
7530         // the MakePortals code works fine on the q3bsp data as well
7531         if (mod_bsp_portalize.integer && cls.state != ca_dedicated)
7532                 Mod_BSP_MakePortals();
7533
7534         // FIXME: shader alpha should replace r_wateralpha support in q3bsp
7535         loadmodel->brush.supportwateralpha = true;
7536
7537         loadmodel->brush.num_leafs = 0;
7538         Mod_Q3BSP_RecursiveFindNumLeafs(loadmodel->brush.data_nodes);
7539
7540         if (loadmodel->brush.numsubmodels)
7541                 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
7542
7543         mod = loadmodel;
7544         mod->modelsurfaces_sorted = (int*)Mem_Alloc(loadmodel->mempool, mod->num_surfaces * sizeof(*mod->modelsurfaces_sorted));
7545         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
7546         {
7547                 if (i > 0)
7548                 {
7549                         char name[10];
7550                         // duplicate the basic information
7551                         dpsnprintf(name, sizeof(name), "*%i", i);
7552                         mod = Mod_FindName(name, loadmodel->name);
7553                         // copy the base model to this one
7554                         *mod = *loadmodel;
7555                         // rename the clone back to its proper name
7556                         dp_strlcpy(mod->name, name, sizeof(mod->name));
7557                         mod->brush.parentmodel = loadmodel;
7558                         // textures and memory belong to the main model
7559                         mod->texturepool = NULL;
7560                         mod->mempool = NULL;
7561                         mod->brush.GetPVS = NULL;
7562                         mod->brush.FatPVS = NULL;
7563                         mod->brush.BoxTouchingPVS = NULL;
7564                         mod->brush.BoxTouchingLeafPVS = NULL;
7565                         mod->brush.BoxTouchingVisibleLeafs = NULL;
7566                         mod->brush.FindBoxClusters = NULL;
7567                         mod->brush.LightPoint = NULL;
7568                         mod->brush.AmbientSoundLevelsForPoint = NULL;
7569                 }
7570                 mod->brush.submodel = i;
7571                 if (loadmodel->brush.submodels)
7572                         loadmodel->brush.submodels[i] = mod;
7573
7574                 // make the model surface list (used by shadowing/lighting)
7575                 mod->submodelsurfaces_start = mod->brushq3.data_models[i].firstface;
7576                 mod->submodelsurfaces_end = mod->brushq3.data_models[i].firstface + mod->brushq3.data_models[i].numfaces;
7577                 mod->firstmodelbrush = mod->brushq3.data_models[i].firstbrush;
7578                 mod->nummodelbrushes = mod->brushq3.data_models[i].numbrushes;
7579
7580                 VectorCopy(mod->brushq3.data_models[i].mins, mod->normalmins);
7581                 VectorCopy(mod->brushq3.data_models[i].maxs, mod->normalmaxs);
7582                 // enlarge the bounding box to enclose all geometry of this model,
7583                 // because q3map2 sometimes lies (mostly to affect the lightgrid),
7584                 // which can in turn mess up the farclip (as well as culling when
7585                 // outside the level - an unimportant concern)
7586
7587                 //printf("Editing model %d... BEFORE re-bounding: %f %f %f - %f %f %f\n", i, mod->normalmins[0], mod->normalmins[1], mod->normalmins[2], mod->normalmaxs[0], mod->normalmaxs[1], mod->normalmaxs[2]);
7588                 for (j = mod->submodelsurfaces_start;j < mod->submodelsurfaces_end;j++)
7589                 {
7590                         const msurface_t *surface = mod->data_surfaces + j;
7591                         const float *v = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
7592                         int k;
7593                         if (!surface->num_vertices)
7594                                 continue;
7595                         for (k = 0;k < surface->num_vertices;k++, v += 3)
7596                         {
7597                                 mod->normalmins[0] = min(mod->normalmins[0], v[0]);
7598                                 mod->normalmins[1] = min(mod->normalmins[1], v[1]);
7599                                 mod->normalmins[2] = min(mod->normalmins[2], v[2]);
7600                                 mod->normalmaxs[0] = max(mod->normalmaxs[0], v[0]);
7601                                 mod->normalmaxs[1] = max(mod->normalmaxs[1], v[1]);
7602                                 mod->normalmaxs[2] = max(mod->normalmaxs[2], v[2]);
7603                         }
7604                 }
7605                 //printf("Editing model %d... AFTER re-bounding: %f %f %f - %f %f %f\n", i, mod->normalmins[0], mod->normalmins[1], mod->normalmins[2], mod->normalmaxs[0], mod->normalmaxs[1], mod->normalmaxs[2]);
7606                 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
7607                 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
7608                 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
7609                 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
7610                 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
7611                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
7612                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
7613                 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
7614                 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
7615                 mod->yawmins[2] = mod->normalmins[2];
7616                 mod->yawmaxs[2] = mod->normalmaxs[2];
7617                 mod->radius = modelradius;
7618                 mod->radius2 = modelradius * modelradius;
7619
7620                 Mod_SetDrawSkyAndWater(mod);
7621                 Mod_MakeCollisionBIH(mod, false, &mod->collision_bih);
7622                 Mod_MakeCollisionBIH(mod, true, &mod->render_bih);
7623
7624                 // generate VBOs and other shared data before cloning submodels
7625                 if (i == 0)
7626                         Mod_BuildVBOs();
7627         }
7628         mod = loadmodel;
7629
7630         // make the model surface list (used by shadowing/lighting)
7631         Mod_MakeSortedSurfaces(loadmodel);
7632
7633         if (mod_q3bsp_sRGBlightmaps.integer)
7634         {
7635                 if (vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
7636                 {
7637                         // actually we do in sRGB fallback with sRGB lightmaps: Image_sRGBFloatFromLinear_Lightmap(Image_LinearFloatFromsRGBFloat(x))
7638                         // neutral point is at Image_sRGBFloatFromLinearFloat(0.5)
7639                         // so we need to map Image_sRGBFloatFromLinearFloat(0.5) to 0.5
7640                         // factor is 0.5 / Image_sRGBFloatFromLinearFloat(0.5)
7641                         //loadmodel->lightmapscale *= 0.679942f; // fixes neutral level
7642                 }
7643                 else // if this is NOT set, regular rendering looks right by this requirement anyway
7644                 {
7645                         /*
7646                         // we want color 1 to do the same as without sRGB
7647                         // so, we want to map 1 to Image_LinearFloatFromsRGBFloat(2) instead of to 2
7648                         loadmodel->lightmapscale *= 2.476923f; // fixes max level
7649                         */
7650
7651                         // neutral level 0.5 gets uploaded as sRGB and becomes Image_LinearFloatFromsRGBFloat(0.5)
7652                         // we need to undo that
7653                         loadmodel->lightmapscale *= 2.336f; // fixes neutral level
7654                 }
7655         }
7656
7657         Con_DPrintf("Stats for q3bsp model \"%s\": %i faces, %i nodes, %i leafs, %i clusters, %i clusterportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
7658 }
7659
7660 void Mod_IBSP_Load(model_t *mod, void *buffer, void *bufferend)
7661 {
7662         int i = LittleLong(((int *)buffer)[1]);
7663         if (i == Q3BSPVERSION || i == Q3BSPVERSION_IG || i == Q3BSPVERSION_LIVE)
7664                 Mod_Q3BSP_Load(mod,buffer, bufferend);
7665         else if (i == Q2BSPVERSION)
7666                 Mod_Q2BSP_Load(mod,buffer, bufferend);
7667         else
7668                 Host_Error("Mod_IBSP_Load: unknown/unsupported version %i", i);
7669 }
7670
7671 static void Mod_VBSP_LoadEntities(sizebuf_t *sb)
7672 {
7673         loadmodel->brush.entities = NULL;
7674         if (!sb->cursize)
7675                 return;
7676         loadmodel->brush.entities = (char *)Mem_Alloc(loadmodel->mempool, sb->cursize + 1);
7677         MSG_ReadBytes(sb, sb->cursize, (unsigned char *)loadmodel->brush.entities);
7678         loadmodel->brush.entities[sb->cursize] = 0;
7679 }
7680
7681 static void Mod_VBSP_LoadVertexes(sizebuf_t *sb)
7682 {
7683         mvertex_t       *out;
7684         int                     i, count;
7685         int                     structsize = 12;
7686
7687         if (sb->cursize % structsize)
7688                 Host_Error("Mod_VBSP_LoadVertexes: funny lump size in %s",loadmodel->name);
7689         count = sb->cursize / structsize;
7690         out = (mvertex_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(*out));
7691
7692         loadmodel->brushq1.vertexes = out;
7693         loadmodel->brushq1.numvertexes = count;
7694
7695         for ( i=0 ; i<count ; i++, out++)
7696         {
7697                 out->position[0] = MSG_ReadLittleFloat(sb);
7698                 out->position[1] = MSG_ReadLittleFloat(sb);
7699                 out->position[2] = MSG_ReadLittleFloat(sb);
7700         }
7701 }
7702
7703 static void Mod_VBSP_LoadEdges(sizebuf_t *sb)
7704 {
7705         medge_t *out;
7706         int     i, count;
7707         int             structsize = 4;
7708
7709         if (sb->cursize % structsize)
7710                 Host_Error("Mod_VBSP_LoadEdges: funny lump size in %s",loadmodel->name);
7711         count = sb->cursize / structsize;
7712         out = (medge_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
7713
7714         loadmodel->brushq1.edges = out;
7715         loadmodel->brushq1.numedges = count;
7716
7717         for ( i=0 ; i<count ; i++, out++)
7718         {
7719                 out->v[0] = (unsigned short)MSG_ReadLittleShort(sb);
7720                 out->v[1] = (unsigned short)MSG_ReadLittleShort(sb);
7721                 
7722                 if ((int)out->v[0] >= loadmodel->brushq1.numvertexes || (int)out->v[1] >= loadmodel->brushq1.numvertexes)
7723                 {
7724                         Con_Printf("Mod_VBSP_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);
7725                         if(!loadmodel->brushq1.numvertexes)
7726                                 Host_Error("Mod_VBSP_LoadEdges: %s has edges but no vertexes, cannot fix\n", loadmodel->name);
7727                                 
7728                         out->v[0] = 0;
7729                         out->v[1] = 0;
7730                 }
7731         }
7732 }
7733
7734 static void Mod_VBSP_LoadSurfedges(sizebuf_t *sb)
7735 {
7736         int             i;
7737         int structsize = 4;
7738
7739         if (sb->cursize % structsize)
7740                 Host_Error("Mod_VBSP_LoadSurfedges: funny lump size in %s",loadmodel->name);
7741         loadmodel->brushq1.numsurfedges = sb->cursize / structsize;
7742         loadmodel->brushq1.surfedges = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->brushq1.numsurfedges * sizeof(int));
7743
7744         for (i = 0;i < loadmodel->brushq1.numsurfedges;i++)
7745                 loadmodel->brushq1.surfedges[i] = MSG_ReadLittleLong(sb);
7746 }
7747
7748 static void Mod_VBSP_LoadTextures(sizebuf_t *sb)
7749 {
7750         Con_Printf(CON_WARN "Mod_VBSP_LoadTextures: Don't know how to do this yet\n");
7751 }
7752
7753 static void Mod_VBSP_LoadPlanes(sizebuf_t *sb)
7754 {
7755         int                     i;
7756         mplane_t        *out;
7757         int structsize = 20;
7758
7759         if (sb->cursize % structsize)
7760                 Host_Error("Mod_VBSP_LoadPlanes: funny lump size in %s", loadmodel->name);
7761         loadmodel->brush.num_planes = sb->cursize / structsize;
7762         loadmodel->brush.data_planes = out = (mplane_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_planes * sizeof(*out));
7763
7764         for (i = 0;i < loadmodel->brush.num_planes;i++, out++)
7765         {
7766                 out->normal[0] = MSG_ReadLittleFloat(sb);
7767                 out->normal[1] = MSG_ReadLittleFloat(sb);
7768                 out->normal[2] = MSG_ReadLittleFloat(sb);
7769                 out->dist = MSG_ReadLittleFloat(sb);
7770                 MSG_ReadLittleLong(sb); // type is not used, we use PlaneClassify
7771                 PlaneClassify(out);
7772         }
7773 }
7774
7775 static void Mod_VBSP_LoadTexinfo(sizebuf_t *sb)
7776 {
7777         mtexinfo_t *out;
7778         int i, j, k, count, miptex;
7779         int structsize = 72;
7780
7781         if (sb->cursize % structsize)
7782                 Host_Error("Mod_VBSP_LoadTexinfo: funny lump size in %s",loadmodel->name);
7783         count = sb->cursize / structsize;
7784         out = (mtexinfo_t *)Mem_Alloc(loadmodel->mempool, count * sizeof(*out));
7785
7786         loadmodel->brushq1.texinfo = out;
7787         loadmodel->brushq1.numtexinfo = count;
7788
7789         for (i = 0;i < count;i++, out++)
7790         {
7791                 for (k = 0;k < 2;k++)
7792                         for (j = 0;j < 4;j++)
7793                                 out->vecs[k][j] = MSG_ReadLittleFloat(sb);
7794
7795                 for (k = 0;k < 2;k++)
7796                         for (j = 0;j < 4;j++)
7797                                 MSG_ReadLittleFloat(sb); // TODO lightmapVecs
7798
7799                 out->q1flags = MSG_ReadLittleLong(sb);
7800                 miptex = MSG_ReadLittleLong(sb);
7801
7802                 if (out->q1flags & TEX_SPECIAL)
7803                 {
7804                         // if texture chosen is NULL or the shader needs a lightmap,
7805                         // force to notexture water shader
7806                         out->textureindex = loadmodel->num_textures - 1;
7807                 }
7808                 else
7809                 {
7810                         // if texture chosen is NULL, force to notexture
7811                         out->textureindex = loadmodel->num_textures - 2;
7812                 }
7813                 // see if the specified miptex is valid and try to use it instead
7814                 if (loadmodel->data_textures)
7815                 {
7816                         if ((unsigned int) miptex >= (unsigned int) loadmodel->num_textures)
7817                                 Con_Printf("error in model \"%s\": invalid miptex index %i(of %i)\n", loadmodel->name, miptex, loadmodel->num_textures);
7818                         else
7819                                 out->textureindex = miptex;
7820                 }
7821         }
7822 }
7823
7824 static void Mod_VBSP_LoadFaces(sizebuf_t *sb)
7825 {
7826         msurface_t *surface;
7827         int i, j, count, surfacenum, planenum, smax, tmax, ssize, tsize, firstedge, numedges, totalverts, totaltris, lightmapnumber, lightmapsize, totallightmapsamples, lightmapoffset, texinfoindex;
7828         float texmins[2], texmaxs[2], val;
7829         rtexture_t *lightmaptexture, *deluxemaptexture;
7830         char vabuf[1024];
7831         int structsize =  56;
7832
7833         if (sb->cursize % structsize)
7834                 Host_Error("Mod_VBSP_LoadFaces: funny lump size in %s",loadmodel->name);
7835         count = sb->cursize / structsize;
7836         loadmodel->data_surfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_t));
7837         loadmodel->data_surfaces_lightmapinfo = (msurface_lightmapinfo_t *)Mem_Alloc(loadmodel->mempool, count*sizeof(msurface_lightmapinfo_t));
7838
7839         loadmodel->num_surfaces = count;
7840
7841         loadmodel->brushq1.firstrender = true;
7842         loadmodel->brushq1.lightmapupdateflags = (unsigned char *)Mem_Alloc(loadmodel->mempool, count*sizeof(unsigned char));
7843
7844         totalverts = 0;
7845         totaltris = 0;
7846         for (surfacenum = 0;surfacenum < count;surfacenum++)
7847         {
7848                 numedges = BuffLittleShort(sb->data + structsize * surfacenum + 8);
7849                 totalverts += numedges;
7850                 totaltris += numedges - 2;
7851         }
7852
7853         Mod_AllocSurfMesh(loadmodel->mempool, totalverts, totaltris, true, false);
7854
7855         lightmaptexture = NULL;
7856         deluxemaptexture = r_texture_blanknormalmap;
7857         lightmapnumber = 0;
7858         lightmapsize = bound(256, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d);
7859         totallightmapsamples = 0;
7860
7861         totalverts = 0;
7862         totaltris = 0;
7863         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
7864         {
7865                 surface->lightmapinfo = loadmodel->data_surfaces_lightmapinfo + surfacenum;
7866                 planenum = (unsigned short)MSG_ReadLittleShort(sb);
7867                 /*side = */MSG_ReadLittleShort(sb); // TODO support onNode?
7868                 firstedge = MSG_ReadLittleLong(sb);
7869                 numedges = (unsigned short)MSG_ReadLittleShort(sb);
7870                 texinfoindex = (unsigned short)MSG_ReadLittleShort(sb);
7871                 MSG_ReadLittleLong(sb); // skipping over dispinfo and surfaceFogVolumeID, both short
7872                 for (i = 0;i < MAXLIGHTMAPS;i++)
7873                         surface->lightmapinfo->styles[i] = MSG_ReadByte(sb);
7874                 lightmapoffset = MSG_ReadLittleLong(sb);
7875
7876                 // FIXME: validate edges, texinfo, etc?
7877                 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)
7878                         Host_Error("Mod_VBSP_LoadFaces: invalid edge range (firstedge %i, numedges %i, model edges %i)", firstedge, numedges, loadmodel->brushq1.numsurfedges);
7879                 if ((unsigned int) texinfoindex >= (unsigned int) loadmodel->brushq1.numtexinfo)
7880                         Host_Error("Mod_VBSP_LoadFaces: invalid texinfo index %i(model has %i texinfos)", texinfoindex, loadmodel->brushq1.numtexinfo);
7881                 if ((unsigned int) planenum >= (unsigned int) loadmodel->brush.num_planes)
7882                         Host_Error("Mod_VBSP_LoadFaces: invalid plane index %i (model has %i planes)", planenum, loadmodel->brush.num_planes);
7883
7884                 surface->lightmapinfo->texinfo = loadmodel->brushq1.texinfo + texinfoindex;
7885                 surface->texture = loadmodel->data_textures + surface->lightmapinfo->texinfo->textureindex;
7886
7887                 // Q2BSP doesn't use lightmaps on sky or warped surfaces (water), but still has a lightofs of 0
7888                 if (lightmapoffset == 0 && (surface->texture->q2flags & (Q2SURF_SKY | Q2SURF_WARP)))
7889                         lightmapoffset = -1;
7890
7891                 //surface->flags = surface->texture->flags;
7892                 //if (LittleShort(in->side))
7893                 //      surface->flags |= SURF_PLANEBACK;
7894                 //surface->plane = loadmodel->brush.data_planes + planenum;
7895
7896                 surface->num_firstvertex = totalverts;
7897                 surface->num_vertices = numedges;
7898                 surface->num_firsttriangle = totaltris;
7899                 surface->num_triangles = numedges - 2;
7900                 totalverts += numedges;
7901                 totaltris += numedges - 2;
7902
7903                 // convert edges back to a normal polygon
7904                 for (i = 0;i < surface->num_vertices;i++)
7905                 {
7906                         int lindex = loadmodel->brushq1.surfedges[firstedge + i];
7907                         float s, t;
7908                         // note: the q1bsp format does not allow a 0 surfedge (it would have no negative counterpart)
7909                         if (lindex >= 0)
7910                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[lindex].v[0]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
7911                         else
7912                                 VectorCopy(loadmodel->brushq1.vertexes[loadmodel->brushq1.edges[-lindex].v[1]].position, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3);
7913                         s = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
7914                         t = DotProduct(((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
7915                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 0] = s / surface->texture->width;
7916                         (loadmodel->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[i * 2 + 1] = t / surface->texture->height;
7917                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = 0;
7918                         (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = 0;
7919                         (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = 0;
7920                 }
7921
7922                 for (i = 0;i < surface->num_triangles;i++)
7923                 {
7924                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 0] = 0 + surface->num_firstvertex;
7925                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 1] = i + 1 + surface->num_firstvertex;
7926                         (loadmodel->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[i * 3 + 2] = i + 2 + surface->num_firstvertex;
7927                 }
7928
7929                 // compile additional data about the surface geometry
7930                 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);
7931                 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);
7932                 BoxFromPoints(surface->mins, surface->maxs, surface->num_vertices, (loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex));
7933
7934                 // generate surface extents information
7935                 texmins[0] = texmaxs[0] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3];
7936                 texmins[1] = texmaxs[1] = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex), surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3];
7937                 for (i = 1;i < surface->num_vertices;i++)
7938                 {
7939                         for (j = 0;j < 2;j++)
7940                         {
7941                                 val = DotProduct((loadmodel->surfmesh.data_vertex3f + 3 * surface->num_firstvertex) + i * 3, surface->lightmapinfo->texinfo->vecs[j]) + surface->lightmapinfo->texinfo->vecs[j][3];
7942                                 texmins[j] = min(texmins[j], val);
7943                                 texmaxs[j] = max(texmaxs[j], val);
7944                         }
7945                 }
7946                 for (i = 0;i < 2;i++)
7947                 {
7948                         surface->lightmapinfo->texturemins[i] = (int) floor(texmins[i] / 16.0) * 16;
7949                         surface->lightmapinfo->extents[i] = (int) ceil(texmaxs[i] / 16.0) * 16 - surface->lightmapinfo->texturemins[i];
7950                 }
7951
7952                 smax = surface->lightmapinfo->extents[0] >> 4;
7953                 tmax = surface->lightmapinfo->extents[1] >> 4;
7954                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
7955                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
7956
7957                 // lighting info
7958                 surface->lightmaptexture = NULL;
7959                 surface->deluxemaptexture = r_texture_blanknormalmap;
7960                 if (lightmapoffset == -1)
7961                 {
7962                         surface->lightmapinfo->samples = NULL;
7963 #if 1
7964                         // give non-lightmapped water a 1x white lightmap
7965                         if (!loadmodel->brush.isq2bsp && surface->texture->name[0] == '*' && (surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) && ssize <= 256 && tsize <= 256)
7966                         {
7967                                 surface->lightmapinfo->samples = (unsigned char *)Mem_Alloc(loadmodel->mempool, ssize * tsize * 3);
7968                                 surface->lightmapinfo->styles[0] = 0;
7969                                 memset(surface->lightmapinfo->samples, 128, ssize * tsize * 3);
7970                         }
7971 #endif
7972                 }
7973                 else
7974                         surface->lightmapinfo->samples = loadmodel->brushq1.lightdata + lightmapoffset;
7975
7976                 // check if we should apply a lightmap to this
7977                 if (!(surface->lightmapinfo->texinfo->q1flags & TEX_SPECIAL) || surface->lightmapinfo->samples)
7978                 {
7979                         if (ssize > 256 || tsize > 256)
7980                                 Host_Error("Bad surface extents");
7981
7982                         if (lightmapsize < ssize)
7983                                 lightmapsize = ssize;
7984                         if (lightmapsize < tsize)
7985                                 lightmapsize = tsize;
7986
7987                         totallightmapsamples += ssize*tsize;
7988
7989                         // force lightmap upload on first time seeing the surface
7990                         //
7991                         // additionally this is used by the later code to see if a
7992                         // lightmap is needed on this surface (rather than duplicating the
7993                         // logic above)
7994                         loadmodel->brushq1.lightmapupdateflags[surfacenum] = true;
7995                         loadmodel->lit = true;
7996                 }
7997         }
7998
7999         // small maps (such as ammo boxes especially) don't need big lightmap
8000         // textures, so this code tries to guess a good size based on
8001         // totallightmapsamples (size of the lightmaps lump basically), as well as
8002         // trying to max out the size if there is a lot of lightmap data to store
8003         // additionally, never choose a lightmapsize that is smaller than the
8004         // largest surface encountered (as it would fail)
8005         i = lightmapsize;
8006         for (lightmapsize = 64; (lightmapsize < i) && (lightmapsize < bound(128, gl_max_lightmapsize.integer, (int)vid.maxtexturesize_2d)) && (totallightmapsamples > lightmapsize*lightmapsize); lightmapsize*=2)
8007                 ;
8008
8009         // now that we've decided the lightmap texture size, we can do the rest
8010         if (cls.state != ca_dedicated)
8011         {
8012                 int stainmapsize = 0;
8013                 mod_alloclightmap_state_t allocState;
8014
8015                 Mod_AllocLightmap_Init(&allocState, loadmodel->mempool, lightmapsize, lightmapsize);
8016                 for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
8017                 {
8018                         int iu, iv, lightmapx = 0, lightmapy = 0;
8019                         float u, v, ubase, vbase, uscale, vscale;
8020
8021                         if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
8022                                 continue;
8023
8024                         smax = surface->lightmapinfo->extents[0] >> 4;
8025                         tmax = surface->lightmapinfo->extents[1] >> 4;
8026                         ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
8027                         tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
8028                         stainmapsize += ssize * tsize * 3;
8029
8030                         if (!lightmaptexture || !Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy))
8031                         {
8032                                 // allocate a texture pool if we need it
8033                                 if (loadmodel->texturepool == NULL)
8034                                         loadmodel->texturepool = R_AllocTexturePool();
8035                                 // could not find room, make a new lightmap
8036                                 loadmodel->brushq3.num_mergedlightmaps = lightmapnumber + 1;
8037                                 loadmodel->brushq3.data_lightmaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_lightmaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_lightmaps[0]));
8038                                 loadmodel->brushq3.data_deluxemaps = (rtexture_t **)Mem_Realloc(loadmodel->mempool, loadmodel->brushq3.data_deluxemaps, loadmodel->brushq3.num_mergedlightmaps * sizeof(loadmodel->brushq3.data_deluxemaps[0]));
8039                                 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);
8040                                 if (loadmodel->brushq1.nmaplightdata)
8041                                         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);
8042                                 lightmapnumber++;
8043                                 Mod_AllocLightmap_Reset(&allocState);
8044                                 Mod_AllocLightmap_Block(&allocState, ssize, tsize, &lightmapx, &lightmapy);
8045                         }
8046                         surface->lightmaptexture = lightmaptexture;
8047                         surface->deluxemaptexture = deluxemaptexture;
8048                         surface->lightmapinfo->lightmaporigin[0] = lightmapx;
8049                         surface->lightmapinfo->lightmaporigin[1] = lightmapy;
8050
8051                         uscale = 1.0f / (float)lightmapsize;
8052                         vscale = 1.0f / (float)lightmapsize;
8053                         ubase = lightmapx * uscale;
8054                         vbase = lightmapy * vscale;
8055
8056                         for (i = 0;i < surface->num_vertices;i++)
8057                         {
8058                                 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);
8059                                 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);
8060                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 0] = u * uscale + ubase;
8061                                 (loadmodel->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[i * 2 + 1] = v * vscale + vbase;
8062                                 // LadyHavoc: calc lightmap data offset for vertex lighting to use
8063                                 iu = (int) u;
8064                                 iv = (int) v;
8065                                 (loadmodel->surfmesh.data_lightmapoffsets + surface->num_firstvertex)[i] = (bound(0, iv, tmax) * ssize + bound(0, iu, smax)) * 3;
8066                         }
8067                 }
8068
8069                 if (cl_stainmaps.integer)
8070                 {
8071                         // allocate stainmaps for permanent marks on walls and clear white
8072                         unsigned char *stainsamples = NULL;
8073                         stainsamples = (unsigned char *)Mem_Alloc(loadmodel->mempool, stainmapsize);
8074                         memset(stainsamples, 255, stainmapsize);
8075                         // assign pointers
8076                         for (surfacenum = 0, surface = loadmodel->data_surfaces;surfacenum < count;surfacenum++, surface++)
8077                         {
8078                                 if (!loadmodel->brushq1.lightmapupdateflags[surfacenum])
8079                                         continue;
8080                                 ssize = (surface->lightmapinfo->extents[0] >> 4) + 1;
8081                                 tsize = (surface->lightmapinfo->extents[1] >> 4) + 1;
8082                                 surface->lightmapinfo->stainsamples = stainsamples;
8083                                 stainsamples += ssize * tsize * 3;
8084                         }
8085                 }
8086         }
8087
8088         // generate ushort elements array if possible
8089         if (loadmodel->surfmesh.data_element3s)
8090                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8091                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8092 }
8093
8094 // Valve BSP loader
8095 // Cloudwalk: Wasn't sober when I wrote this. I screamed and ran away at the face loader
8096 void Mod_VBSP_Load(model_t *mod, void *buffer, void *bufferend)
8097 {
8098         static cvar_t *testing = NULL; // TEMPORARY
8099         int i;
8100         sizebuf_t sb;
8101         sizebuf_t lumpsb[HL2HEADER_LUMPS];
8102
8103         if(!testing || !testing->integer)
8104         {
8105                 if(!testing)
8106                         testing = Cvar_Get(&cvars_all, "mod_bsp_vbsptest", "0", CF_CLIENT | CF_SERVER, "uhhh");
8107                 Host_Error("Mod_VBSP_Load: not yet fully implemented. Change the now-generated \"mod_bsp_vbsptest\" to 1 if you wish to test this");
8108         }
8109         else
8110         {
8111
8112                 MSG_InitReadBuffer(&sb, (unsigned char *)buffer, (unsigned char *)bufferend - (unsigned char *)buffer);
8113
8114                 mod->type = mod_brushhl2;
8115
8116                 MSG_ReadLittleLong(&sb);
8117                 MSG_ReadLittleLong(&sb); // TODO version check
8118
8119                 mod->modeldatatypestring = "VBSP";
8120
8121                 // read lumps
8122                 for (i = 0; i < HL2HEADER_LUMPS; i++)
8123                 {
8124                         int offset = MSG_ReadLittleLong(&sb);
8125                         int size = MSG_ReadLittleLong(&sb);
8126                         MSG_ReadLittleLong(&sb); // TODO support version
8127                         MSG_ReadLittleLong(&sb); // TODO support ident
8128                         if (offset < 0 || offset + size > sb.cursize)
8129                                 Host_Error("Mod_VBSP_Load: %s has invalid lump %i (offset %i, size %i, file size %i)\n", mod->name, i, offset, size, (int)sb.cursize);
8130                         MSG_InitReadBuffer(&lumpsb[i], sb.data + offset, size);
8131                 }
8132
8133                 MSG_ReadLittleLong(&sb); // TODO support revision field
8134
8135                 mod->soundfromcenter = true;
8136                 mod->TraceBox = Mod_CollisionBIH_TraceBox;
8137                 mod->TraceBrush = Mod_CollisionBIH_TraceBrush;
8138                 mod->TraceLine = Mod_CollisionBIH_TraceLine;
8139                 mod->TracePoint = Mod_CollisionBIH_TracePoint;
8140                 mod->PointSuperContents = Mod_CollisionBIH_PointSuperContents;
8141                 mod->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
8142                 mod->brush.TraceLineOfSight = Mod_Q3BSP_TraceLineOfSight; // probably not correct
8143                 mod->brush.SuperContentsFromNativeContents = Mod_Q3BSP_SuperContentsFromNativeContents; // probably not correct
8144                 mod->brush.NativeContentsFromSuperContents = Mod_Q3BSP_NativeContentsFromSuperContents; // probably not correct
8145                 mod->brush.GetPVS = Mod_BSP_GetPVS;
8146                 mod->brush.FatPVS = Mod_BSP_FatPVS;
8147                 mod->brush.BoxTouchingPVS = Mod_BSP_BoxTouchingPVS;
8148                 mod->brush.BoxTouchingLeafPVS = Mod_BSP_BoxTouchingLeafPVS;
8149                 mod->brush.BoxTouchingVisibleLeafs = Mod_BSP_BoxTouchingVisibleLeafs;
8150                 mod->brush.FindBoxClusters = Mod_BSP_FindBoxClusters;
8151                 mod->brush.LightPoint = Mod_Q3BSP_LightPoint; // probably not correct
8152                 mod->brush.FindNonSolidLocation = Mod_BSP_FindNonSolidLocation;
8153                 mod->brush.AmbientSoundLevelsForPoint = NULL;
8154                 mod->brush.RoundUpToHullSize = NULL;
8155                 mod->brush.PointInLeaf = Mod_BSP_PointInLeaf;
8156                 mod->Draw = R_Mod_Draw;
8157                 mod->DrawDepth = R_Mod_DrawDepth;
8158                 mod->DrawDebug = R_Mod_DrawDebug;
8159                 mod->DrawPrepass = R_Mod_DrawPrepass;
8160                 mod->GetLightInfo = R_Mod_GetLightInfo;
8161                 mod->CompileShadowMap = R_Mod_CompileShadowMap;
8162                 mod->DrawShadowMap = R_Mod_DrawShadowMap;
8163                 mod->DrawLight = R_Mod_DrawLight;
8164
8165                 // allocate a texture pool if we need it
8166                 if (mod->texturepool == NULL)
8167                         mod->texturepool = R_AllocTexturePool();
8168
8169                 Mod_VBSP_LoadEntities(&lumpsb[HL2LUMP_ENTITIES]);
8170                 Mod_VBSP_LoadVertexes(&lumpsb[HL2LUMP_VERTEXES]);
8171                 Mod_VBSP_LoadEdges(&lumpsb[HL2LUMP_EDGES]);
8172                 Mod_VBSP_LoadSurfedges(&lumpsb[HL2LUMP_SURFEDGES]);
8173                 Mod_VBSP_LoadTextures(&lumpsb[HL2LUMP_TEXDATA/*?*/]);
8174                 //Mod_VBSP_LoadLighting(&lumpsb[HL2LUMP_LIGHTING]);
8175                 Mod_VBSP_LoadPlanes(&lumpsb[HL2LUMP_PLANES]);
8176                 Mod_VBSP_LoadTexinfo(&lumpsb[HL2LUMP_TEXINFO]);
8177
8178                 // AHHHHHHH
8179                 Mod_VBSP_LoadFaces(&lumpsb[HL2LUMP_FACES]);
8180         }
8181 }
8182
8183 void Mod_MAP_Load(model_t *mod, void *buffer, void *bufferend)
8184 {
8185         Host_Error("Mod_MAP_Load: not yet implemented");
8186 }
8187
8188 typedef struct objvertex_s
8189 {
8190         int nextindex;
8191         int submodelindex;
8192         int textureindex;
8193         float v[3];
8194         float vt[2];
8195         float vn[3];
8196 }
8197 objvertex_t;
8198
8199 static unsigned char nobsp_pvs[1] = {1};
8200
8201 void Mod_OBJ_Load(model_t *mod, void *buffer, void *bufferend)
8202 {
8203         const char *textbase = (char *)buffer, *text = textbase;
8204         char *s;
8205         char *argv[512];
8206         char line[1024];
8207         char materialname[MAX_QPATH];
8208         int i, j, l, numvertices, firstvertex, firsttriangle, elementindex, vertexindex, surfacevertices, surfacetriangles, surfaceelements, submodelindex = 0;
8209         int index1, index2, index3;
8210         objvertex_t vfirst, vprev, vcurrent;
8211         int argc;
8212         int linelen;
8213         int numtriangles = 0;
8214         int maxtriangles = 0;
8215         objvertex_t *vertices = NULL;
8216         int linenumber = 0;
8217         int maxtextures = 0, numtextures = 0, textureindex = 0;
8218         int maxv = 0, numv = 1;
8219         int maxvt = 0, numvt = 1;
8220         int maxvn = 0, numvn = 1;
8221         char *texturenames = NULL;
8222         float dist, modelradius, modelyawradius, yawradius;
8223         float *obj_v = NULL;
8224         float *obj_vt = NULL;
8225         float *obj_vn = NULL;
8226         float mins[3];
8227         float maxs[3];
8228         float corner[3];
8229         objvertex_t *thisvertex = NULL;
8230         int vertexhashindex;
8231         int *vertexhashtable = NULL;
8232         objvertex_t *vertexhashdata = NULL;
8233         objvertex_t *vdata = NULL;
8234         int vertexhashsize = 0;
8235         int vertexhashcount = 0;
8236         skinfile_t *skinfiles = NULL;
8237         unsigned char *data = NULL;
8238         int *submodelfirstsurface;
8239         msurface_t *tempsurface;
8240         msurface_t *tempsurfaces;
8241
8242         memset(&vfirst, 0, sizeof(vfirst));
8243         memset(&vprev, 0, sizeof(vprev));
8244         memset(&vcurrent, 0, sizeof(vcurrent));
8245
8246         dpsnprintf(materialname, sizeof(materialname), "%s", loadmodel->name);
8247
8248         loadmodel->modeldatatypestring = "OBJ";
8249
8250         loadmodel->type = mod_obj;
8251         loadmodel->soundfromcenter = true;
8252         loadmodel->TraceBox = Mod_CollisionBIH_TraceBox;
8253         loadmodel->TraceBrush = Mod_CollisionBIH_TraceBrush;
8254         loadmodel->TraceLine = Mod_CollisionBIH_TraceLine;
8255         loadmodel->TracePoint = Mod_CollisionBIH_TracePoint_Mesh;
8256         loadmodel->TraceLineAgainstSurfaces = Mod_CollisionBIH_TraceLine;
8257         loadmodel->PointSuperContents = Mod_CollisionBIH_PointSuperContents_Mesh;
8258         loadmodel->brush.TraceLineOfSight = NULL;
8259         loadmodel->brush.SuperContentsFromNativeContents = NULL;
8260         loadmodel->brush.NativeContentsFromSuperContents = NULL;
8261         loadmodel->brush.GetPVS = NULL;
8262         loadmodel->brush.FatPVS = NULL;
8263         loadmodel->brush.BoxTouchingPVS = NULL;
8264         loadmodel->brush.BoxTouchingLeafPVS = NULL;
8265         loadmodel->brush.BoxTouchingVisibleLeafs = NULL;
8266         loadmodel->brush.FindBoxClusters = NULL;
8267         loadmodel->brush.LightPoint = NULL;
8268         loadmodel->brush.FindNonSolidLocation = NULL;
8269         loadmodel->brush.AmbientSoundLevelsForPoint = NULL;
8270         loadmodel->brush.RoundUpToHullSize = NULL;
8271         loadmodel->brush.PointInLeaf = NULL;
8272         loadmodel->Draw = R_Mod_Draw;
8273         loadmodel->DrawDepth = R_Mod_DrawDepth;
8274         loadmodel->DrawDebug = R_Mod_DrawDebug;
8275         loadmodel->DrawPrepass = R_Mod_DrawPrepass;
8276         loadmodel->GetLightInfo = R_Mod_GetLightInfo;
8277         loadmodel->CompileShadowMap = R_Mod_CompileShadowMap;
8278         loadmodel->DrawShadowMap = R_Mod_DrawShadowMap;
8279         loadmodel->DrawLight = R_Mod_DrawLight;
8280
8281         skinfiles = Mod_LoadSkinFiles();
8282         if (loadmodel->numskins < 1)
8283                 loadmodel->numskins = 1;
8284
8285         // make skinscenes for the skins (no groups)
8286         loadmodel->skinscenes = (animscene_t *)Mem_Alloc(loadmodel->mempool, sizeof(animscene_t) * loadmodel->numskins);
8287         for (i = 0;i < loadmodel->numskins;i++)
8288         {
8289                 loadmodel->skinscenes[i].firstframe = i;
8290                 loadmodel->skinscenes[i].framecount = 1;
8291                 loadmodel->skinscenes[i].loop = true;
8292                 loadmodel->skinscenes[i].framerate = 10;
8293         }
8294
8295         VectorClear(mins);
8296         VectorClear(maxs);
8297
8298         // we always have model 0, i.e. the first "submodel"
8299         loadmodel->brush.numsubmodels = 1;
8300
8301         // parse the OBJ text now
8302         for(;;)
8303         {
8304                 static char emptyarg[1] = "";
8305                 if (!*text)
8306                         break;
8307                 linenumber++;
8308                 linelen = 0;
8309                 for (linelen = 0;text[linelen] && text[linelen] != '\r' && text[linelen] != '\n';linelen++)
8310                         line[linelen] = text[linelen];
8311                 line[linelen] = 0;
8312                 for (argc = 0;argc < 4;argc++)
8313                         argv[argc] = emptyarg;
8314                 argc = 0;
8315                 s = line;
8316                 while (*s == ' ' || *s == '\t')
8317                         s++;
8318                 while (*s)
8319                 {
8320                         argv[argc++] = s;
8321                         while (*s > ' ')
8322                                 s++;
8323                         if (!*s)
8324                                 break;
8325                         *s++ = 0;
8326                         while (*s == ' ' || *s == '\t')
8327                                 s++;
8328                 }
8329                 text += linelen;
8330                 if (*text == '\r')
8331                         text++;
8332                 if (*text == '\n')
8333                         text++;
8334                 if (!argc)
8335                         continue;
8336                 if (argv[0][0] == '#')
8337                         continue;
8338                 if (!strcmp(argv[0], "v"))
8339                 {
8340                         if (maxv <= numv)
8341                         {
8342                                 maxv = max(maxv * 2, 1024);
8343                                 obj_v = (float *)Mem_Realloc(tempmempool, obj_v, maxv * sizeof(float[3]));
8344                         }
8345                         if(mod_obj_orientation.integer)
8346                         {
8347                                 obj_v[numv*3+0] = atof(argv[1]);
8348                                 obj_v[numv*3+2] = atof(argv[2]);
8349                                 obj_v[numv*3+1] = atof(argv[3]);
8350                         }
8351                         else
8352                         {
8353                                 obj_v[numv*3+0] = atof(argv[1]);
8354                                 obj_v[numv*3+1] = atof(argv[2]);
8355                                 obj_v[numv*3+2] = atof(argv[3]);
8356                         }
8357                         numv++;
8358                 }
8359                 else if (!strcmp(argv[0], "vt"))
8360                 {
8361                         if (maxvt <= numvt)
8362                         {
8363                                 maxvt = max(maxvt * 2, 1024);
8364                                 obj_vt = (float *)Mem_Realloc(tempmempool, obj_vt, maxvt * sizeof(float[2]));
8365                         }
8366                         obj_vt[numvt*2+0] = atof(argv[1]);
8367                         obj_vt[numvt*2+1] = 1-atof(argv[2]);
8368                         numvt++;
8369                 }
8370                 else if (!strcmp(argv[0], "vn"))
8371                 {
8372                         if (maxvn <= numvn)
8373                         {
8374                                 maxvn = max(maxvn * 2, 1024);
8375                                 obj_vn = (float *)Mem_Realloc(tempmempool, obj_vn, maxvn * sizeof(float[3]));
8376                         }
8377                         if(mod_obj_orientation.integer)
8378                         {
8379                                 obj_vn[numvn*3+0] = atof(argv[1]);
8380                                 obj_vn[numvn*3+2] = atof(argv[2]);
8381                                 obj_vn[numvn*3+1] = atof(argv[3]);
8382                         }
8383                         else
8384                         {
8385                                 obj_vn[numvn*3+0] = atof(argv[1]);
8386                                 obj_vn[numvn*3+1] = atof(argv[2]);
8387                                 obj_vn[numvn*3+2] = atof(argv[3]);
8388                         }
8389                         numvn++;
8390                 }
8391                 else if (!strcmp(argv[0], "f"))
8392                 {
8393                         if (!numtextures)
8394                         {
8395                                 if (maxtextures <= numtextures)
8396                                 {
8397                                         maxtextures = max(maxtextures * 2, 256);
8398                                         texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8399                                 }
8400                                 textureindex = numtextures++;
8401                                 dp_strlcpy(texturenames + textureindex*MAX_QPATH, loadmodel->name, MAX_QPATH);
8402                         }
8403                         for (j = 1;j < argc;j++)
8404                         {
8405                                 index1 = atoi(argv[j]);
8406                                 while(argv[j][0] && argv[j][0] != '/')
8407                                         argv[j]++;
8408                                 if (argv[j][0])
8409                                         argv[j]++;
8410                                 index2 = atoi(argv[j]);
8411                                 while(argv[j][0] && argv[j][0] != '/')
8412                                         argv[j]++;
8413                                 if (argv[j][0])
8414                                         argv[j]++;
8415                                 index3 = atoi(argv[j]);
8416                                 // negative refers to a recent vertex
8417                                 // zero means not specified
8418                                 // positive means an absolute vertex index
8419                                 if (index1 < 0)
8420                                         index1 = numv - index1;
8421                                 if (index2 < 0)
8422                                         index2 = numvt - index2;
8423                                 if (index3 < 0)
8424                                         index3 = numvn - index3;
8425                                 vcurrent.nextindex = -1;
8426                                 vcurrent.textureindex = textureindex;
8427                                 vcurrent.submodelindex = submodelindex;
8428                                 if (obj_v && index1 >= 0 && index1 < numv)
8429                                         VectorCopy(obj_v + 3*index1, vcurrent.v);
8430                                 if (obj_vt && index2 >= 0 && index2 < numvt)
8431                                         Vector2Copy(obj_vt + 2*index2, vcurrent.vt);
8432                                 if (obj_vn && index3 >= 0 && index3 < numvn)
8433                                         VectorCopy(obj_vn + 3*index3, vcurrent.vn);
8434                                 if (numtriangles == 0)
8435                                 {
8436                                         VectorCopy(vcurrent.v, mins);
8437                                         VectorCopy(vcurrent.v, maxs);
8438                                 }
8439                                 else
8440                                 {
8441                                         mins[0] = min(mins[0], vcurrent.v[0]);
8442                                         mins[1] = min(mins[1], vcurrent.v[1]);
8443                                         mins[2] = min(mins[2], vcurrent.v[2]);
8444                                         maxs[0] = max(maxs[0], vcurrent.v[0]);
8445                                         maxs[1] = max(maxs[1], vcurrent.v[1]);
8446                                         maxs[2] = max(maxs[2], vcurrent.v[2]);
8447                                 }
8448                                 if (j == 1)
8449                                         vfirst = vcurrent;
8450                                 else if (j >= 3)
8451                                 {
8452                                         if (maxtriangles <= numtriangles)
8453                                         {
8454                                                 maxtriangles = max(maxtriangles * 2, 32768);
8455                                                 vertices = (objvertex_t*)Mem_Realloc(loadmodel->mempool, vertices, maxtriangles * sizeof(objvertex_t[3]));
8456                                         }
8457                                         if(mod_obj_orientation.integer)
8458                                         {
8459                                                 vertices[numtriangles*3+0] = vfirst;
8460                                                 vertices[numtriangles*3+1] = vprev;
8461                                                 vertices[numtriangles*3+2] = vcurrent;
8462                                         }
8463                                         else
8464                                         {
8465                                                 vertices[numtriangles*3+0] = vfirst;
8466                                                 vertices[numtriangles*3+2] = vprev;
8467                                                 vertices[numtriangles*3+1] = vcurrent;
8468                                         }
8469                                         numtriangles++;
8470                                 }
8471                                 vprev = vcurrent;
8472                         }
8473                 }
8474                 else if (!strcmp(argv[0], "o") || !strcmp(argv[0], "g"))
8475                 {
8476                         submodelindex = atof(argv[1]);
8477                         loadmodel->brush.numsubmodels = max(submodelindex + 1, loadmodel->brush.numsubmodels);
8478                 }
8479                 else if (!strcmp(argv[0], "usemtl"))
8480                 {
8481                         for (i = 0;i < numtextures;i++)
8482                                 if (!strcmp(texturenames+i*MAX_QPATH, argv[1]))
8483                                         break;
8484                         if (i < numtextures)
8485                                 textureindex = i;
8486                         else
8487                         {
8488                                 if (maxtextures <= numtextures)
8489                                 {
8490                                         maxtextures = max(maxtextures * 2, 256);
8491                                         texturenames = (char *)Mem_Realloc(loadmodel->mempool, texturenames, maxtextures * MAX_QPATH);
8492                                 }
8493                                 textureindex = numtextures++;
8494                                 dp_strlcpy(texturenames + textureindex*MAX_QPATH, argv[1], MAX_QPATH);
8495                         }
8496                 }
8497         }
8498
8499         // now that we have the OBJ data loaded as-is, we can convert it
8500
8501         // copy the model bounds, then enlarge the yaw and rotated bounds according to radius
8502         VectorCopy(mins, loadmodel->normalmins);
8503         VectorCopy(maxs, loadmodel->normalmaxs);
8504         dist = max(fabs(loadmodel->normalmins[0]), fabs(loadmodel->normalmaxs[0]));
8505         modelyawradius = max(fabs(loadmodel->normalmins[1]), fabs(loadmodel->normalmaxs[1]));
8506         modelyawradius = dist*dist+modelyawradius*modelyawradius;
8507         modelradius = max(fabs(loadmodel->normalmins[2]), fabs(loadmodel->normalmaxs[2]));
8508         modelradius = modelyawradius + modelradius * modelradius;
8509         modelyawradius = sqrt(modelyawradius);
8510         modelradius = sqrt(modelradius);
8511         loadmodel->yawmins[0] = loadmodel->yawmins[1] = -modelyawradius;
8512         loadmodel->yawmins[2] = loadmodel->normalmins[2];
8513         loadmodel->yawmaxs[0] = loadmodel->yawmaxs[1] =  modelyawradius;
8514         loadmodel->yawmaxs[2] = loadmodel->normalmaxs[2];
8515         loadmodel->rotatedmins[0] = loadmodel->rotatedmins[1] = loadmodel->rotatedmins[2] = -modelradius;
8516         loadmodel->rotatedmaxs[0] = loadmodel->rotatedmaxs[1] = loadmodel->rotatedmaxs[2] =  modelradius;
8517         loadmodel->radius = modelradius;
8518         loadmodel->radius2 = modelradius * modelradius;
8519
8520         // allocate storage for triangles
8521         loadmodel->surfmesh.data_element3i = (int *)Mem_Alloc(loadmodel->mempool, numtriangles * sizeof(int[3]));
8522         // allocate vertex hash structures to build an optimal vertex subset
8523         vertexhashsize = numtriangles*2;
8524         vertexhashtable = (int *)Mem_Alloc(loadmodel->mempool, sizeof(int) * vertexhashsize);
8525         memset(vertexhashtable, 0xFF, sizeof(int) * vertexhashsize);
8526         vertexhashdata = (objvertex_t *)Mem_Alloc(loadmodel->mempool, sizeof(*vertexhashdata) * numtriangles*3);
8527         vertexhashcount = 0;
8528
8529         // gather surface stats for assigning vertex/triangle ranges
8530         firstvertex = 0;
8531         firsttriangle = 0;
8532         elementindex = 0;
8533         loadmodel->num_surfaces = 0;
8534         // allocate storage for the worst case number of surfaces, later we resize
8535         tempsurfaces = (msurface_t *)Mem_Alloc(loadmodel->mempool, numtextures * loadmodel->brush.numsubmodels * sizeof(msurface_t));
8536         submodelfirstsurface = (int *)Mem_Alloc(loadmodel->mempool, (loadmodel->brush.numsubmodels+1) * sizeof(int));
8537         tempsurface = tempsurfaces;
8538         for (submodelindex = 0;submodelindex < loadmodel->brush.numsubmodels;submodelindex++)
8539         {
8540                 submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8541                 for (textureindex = 0;textureindex < numtextures;textureindex++)
8542                 {
8543                         for (vertexindex = 0;vertexindex < numtriangles*3;vertexindex++)
8544                         {
8545                                 thisvertex = vertices + vertexindex;
8546                                 if (thisvertex->submodelindex == submodelindex && thisvertex->textureindex == textureindex)
8547                                         break;
8548                         }
8549                         // skip the surface creation if there are no triangles for it
8550                         if (vertexindex == numtriangles*3)
8551                                 continue;
8552                         // create a surface for these vertices
8553                         surfacevertices = 0;
8554                         surfaceelements = 0;
8555                         // we hack in a texture index in the surface to be fixed up later...
8556                         tempsurface->texture = (texture_t *)((size_t)textureindex);
8557                         // calculate bounds as we go
8558                         VectorCopy(thisvertex->v, tempsurface->mins);
8559                         VectorCopy(thisvertex->v, tempsurface->maxs);
8560                         for (;vertexindex < numtriangles*3;vertexindex++)
8561                         {
8562                                 thisvertex = vertices + vertexindex;
8563                                 if (thisvertex->submodelindex != submodelindex)
8564                                         continue;
8565                                 if (thisvertex->textureindex != textureindex)
8566                                         continue;
8567                                 // add vertex to surface bounds
8568                                 tempsurface->mins[0] = min(tempsurface->mins[0], thisvertex->v[0]);
8569                                 tempsurface->mins[1] = min(tempsurface->mins[1], thisvertex->v[1]);
8570                                 tempsurface->mins[2] = min(tempsurface->mins[2], thisvertex->v[2]);
8571                                 tempsurface->maxs[0] = max(tempsurface->maxs[0], thisvertex->v[0]);
8572                                 tempsurface->maxs[1] = max(tempsurface->maxs[1], thisvertex->v[1]);
8573                                 tempsurface->maxs[2] = max(tempsurface->maxs[2], thisvertex->v[2]);
8574                                 // add the vertex if it is not found in the merged set, and
8575                                 // get its index (triangle element) for the surface
8576                                 vertexhashindex = (unsigned int)(thisvertex->v[0] * 3571 + thisvertex->v[0] * 1777 + thisvertex->v[0] * 457) % (unsigned int)vertexhashsize;
8577                                 for (i = vertexhashtable[vertexhashindex];i >= 0;i = vertexhashdata[i].nextindex)
8578                                 {
8579                                         vdata = vertexhashdata + i;
8580                                         if (vdata->submodelindex == thisvertex->submodelindex && vdata->textureindex == thisvertex->textureindex && VectorCompare(thisvertex->v, vdata->v) && VectorCompare(thisvertex->vn, vdata->vn) && Vector2Compare(thisvertex->vt, vdata->vt))
8581                                                 break;
8582                                 }
8583                                 if (i < 0)
8584                                 {
8585                                         i = vertexhashcount++;
8586                                         vdata = vertexhashdata + i;
8587                                         *vdata = *thisvertex;
8588                                         vdata->nextindex = vertexhashtable[vertexhashindex];
8589                                         vertexhashtable[vertexhashindex] = i;
8590                                         surfacevertices++;
8591                                 }
8592                                 loadmodel->surfmesh.data_element3i[elementindex++] = i;
8593                                 surfaceelements++;
8594                         }
8595                         surfacetriangles = surfaceelements / 3;
8596                         tempsurface->num_vertices = surfacevertices;
8597                         tempsurface->num_triangles = surfacetriangles;
8598                         tempsurface->num_firstvertex = firstvertex;
8599                         tempsurface->num_firsttriangle = firsttriangle;
8600                         firstvertex += tempsurface->num_vertices;
8601                         firsttriangle += tempsurface->num_triangles;
8602                         tempsurface++;
8603                         loadmodel->num_surfaces++;
8604                 }
8605         }
8606         submodelfirstsurface[submodelindex] = loadmodel->num_surfaces;
8607         numvertices = firstvertex;
8608         loadmodel->data_surfaces = (msurface_t *)Mem_Realloc(loadmodel->mempool, tempsurfaces, loadmodel->num_surfaces * sizeof(msurface_t));
8609         tempsurfaces = NULL;
8610
8611         // allocate storage for final mesh data
8612         loadmodel->num_textures = numtextures * loadmodel->numskins;
8613         loadmodel->num_texturesperskin = numtextures;
8614         data = (unsigned char *)Mem_Alloc(loadmodel->mempool, loadmodel->num_surfaces * sizeof(int) + loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t) + numtriangles * sizeof(int[3]) + (numvertices <= 65536 ? numtriangles * sizeof(unsigned short[3]) : 0) + numvertices * sizeof(float[14]) + loadmodel->brush.numsubmodels * sizeof(model_t *));
8615         loadmodel->brush.submodels = (model_t **)data;data += loadmodel->brush.numsubmodels * sizeof(model_t *);
8616         loadmodel->modelsurfaces_sorted = (int *)data;data += loadmodel->num_surfaces * sizeof(int);
8617         loadmodel->data_textures = (texture_t *)data;data += loadmodel->num_surfaces * loadmodel->numskins * sizeof(texture_t);
8618         loadmodel->surfmesh.num_vertices = numvertices;
8619         loadmodel->surfmesh.num_triangles = numtriangles;
8620         loadmodel->surfmesh.data_vertex3f = (float *)data;data += numvertices * sizeof(float[3]);
8621         loadmodel->surfmesh.data_svector3f = (float *)data;data += numvertices * sizeof(float[3]);
8622         loadmodel->surfmesh.data_tvector3f = (float *)data;data += numvertices * sizeof(float[3]);
8623         loadmodel->surfmesh.data_normal3f = (float *)data;data += numvertices * sizeof(float[3]);
8624         loadmodel->surfmesh.data_texcoordtexture2f = (float *)data;data += numvertices * sizeof(float[2]);
8625
8626         if (loadmodel->surfmesh.num_vertices <= 65536) {
8627                 loadmodel->surfmesh.data_element3s = (unsigned short *)data;data += loadmodel->surfmesh.num_triangles * sizeof(unsigned short[3]);
8628         }
8629
8630         for (j = 0;j < loadmodel->surfmesh.num_vertices;j++)
8631         {
8632                 VectorCopy(vertexhashdata[j].v, loadmodel->surfmesh.data_vertex3f + 3*j);
8633                 VectorCopy(vertexhashdata[j].vn, loadmodel->surfmesh.data_normal3f + 3*j);
8634                 Vector2Copy(vertexhashdata[j].vt, loadmodel->surfmesh.data_texcoordtexture2f + 2*j);
8635         }
8636
8637         // load the textures
8638         for (textureindex = 0;textureindex < numtextures;textureindex++)
8639                 Mod_BuildAliasSkinsFromSkinFiles(loadmodel->data_textures + textureindex, skinfiles, texturenames + textureindex*MAX_QPATH, texturenames + textureindex*MAX_QPATH);
8640         Mod_FreeSkinFiles(skinfiles);
8641
8642         // set the surface textures to their real values now that we loaded them...
8643         for (i = 0;i < loadmodel->num_surfaces;i++)
8644                 loadmodel->data_surfaces[i].texture = loadmodel->data_textures + (size_t)loadmodel->data_surfaces[i].texture;
8645
8646         // free data
8647         Mem_Free(vertices);
8648         Mem_Free(texturenames);
8649         Mem_Free(obj_v);
8650         Mem_Free(obj_vt);
8651         Mem_Free(obj_vn);
8652         Mem_Free(vertexhashtable);
8653         Mem_Free(vertexhashdata);
8654
8655         // compute all the mesh information that was not loaded from the file
8656         if (loadmodel->surfmesh.data_element3s)
8657                 for (i = 0;i < loadmodel->surfmesh.num_triangles*3;i++)
8658                         loadmodel->surfmesh.data_element3s[i] = loadmodel->surfmesh.data_element3i[i];
8659         Mod_ValidateElements(loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_element3s, loadmodel->surfmesh.num_triangles, 0, loadmodel->surfmesh.num_vertices, __FILE__, __LINE__);
8660         // generate normals if the file did not have them
8661         if (!VectorLength2(loadmodel->surfmesh.data_normal3f))
8662                 Mod_BuildNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_normal3f, r_smoothnormals_areaweighting.integer != 0);
8663         Mod_BuildTextureVectorsFromNormals(0, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->surfmesh.data_vertex3f, loadmodel->surfmesh.data_texcoordtexture2f, loadmodel->surfmesh.data_normal3f, loadmodel->surfmesh.data_element3i, loadmodel->surfmesh.data_svector3f, loadmodel->surfmesh.data_tvector3f, r_smoothnormals_areaweighting.integer != 0);
8664
8665         // if this is a worldmodel and has no BSP tree, create a fake one for the purpose
8666         loadmodel->brush.num_visleafs = 1;
8667         loadmodel->brush.num_leafs = 1;
8668         loadmodel->brush.num_nodes = 0;
8669         loadmodel->brush.num_leafsurfaces = loadmodel->num_surfaces;
8670         loadmodel->brush.data_leafs = (mleaf_t *)Mem_Alloc(loadmodel->mempool, loadmodel->brush.num_leafs * sizeof(mleaf_t));
8671         loadmodel->brush.data_nodes = (mnode_t *)loadmodel->brush.data_leafs;
8672         loadmodel->brush.num_pvsclusters = 1;
8673         loadmodel->brush.num_pvsclusterbytes = 1;
8674         loadmodel->brush.data_pvsclusters = nobsp_pvs;
8675         //if (loadmodel->num_nodes) loadmodel->data_nodes = (mnode_t *)Mem_Alloc(loadmodel->mempool, loadmodel->num_nodes * sizeof(mnode_t));
8676         //loadmodel->data_leafsurfaces = (int *)Mem_Alloc(loadmodel->mempool, loadmodel->num_leafsurfaces * sizeof(int));
8677         loadmodel->brush.data_leafsurfaces = loadmodel->modelsurfaces_sorted;
8678         VectorCopy(loadmodel->normalmins, loadmodel->brush.data_leafs->mins);
8679         VectorCopy(loadmodel->normalmaxs, loadmodel->brush.data_leafs->maxs);
8680         loadmodel->brush.data_leafs->combinedsupercontents = 0; // FIXME?
8681         loadmodel->brush.data_leafs->clusterindex = 0;
8682         loadmodel->brush.data_leafs->areaindex = 0;
8683         loadmodel->brush.data_leafs->numleafsurfaces = loadmodel->brush.num_leafsurfaces;
8684         loadmodel->brush.data_leafs->firstleafsurface = loadmodel->brush.data_leafsurfaces;
8685         loadmodel->brush.data_leafs->numleafbrushes = 0;
8686         loadmodel->brush.data_leafs->firstleafbrush = NULL;
8687         loadmodel->brush.supportwateralpha = true;
8688
8689         if (loadmodel->brush.numsubmodels)
8690                 loadmodel->brush.submodels = (model_t **)Mem_Alloc(loadmodel->mempool, loadmodel->brush.numsubmodels * sizeof(model_t *));
8691
8692         mod = loadmodel;
8693         for (i = 0;i < loadmodel->brush.numsubmodels;i++)
8694         {
8695                 if (i > 0)
8696                 {
8697                         char name[10];
8698                         // duplicate the basic information
8699                         dpsnprintf(name, sizeof(name), "*%i", i);
8700                         mod = Mod_FindName(name, loadmodel->name);
8701                         // copy the base model to this one
8702                         *mod = *loadmodel;
8703                         // rename the clone back to its proper name
8704                         dp_strlcpy(mod->name, name, sizeof(mod->name));
8705                         mod->brush.parentmodel = loadmodel;
8706                         // textures and memory belong to the main model
8707                         mod->texturepool = NULL;
8708                         mod->mempool = NULL;
8709                         mod->brush.GetPVS = NULL;
8710                         mod->brush.FatPVS = NULL;
8711                         mod->brush.BoxTouchingPVS = NULL;
8712                         mod->brush.BoxTouchingLeafPVS = NULL;
8713                         mod->brush.BoxTouchingVisibleLeafs = NULL;
8714                         mod->brush.FindBoxClusters = NULL;
8715                         mod->brush.LightPoint = NULL;
8716                         mod->brush.AmbientSoundLevelsForPoint = NULL;
8717                 }
8718                 mod->brush.submodel = i;
8719                 if (loadmodel->brush.submodels)
8720                         loadmodel->brush.submodels[i] = mod;
8721
8722                 // make the model surface list (used by shadowing/lighting)
8723                 mod->submodelsurfaces_start = submodelfirstsurface[i];
8724                 mod->submodelsurfaces_end = submodelfirstsurface[i+1];
8725                 mod->firstmodelbrush = 0;
8726                 mod->nummodelbrushes = 0;
8727
8728                 VectorClear(mod->normalmins);
8729                 VectorClear(mod->normalmaxs);
8730                 l = false;
8731                 for (j = mod->submodelsurfaces_start;j < mod->submodelsurfaces_end;j++)
8732                 {
8733                         const msurface_t *surface = mod->data_surfaces + j;
8734                         const float *v3f = mod->surfmesh.data_vertex3f + 3 * surface->num_firstvertex;
8735                         int k;
8736                         if (!surface->num_vertices)
8737                                 continue;
8738                         if (!l)
8739                         {
8740                                 l = true;
8741                                 VectorCopy(v3f, mod->normalmins);
8742                                 VectorCopy(v3f, mod->normalmaxs);
8743                         }
8744                         for (k = 0;k < surface->num_vertices;k++, v3f += 3)
8745                         {
8746                                 mod->normalmins[0] = min(mod->normalmins[0], v3f[0]);
8747                                 mod->normalmins[1] = min(mod->normalmins[1], v3f[1]);
8748                                 mod->normalmins[2] = min(mod->normalmins[2], v3f[2]);
8749                                 mod->normalmaxs[0] = max(mod->normalmaxs[0], v3f[0]);
8750                                 mod->normalmaxs[1] = max(mod->normalmaxs[1], v3f[1]);
8751                                 mod->normalmaxs[2] = max(mod->normalmaxs[2], v3f[2]);
8752                         }
8753                 }
8754                 corner[0] = max(fabs(mod->normalmins[0]), fabs(mod->normalmaxs[0]));
8755                 corner[1] = max(fabs(mod->normalmins[1]), fabs(mod->normalmaxs[1]));
8756                 corner[2] = max(fabs(mod->normalmins[2]), fabs(mod->normalmaxs[2]));
8757                 modelradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]+corner[2]*corner[2]);
8758                 yawradius = sqrt(corner[0]*corner[0]+corner[1]*corner[1]);
8759                 mod->rotatedmins[0] = mod->rotatedmins[1] = mod->rotatedmins[2] = -modelradius;
8760                 mod->rotatedmaxs[0] = mod->rotatedmaxs[1] = mod->rotatedmaxs[2] = modelradius;
8761                 mod->yawmaxs[0] = mod->yawmaxs[1] = yawradius;
8762                 mod->yawmins[0] = mod->yawmins[1] = -yawradius;
8763                 mod->yawmins[2] = mod->normalmins[2];
8764                 mod->yawmaxs[2] = mod->normalmaxs[2];
8765                 mod->radius = modelradius;
8766                 mod->radius2 = modelradius * modelradius;
8767
8768                 Mod_SetDrawSkyAndWater(mod);
8769
8770                 Mod_MakeCollisionBIH(mod, true, &mod->collision_bih);
8771                 mod->render_bih = mod->collision_bih;
8772
8773                 // generate VBOs and other shared data before cloning submodels
8774                 if (i == 0)
8775                         Mod_BuildVBOs();
8776         }
8777         mod = loadmodel;
8778         Mem_Free(submodelfirstsurface);
8779
8780         // make the model surface list (used by shadowing/lighting)
8781         Mod_MakeSortedSurfaces(loadmodel);
8782
8783         Con_DPrintf("Stats for obj model \"%s\": %i faces, %i nodes, %i leafs, %i clusters, %i clusterportals, mesh: %i vertices, %i triangles, %i surfaces\n", loadmodel->name, loadmodel->num_surfaces, loadmodel->brush.num_nodes, loadmodel->brush.num_leafs, mod->brush.num_pvsclusters, loadmodel->brush.num_portals, loadmodel->surfmesh.num_vertices, loadmodel->surfmesh.num_triangles, loadmodel->num_surfaces);
8784 }