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