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