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