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